Maven Spring WebApp HTTP Status 404 - spring

Try to run student_list.jsp and after running a I got HTTP Status 404.
Here I send photo of my maven project which is set up in Netbeans and the codes. Please for check if everything is set up right. I am the beginner in Spring.
Thanks
Code:
student_list.jsp
<%#page import="java.util.List"%>
<%#page import="cz.webapp.student.entity.Student"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%#taglib prefix="s" uri="http://www.springframework.org/tags"%>
<div>
<h2>List of Persons</h2>
<table title="List Of Persons" border="1">
<tr>
<th>Name</th>
<th>Age</th>
</tr>
<%
List<Student> studentList = (List)request.getAttribute("students");
for(Student student: studentList){
out.println("<tr>");
out.println("<td>" + student.getId() + "</td>");
out.println("<td>" + student.getName() + "</td>");
out.println("<td>" + student.getAge() + "</td>");
out.println("</tr>");
}
%>
</table>
</div>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>Spring MVC Application</display-name>
<servlet>
<servlet-name>StudentWebApp</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>StudentWebApp</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
StudentWebApp-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="cz.webapp.student" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
StudentController
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package cz.webapp.student.controllers;
import cz.webapp.student.entity.Student;
import cz.webapp.student.service.StudentService;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import org.springframework.web.bind.annotation.RequestParam;
/**
*
* #author Jenda
*/
#Controller
public class StudentController {
#Autowired
StudentService studentServiceImpl;
#RequestMapping(value="/students", method=GET)
public String showAllStudent(Map<String, Object> model){
List<Student> studentList = studentServiceImpl.findAll();
model.put("students", studentList);
return "student_list";
}
}

I THINK I may have found a problem. In your servlet.xml file, your base package seems wrong. Try this: <context:component-scan base-package="cz.webapp.student.*" />
Because I think Spring is looking for a package called cz.webapp.student when you have your package set to cz.webapp.student.controllers
There are a lot of causes for a 404 error and having a wrong base package is one of them, so I'm not exactly certain if this will fix it, but it's a good start.

Related

spring ModelAndView sending data to jsp but on webpage showing null

Hii Guys am new in spring and am learning spring mvc while I am facing this problem when I am sending data from the controller the jsp page shows object values as null. output and code attached please help me...
HomeController.java class
package springmvc.controller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
#Controller // Declaring this class is controller
public class HomeController
{
#RequestMapping("/home") // when we want to fire this method
public String home( Model model)
{
System.out.println("----------hello this home url -------");
model.addAttribute("name","Swapnil Rajendra Take");
model.addAttribute("Id","101");
List <String> friend = new ArrayList<String>();
friend.add("Swapnil");
friend.add("pooja ");
friend.add("abhijit");
friend.add("Onkar");
friend.add("shradhha");
friend.add("rohit");
model.addAttribute("f",friend);
return "index";
}
#RequestMapping("/about")
public String about()
{
System.out.println("this is about page ");
return "about";
}
#RequestMapping("Carier")
public String carrier() {
return "Carier";
}
/// Sending data with model and view
#RequestMapping("/help")
public ModelAndView help() { // we have return model and view object
System.out.println("This is help page ");
ModelAndView modelAndView=new ModelAndView(); // Creating model and view object.
// setting the data
modelAndView.addObject("name","Swapnil");
modelAndView.addObject("rollnumber", 1234 );
// Setting the view
modelAndView.setViewName("help");
return modelAndView;
}
}
help.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
import="java.util.*"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE HTML>
<HTML>
<head>
<meta charset="ISO-8859-1">
<title>help</title>
</head>
<body>
<h1> Hiieee This is help page ...</h1>
<%
String name= (String ) request.getAttribute("name");
Integer rollnumber= (Integer ) request.getAttribute("rollnumber");
%>
<h1> Hello My name is <%=name %></h1>
<h1> My ROllnumber is <%=rollnumber %></h1>
</body>
</html>
spring-servlet.xml file
<?xml version="1.0" encoding="UTF-8"?>
<!-- NameSpace -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd" >
<context:component-scan base-package="springmvc.controller"/> <!-- For Activating annotations
-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
name="viewResolver">
<!-- Configuring view Resolver -->
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
web.xml file
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<!-- Configure dispatcher servlet -->
<servlet>
<!-- Servlet declaration -->
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<!-- Servlet Mapping -->
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Folder Strucher
Output

Issue with Spring Form Tag in spring MVC

