Spring4 MVC form validation result.hasErrors() is always false - validation

I'm using validation-api-1.1.0.Final.jar to valid form input in Spring 4 MVC. But I'm stuck in here, the result.hasErrors() seems always false(it means #Valid doesn't work properly). I followed this guideValidating Form Input, but that guide validating form input using Spring Boot. I'm using Tomcat 8 instead of using Spring Boot. I've search a lot about this, but the issue still existed.
Seaking for help.
Thanks!
Project Structure:
UserController.java
package com.ro.user.controller;
import com.ro.user.model.UserModel;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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;
import javax.validation.Valid;
#Controller
public class UserController {
#RequestMapping(value = "/user", method = RequestMethod.GET)
public UserModel user(Model model) {
UserModel userModel = new UserModel();
model.addAttribute("userModel", userModel);
return userModel;
}
#RequestMapping(value = "/userLogin", method = RequestMethod.POST)
public String userLogin(#Valid #ModelAttribute("userModel") UserModel userModel, BindingResult bindingResult) {
System.out.println("Before: bindingResult.hasErrors()");
if (bindingResult.hasErrors()) {
System.out.println("After: bindingResult.hasErrors()");
return "user";
}
return "result";
}
}
UserModel.java
package com.ro.user.model;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class UserModel {
#NotNull
#Size(min = 6, max = 12)
private String username;
#Size(min = 8, max = 16)
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
user.jsp
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<html>
<head>
<title>Spring MVC Form Handling</title>
<style>
.error {
color: #ff0000;
}
.errorblock {
color: #000;
background-color: #ffEEEE;
border: 3px solid #ff0000;
padding: 8px;
margin: 16px;
}
</style>
</head>
<body>
<h2>User Information</h2>
<form:form action="userLogin" modelAttribute="userModel" method="POST">
<form:errors path="*" cssClass="errorblock" element="div"/>
<table>
<tr>
<td><form:label path="username">Username:</form:label></td>
<td><form:input path="username"/></td>
<td><form:errors path="username" cssClass="error"/></td>
</tr>
<tr>
<td><form:label path="password">Password:</form:label></td>
<td><form:input path="password"/></td>
<td><form:errors path="username" cssClass="error"/></td>
</tr>
<tr>
<td colspan="3">
<input type="submit" value="Submit"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>UserLogin</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>UserLogin</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
UserLogin-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"
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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<mvc:annotation-driven/>
<context:component-scan base-package="com.ro.user.controller"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<bean class="org.springframework.context.support.ResourceBundleMessageSource" id="messageSource">
<property name="basename" value="com.ro.user.model.error"/>
</bean>
</beans>

This issue is caused by lack of the dependency of Hibernate Validator. It is supposed to add all Jars in a folder named required to project's lib(download zip from the official website and unzip it, you will see this folder). Not just the hibernate-validator.jar and validation-api.jar.

I guess you've created a custom HandlerAdapter, then you need to initialize the webBinding manually.
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="webBindingInitializer">
<bean class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
<property name="validator" ref="validator"/>
</bean>
</property>
</bean>

I had the same issue. I resolved it by changing hibernate validator version. In my case, it worked with version 6.2 and it didn't work with version 7.

Related

Spring MVC Controller URL not mapped

I am trying to make simple project in Spring MVC,but getting this error :
WARNING: No mapping found for HTTP request with URI [/SpringMVCForm/login.htm] in DispatcherServlet with name 'springform'
HTTP Status 404 - Not Found.
Not able to get what I am missing. Please let me know.
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
<display-name>SpringMVCForm</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>springform</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springform</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
</web-app>
springform-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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<context:component-scan base-package="com.mvcform.*" />
<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
LoginController.java
package com.mvcform.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
#Controller
#RequestMapping("/login.htm")
public class LoginController {
#RequestMapping(method=RequestMethod.POST)
public ModelAndView processCredentials(#RequestParam("userId") String userId, #RequestParam("password") String password) {
String message = "Invalid Credentials";
if (userId != null && userId.length() >= 5) {
if (userId.equals(password)) {
//message = "Welcome " + userId + " !!!";
return new ModelAndView("redirect:/showform");
}
}
return new ModelAndView("index", "message", message);
}
}
index.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Spring MVC Form</title>
</head>
<body>
<h1> Index.jsp </h1>
<h1>Enter your user id and password</h1>
<form action="login.htm" method="post">
<table>
<tr>
<td> User Id </td>
<td> <input type="text" name="userId" /></td>
</tr>
<tr>
<td>Password </td>
<td> <input type="password" name="password" /></td>
</tr>
<tr>
<td>
<input type="submit" value="Submit" />
</td>
</tr>
</table>
</form>
</body>
</html>
I think Spring is not able to scan base package: com.mvcform.*
Please let me know what I am missing here.
1) if you configured correct then you must check the json format which you sending to server to save it may be wrong (refere the urlenter link description here)
2) please check your controller controller doesn't have this url "URI [/SpringMVCForm/login.htm]" you have only /login.htm url.
Remove
#RequestMapping("/login.htm")
and keep only
#RequestMapping("/login")
in controller