I am trying to build a simple application to create and update few records using spring MVC. But not able to proceed further as I am facing issue that my spring form tag has some error and I am not able to figure out since 2 days. error says:
java.lang.IllegalStateException: No WebApplicationContext found: not in a DispatcherServlet request and no ContextLoaderListener registered?
Few Doubts as well :
Why do I need ContextLoaderListener when I am using dispatcherServlet.
Every DispatcherServlet has its own or instantiates WebApplicationContext. Then why is the error saying its not available ?
Anything that I am missing, conceptually or programmatically ?
Welcome.jsp
<html>
<body>
<h2>Welcome to the ADStore Portal</h2>
Add Employee<br>
<!-- Update Employee -->
</body>
</html>
addEmp.jsp
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Add Employee</h1>
<form:form action = "/add" modelAttribute = "employee">
<table>
<tr>
<td>Name :</td>
<td><form:input path="empname"/>
</tr>
<tr>
<td>Id :</td>
<td><form:input path="empid"/>
</tr>
<tr>
<td>Designation :</td>
<td><form:input path="designation"/>
</tr>
<tr>
<td>Department :</td>
<td><form:input path="department"/>
</tr>
<tr>
<td><input type="submit" name="Submit"/></td>
</tr>
</table>
</form:form>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name>AD Store</display-name>
<servlet>
<servlet-name>adstore</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>adstore</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
adstore-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<mvc:annotation-driven/>
<context:annotation-config/>
<context:component-scan base-package="com.adstore" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
EmployeeController.java
package com.adstore.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.adstore.bean.Employee;
import com.adstore.dao.EmployeeDAO;
#Controller
public class EmployeeController {
private EmployeeDAO dao;
#RequestMapping(value="/add")
public ModelAndView saveEmployee(#ModelAttribute("employee") Employee emp) {
System.out.println("In saveEmployee");
dao.saveEmp(emp);
return new ModelAndView("viewEmployee","command",new Employee());
}
}
EmployeeDAO.java
package com.adstore.dao;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCallback;
import com.adstore.bean.Employee;
public class EmployeeDAO {
private JdbcTemplate jdbcTemplate;
public boolean saveEmp(final Employee emp) {
boolean result = false;
String query = "INSERT INTO ADSTORE VALUES(?,?,?,?)";
result = jdbcTemplate.execute(query, new PreparedStatementCallback<Boolean>() {
public Boolean doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
ps.setString(1, emp.getEmpName());
ps.setInt(2, emp.getEmpId());
ps.setString(3, emp.getDesignation());
ps.setString(4, emp.getDepartment());
return ps.execute();
}
});
return result;
}
}
Error Image::
No application context is found because the request is not being handled by the DispatcherServlet as you are going directly to the JSP page. Hence there is no required Spring infrastructure to process the form:form tags.
You should access the page using the url defined in the #Controller using #RequestMapping or its variants. Its not good practice to put the JSP pages in a location which makes them accessible directly by clients. Instead you should hide them in the /WEB-INF/ directory
According to your view resolver the jsp pages should reside in the /WEB-INF/views folder. Move the JSPs to this folder.
You need to add following code in your web.xml
<servlet-mapping>
<servlet-name>jsp</servlet-name>
<url-pattern>/WEB-INF/views/*</url-pattern>
</servlet-mapping>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-security.xml //if you need
/WEB-INF/adstore-servlet.xml
</param-value>
</context-param>
and about your doubts-
1- If you want to put your Servlet file with custom name or at your custom location, rather than the default naming convention [servletname]-servlet.xml and path under Web-INF/ ,then you can use ContextLoaderListener.
Basically you can isolate your root application context and web application context using ContextLoaderListner.
The config file mapped with context param will behave as root application context configuration. And config file mapped with dispatcher servlet will behave like web application context.
In any web application we may have multiple dispatcher servlets, so multiple web application contexts.
But in any web application we may have only one root application context that is shared with all web application contexts.
We should define our common services, entities, etc in root application context. And controllers, interceptors etc are in relevant web application context.
and for more information--
The blog, "Purpose of ContextLoaderListener – Spring MVC" gives a very good explanation.
The code which you have posted is absolutely working fine.
I don't get any exception what is posted here. But few pointers I can point it out.
Check your files in the project which should be exactly same as below
You can call directly call addEmp.jsp in the starting as replacing your code.
#RequestMapping(value = "/", method = RequestMethod.GET)
public String printWelcome(#ModelAttribute("employee") Employee emp) {
return "addEmp";
}
Hope it resolves. If still you are facing issue, commit code to github and share the link.

Whoops! Lost connection to undefined - Connection Lost Just After The Connection Established

For Last couple of days i have been trying spring 4 websocket . But There is a problem
I am using apache-tomcat-8 and this is not a maven project.
Here are my snippets
index.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Hello WebSocket</title>
<script type="text/javascript" src="./js/sockjs-0.3.4.js"></script>
<script type="text/javascript" src="./js/stomp.js"></script>
<script type="text/javascript">
var stompClient = null;
function setConnected(connected) {
document.getElementById('connect').disabled = connected;
document.getElementById('disconnect').disabled = !connected;
document.getElementById('conversationDiv').style.visibility = connected ? 'visible' : 'hidden';
document.getElementById('response').innerHTML = '';
}
function connect() {
var socket = new SockJS("<c:url value='/hello'/>");
stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
setConnected(true);
console.log('Connected: ' + frame);
window.alert('Connected: ' + frame);
stompClient.subscribe('/topic/greetings', function(greeting){
showGreeting(JSON.parse(greeting.body).content);
});
});
}
function disconnect() {
if (stompClient != null) {
stompClient.disconnect();
}
setConnected(false);
console.log("Disconnected");
}
function sendName() {
var name = document.getElementById('name').value;
stompClient.send("/app/hello", {}, JSON.stringify({ 'name': name }));
}
function showGreeting(message) {
var response = document.getElementById('response');
var p = document.createElement('p');
p.style.wordWrap = 'break-word';
p.appendChild(document.createTextNode(message));
response.appendChild(p);
}
</script>
</head>
<body>
<noscript><h2 style="color: #ff0000">Seems your browser doesn't support Javascript! Websocket relies on Javascript being enabled. Please enable
Javascript and reload this page!</h2></noscript>
<div>
<div>
<button id="connect" onclick='connect();'>Connect</button>
<button id="disconnect" disabled="disabled" onclick="disconnect();">Disconnect</button>
</div>
<div id="conversationDiv">
<label>What is your name?</label><input type="text" id="name" />
<button id="sendName" onclick="sendName();">Send</button>
<p id="response"></p>
</div>
</div>
</body>
</html>
WebSocketConfig.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:websocket="http://www.springframework.org/schema/websocket"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/websocket
http://www.springframework.org/schema/websocket/spring-websocket.xsd">
<websocket:message-broker application-destination-prefix="/app">
<websocket:stomp-endpoint path="/hello">
<websocket:sockjs/>
</websocket:stomp-endpoint>
<websocket:simple-broker prefix="/topic"/>
</websocket:message-broker>
</beans>
HelloMessage.java
package com.springws.test;
public class HelloMessage {
private String name;
public String getName() {
return name;
}
}
Greeting.java
package com.springws.test;
public class Greeting {
private String content;
public Greeting(String content) {
this.content = content;
}
public String getContent() {
return content;
}
}
GreetingController.java
package com.springws.test;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
#Controller
public class GreetingController {
#MessageMapping("/hello")
#SendTo("/topic/greetings")
public Greeting greeting(HelloMessage message) throws Exception {
System.out.println(message.getName());
return new Greeting("Hello, " + message.getName() + "!");
}
}
web.xml
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID"
version="3.0">
<display-name>CRUDWebAppMavenized</display-name>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value> /WEB-INF/WebSocketConfig.xml</param-value>
</context-param>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
spring-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<mvc:annotation-driven/>
<mvc:default-servlet-handler/>
<context:annotation-config />
<context:component-scan base-package="com.springws.test" />
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/"/>
<property name="suffix" value=".jsp"/>
</bean>
<tx:annotation-driven />
</beans>
WebSocketConfig.java
package com.springws.test;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
#Configuration
#ComponentScan(basePackages = {"com.springws.test"})
#EnableWebSocketMessageBroker
#EnableWebMvc
#Controller
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
#Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
#Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/hello").withSockJS();
}
}
Libraries
But in browser console
its giving the following output
Opening Web Socket...
stomp.js:145 Web Socket Opened...
stomp.js:145 >>> CONNECT
accept-version:1.1,1.0
heart-beat:10000,10000
Whoops! Lost connection to undefined
why its losing connection ?
I Found the Answer. I missed three libraries.
jackson-annotations-2.5.1.jar ,
jackson-core-2.5.1.jar ,
jackson-databind-2.5.1.jar
and i removed the old library jackson-annotations-2.1.2.jar and added these three libraries . And Now its workig like a deram

Spring 3 MVC extra #RequestMapping value getting appended to returned view

I have a view 'hi.jsp' with user name and password text fields. I need to submit 'hi.jsp' to 'LoginController.java'. If there is any error in the data submitted then 'LoginController.java' must redirect the request back to 'hi.jsp' (with text fields retaning the entered data) with respective error messages. After changing data and re-submitting 'hi.jsp' I get 404 error.
So the first submission is successful however problem occurs during second submission.
The source code of files is mentioned below:
hi.jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="s" %>
<%# page session="false" %>
<html>
<body>
<s:form method="POST" modelAttribute="loginObj" action="login/validatelogin">
<label for="userName">UserName</label>
<s:input path="userName" id="userName" size="15"/><br>
<div style="{color:red}"> <s:errors path="userName"></s:errors></div>
<label for="password">Password</label>
<s:input path="password" id="password" size="15" /><br>
<s:errors path="password"></s:errors>
<input name="submit" type="submit" value="login"/>
</s:form>
</body>
</html>
LoginController.java
package rajeev.spring.spitter.mvc.controller;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
#RequestMapping("/login")
public class LoginController {
#RequestMapping(value="/validatelogin", method=RequestMethod.POST)
public String validateLogin(#Valid #ModelAttribute("loginObj") LoginBean loginObj, BindingResult bindingResult)
{
System.out.println(bindingResult.hasErrors());
if(bindingResult.hasErrors())
{
return "hi";
}
return "home";
}
}
spitter-servlet.xml (spring configuration)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<mvc:annotation-driven/>
<context:component-scan base-package="rajeev.spring.spitter.mvc.controller"></context:component-scan>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>Spring Hello World</display-name>
<welcome-file-list>
<welcome-file>/</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>springDispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spitter-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springDispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
During the second submission of 'hi.jsp' tomcat log also displays a warning:
WARNING: No mapping found for HTTP request with URI [/SpringMVC/login/login/validatelogin] in DispatcherServlet with name 'springDispatcher'
It seems that during second submission of 'hi.jsp' an extra '/login' is getting appended to the submission path of the form.
Kindly suggest if something is wrong with above code or do I need to modify it to make it working.
Thanks for your help.
This is because the relative form post URL changed when you map your handler method into a different URL
<s:form method="POST" modelAttribute="loginObj" action="login/validatelogin">
Common solution to this problem is to use absolute path, but instead of hardcoding, lookup your context-path using
<c:set var="root" value="${pageContext.request.contextPath}"/>
Then on your form
<s:form method="POST" modelAttribute="loginObj" action="${root}/login/validatelogin">
Other option you might consider is to use Post-Redirect pattern in your controller handler method to avoid switching the URL
public String validateLogin(#Valid #ModelAttribute("loginObj") LoginBean loginObj, BindingResult bindingResult) {
....
return "redirect:/login";
}
Try this:
<c:url var="myAction" value="/login/validatelogin"/>
<s:form method="POST" modelAttribute="loginObj" action="${myAction}">

validation form using Spring 3

i'm creating validation form on Spring 3, My problem is, that i saw a lot of examples with validation form. I even created one. but my form passing "result.hasErrors()" method, even when there are errors.
My code is:
Controller:
package com.esb.sso;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import javax.servlet.http.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.validation.BindingResult;
import java.util.Map;
import javax.validation.Valid;
import com.esb.sso.form.LoginForm;
import javax.servlet.http.HttpServletRequest;
/**
* Handles requests for the application home page.
*/
#Controller
#RequestMapping(value = "/")
public class HomeController {
LoginForm loginForm = new LoginForm();
model.put("loginForm", loginForm);
return "home";
}
#RequestMapping(method = RequestMethod.POST)
public String validation(#Valid LoginForm loginForm, BindingResult result,
Map model) throws IOException {
logger.info("Login POST var");
logger.info(loginForm.getLogin());
logger.info(loginForm.getPassword());
if (result.hasErrors()) {
logger.info("error");
return "home";
}
model.put("loginForm", loginForm);
return "logged";
}
}
Validator:
package com.esb.sso.form;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class LoginForm {
#NotNull(message = "notNull")
#Size(min=1, max=50, message="mote charters")
private String login;
#NotNull(message = "notNull")
#Size(min=1, max=50, message="mote charters")
private String password;
public void setLogin(String login){
this.login = login;
}
public String getLogin(){
return login;
}
public void setPassword(String password){
this.password = password;
}
public String getPassword(){
return password;
}
}
View:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<title>Home</title>
</head>
<body>
Autoryzacja!!!
<form:form action="" commandName="loginForm">
<table>
<tr>
<td>User Name:<FONT color="red"><form:errors path="login" /></FONT></td>
</tr>
<tr>
<td><form:input path="login" /></td>
</tr>
<tr>
<td>Password:<FONT color="red"><form:errors path="password" /></FONT></td>
</tr>
<tr>
<td><form:password path="password" /></td>
</tr>
<tr>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>
</body>
</html>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
servlet-context:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="com.esb.sso" />
<beans:bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<beans:property name="basename" value="/WEB-INF/messages" />
</beans:bean>
</beans:beans>
and messages.properties:
NotNull.loginForm.login=must not be blank.
NotNull.loginForm.password=must not be blank.
Size.loginForm.login=Login size must be between 1 and 50 charters.
Size.loginForm.password=Password size must be between 1 and 50 charters.
I don't know where is the problem
Coul'd enybody help me ?
Assuming copy paste error in HomeController-get method of the "/" mapping method.
To answer your question - You must specify the LoginForm object as model attribute in order to bind validations on it with BindingResult. Below is the correct code
public String validation((#ModelAttribute("loginForm") #Valid LoginForm loginForm, BindingResult result,
Map model) throws IOException {
For reference see the documentation

Resources