java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'configbean' available as request attribute

When try to run spring sample application using maven i have got the exception mentioned.
Here is my program
Firstpage1.jsp [present in Webcontent]
<html>
<head>
<title>Finacle data retriever</title>
</head>
<body>
<h2>Enter the configuration details</h2>
<form:form method="POST" action="/formexample/Configgen" commandName="configbean">
<table>
<tr>
<td><form:label path="tnu">Total number of Users</form:label></td>
<td><form:input path="tnu" /></td>
</tr>
<tr>
<td><form:label path="cnu">Concurrent number of Users</form:label></td>
<td><form:input path="cnu" /></td>
</tr>
<tr>
<td><form:label path="kat">Keep Alive Timeout</form:label></td>
<td><form:input path="kat" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>
</body>
</html>
result.jsp [ Webcontent/WEB-INF/jsp]
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Result page</title>
</head>
<body>
<h2> Result page information</h2>
<table>
<tr>
<td>Total Number of users</td>
<td>${congibean.tnc}</td>
</tr>
<tr>
<td>Concurrent Number of users</td>
<td>${congibean.cnu}</td>
</tr>
<tr>
<td>Keep alive timeout</td>
<td>${congibean.kat}</td>
</tr>
</table>
</body>
</html>
**spring dependencies are present in maven dependencies.**
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">
<jsp-config>
<taglib>
<taglib-uri>/WEB-INF/spring-form.tld</taglib-uri>
<taglib-location>spring-form.tld</taglib-location>
</taglib>
</jsp-config>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/formex-servlet.xml</param-value>
</context-param>
<welcome-file-list>
<welcome-file>Firstpage1.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>formex</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>formex</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
formex-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"
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-4.2.xsd">
<context:component-scan base-package="formexamplepack1"></context:component-scan>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
formexamplepack1 - package
configbean.java
package formexamplepack1;
public class configbean {
private int tuc;
private int cnu;
private int kat;
public int getTuc() {
return tuc;
}
public void setTuc(int tuc) {
this.tuc = tuc;
}
public int getCnu() {
return cnu;
}
public void setCnu(int cnu) {
this.cnu = cnu;
}
public int getKat() {
return kat;
}
public void setKat(int kat) {
this.kat = kat;
}
}
ConfigurationController.java
package formexamplepack1;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
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(value = "/Configgen")
public class ConfigurationController {
#RequestMapping(method=RequestMethod.GET)
public String showform(ModelMap model) {
configbean configbean=new configbean();
model.addAttribute("configbean",configbean);
return "Firstpage";
}
#RequestMapping(method=RequestMethod.POST)
public String getdetails(#ModelAttribute("configbean")configbean configbean,ModelMap model,BindingResult bindingResult){
model.addAttribute("tnu", configbean.getTuc());
model.addAttribute("cnu", configbean.getCnu());
model.addAttribute("kat",configbean.getKat());
return "result";
}
}
Help me in resolving the below exception. I have gone through all the answers but not able to figure out. Using java 1.8 and spring jars latest [4.2.6]
tomcat- 7.0.68
Below is the exception
org.apache.jasper.JasperException: java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'configbean' available as request attribute
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:556)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:472)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339)
javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'configbean' available as request attribute
org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:144)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:168)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:188)
org.springframework.web.servlet.tags.form.LabelTag.autogenerateFor(LabelTag.java:130)
org.springframework.web.servlet.tags.form.LabelTag.resolveFor(LabelTag.java:120)
org.springframework.web.servlet.tags.form.LabelTag.writeTagContent(LabelTag.java:90)
org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:84)
org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:80)
org.apache.jsp.Firstpage1_jsp._jspx_meth_form_005flabel_005f0(Firstpage1_jsp.java:216)
org.apache.jsp.Firstpage1_jsp._jspx_meth_form_005fform_005f0(Firstpage1_jsp.java:152)
org.apache.jsp.Firstpage1_jsp._jspService(Firstpage1_jsp.java:105)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:439)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339)
javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Try:
without ModelAttribute annotation
Binding Result direct after the command object
like:
#RequestMapping(method=RequestMethod.POST)
public String getdetails(configbean configbean, BindingResult bindingResult){
model.addAttribute("tnu", configbean.getTuc());
model.addAttribute("cnu", configbean.getCnu());
model.addAttribute("kat",configbean.getKat());
return "result";
}
you are trying to use ${congibean.tnc} in your result.jsp file , but you are not passing it as a model attribute . Instead you are trying to pass "tnu","cnu" and "kat" .
As a result it's giving you a jasper exception , as the compiler is unable to find any model attribute called "configbean" .
To solve this either pass only "configBean" as your model Attribute in the getdetails() method , or change your result.jsp file to use only "${tnc}", "${cnu}" and "${kat}"

java.lang.ClassCastException: while typecasting the command object in onSubmit method

I am beginner in spring3 so i am creating a simple login application. In my loginController i am getting "java.lang.ClassCastException: org.springframework.web.bind.support.SimpleSessionStatus cannot be cast to com.forms.LoginForm" on the following line
LoginForm login = (LoginForm)command;
For the reference code is as follows:
LoginController.java:-
package com.beans;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import com.Dao.LoginDaoUtil;
import com.forms.LoginForm;
#SuppressWarnings("deprecation")
#Controller
public class LoginController extends SimpleFormController {
public LoginController() {
setCommandClass(LoginForm.class);
}
#RequestMapping("/LoginAction")
protected ModelAndView onSubmit(Object command) {
try {
LoginForm login = (LoginForm) command;
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"SpringBlogger-servlet.xml");
LoginDaoUtil daoUtil = ctx.getBean("LoginDaoUtil",
LoginDaoUtil.class);
boolean isUserValid = daoUtil.isValidUser(login.getUsername(),
login.getPassword());
if (isUserValid)
return new ModelAndView("success").addObject("name",
login.getUsername());
else
return new ModelAndView("login", "loginForm", new LoginForm());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return new ModelAndView("login", "loginForm", new LoginForm());
}
}
}
login.jsp:-
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/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>${message}</h1>
<form:form action="LoginAction" method="post" commandName="loginForm">
Username:<form:input path="username"/>
<font color="red"><form:errors path="username"/></font><br/><br/>
Password:<form:password path="password"/>
<font color="red"><form:errors path="password"/></font><br/><br/>
<input type="submit" value="submit">
</form:form>
</body>
</html>
LoginForm.java:-
package com.forms;
public class LoginForm {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
HomeController.java:-
package com.beans;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import com.forms.LoginForm;
#Controller
public class HomeController {
#RequestMapping({"/","/home"})
public String showHomePage(ModelMap map){
map.addAttribute("message", "Welcome to Spring Blogger");
map.addAttribute("loginForm", new LoginForm());
return "login";
}
}
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_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>SpringBlogger</display-name>
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>SpringBlogger</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringBlogger</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
SpringBlogger-servlet.xml :-
<?xml version="1.0" encoding="UTF-8"?>
<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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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">
<mvc:annotation-driven/>
<context:component-scan base-package="com.beans" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost/springblogger"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
</beans>
Please help.
Thanks,
Manish
You cannot use Object type to bind your form, use its type instead decoreated with #ModelAttribute1
#RequestMapping("/LoginAction")
public ModelAndView onSubmit(#ModelAttribute("loginForm") LoginForm command) {
Also I saw you're trying to create a new application context inside the controller which seem unecessary, use dependency injection / autowiring instead to your controller class

No appenders could be found for the logger

I am trying some samples in spring mvc.I have three classes Student.java and StudentController.java as follows
Student.java
package mvc1;
public class Student {
private Integer age;
private String name;
private Integer id;
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
}
StudentController.java
package mvc1;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.ui.ModelMap;
#Controller
#RequestMapping("login.do")
public class StudentController {
#RequestMapping(value = "/student", method = RequestMethod.GET)
public ModelAndView student() {
return new ModelAndView("student", "command", new Student());
}
#RequestMapping(value = "/addStudent", method = RequestMethod.POST)
public String addStudent(#ModelAttribute("SpringWeb")Student student,
ModelMap model) {
model.addAttribute("name", student.getName());
model.addAttribute("age", student.getAge());
model.addAttribute("id", student.getId());
return "result";
}
}
I have a servlet xml file as HelloWeb-Servlet.xml which is as follow
<?xml version="1.0" encoding="UTF-8"?>
<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="Servee" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
and the web.xml file as follows...
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/DispatcherServlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-
class>
</listener>
<servlet>
<servlet-name>HelloWeb</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>HelloWeb</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
and the student.jsp and result.jsp files are stored in mvc11 package
student.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h2>Student Information</h2>
<form:form method="POST" action="/Spring/mvc1/addStudent">
<table>
<tr>
<td><form:label path="name">Name</form:label></td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td><form:label path="age">Age</form:label></td>
<td><form:input path="age" /></td>
</tr>
<tr>
<td><form:label path="id">id</form:label></td>
<td><form:input path="id" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Submit"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
result.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h2>Submitted Student Information</h2>
<table>
<tr>
<td>Name</td>
<td>${name}</td>
</tr>
<tr>
<td>Age</td>
<td>${age}</td>
</tr>
<tr>
<td>ID</td>
<td>${id}</td>
</tr>
</table>
</body>
</html>
When running the spring program i am getting the warning message as follows
log4j:WARN No appenders could be found for logger (org.springframework.web.context.ContextLoader).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
and the error message as
The requested resource (/Spring/mvc11/student.jsp) is not available.
the HelloWeb-Servlet.xml is stored under WEB-INF.I have referred a lot of source but couldnt fix it.Can someone help me with it...
Looks like there are multiple problems
The package mvc1 is not added to component-scan.
solution: Add the following line to HelloWeb-Servlet.xml
#RequestMapping("login.do") annotation in StudentController does not make any sense, remove it
You have a mapping for the url /student, but is trying to access /Spring/mvc11/student.jsp, either change the RequestMapping or the requested url

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