No message found under code for locale 'en_US' - validation

I'm facing a problem while getting the key value pair from the properties file during spring validation.
Configuration
<?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="controller"></context:component-scan>
<bean id="viewResolver"
class=" org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<bean id="messageResource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource" >
<property name="basename" value="messages"></property>
</bean>
</beans>
Validator
public class ValidatorPlayer implements Validator {
public boolean supports(Class<?> arg0) {
// TODO Auto-generated method stub
return false;
}
public void validate(Object obj, Errors errors) {
Player player = (Player) obj;
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "id","test.to");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name","test.to");
}
}
JSP Form
<body>
<form:form commandName="command">
<table>
<tr>
<td>Enter Id</td>
<td><form:input path="id"/></td>
<td><form:errors path="id"/></td>
</tr>
<tr>
<td>Enter Name</td>
<td><form:input path="name"/></td>
<td><form:errors path="name"/></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="save"></td>
</tr>
</table>
</form:form>
</body>
</html>
Controller
#Controller
public class TestController {
#RequestMapping(value="/getForm.action")
public ModelAndView getForm(){
return new ModelAndView("formd","command",new Player());
}
#RequestMapping(value="/getForm.action", method=RequestMethod.POST)
public ModelAndView saveAdndValidateForm(#ModelAttribute("command") Player player,BindingResult errors){
new ValidatorPlayer().validate(player, errors);
if(errors.hasErrors()){
return new ModelAndView("formd");
}
return new ModelAndView("formd","command",new Player());
}
}
in the messages.properties file I have defined test.to="some value" and this file is in src folder.
in bindingResult error is comming but 500 error is appering on web page saying the above mention error.

Related

SpringMVC-FileUpload - HTTP Status 400 -The request sent by the client was syntactically incorrect

I am new to spring and trying to Upload an image using spring 4.2.7 and commons-io-1.3.2,commons-fileupload-1.3,jdk 1.8.
But unfortunately I am getting error i.e HTTP Status 400 -The request sent by the client was syntactically incorrect.
Please help.
Code snippet is
formExamplePage.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# 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>Spring Form Example</title>
</head>
<body>
<h2>Form Example</h2>
<form:form commandName="formExample" action="formExampleDetails" method="post">
<table>
<tr>
<td>
<label>User Name:</label>
</td>
<td>
<form:input path="userName" placeholder="User Name"></form:input>
</td>
</tr>
<tr>
<td>
<label>Salary:</label>
</td>
<td>
<form:input path="salary" placeholder="salary in decimal"/>
</td>
</tr>
<tr>
<td>
<label>Gender</label>
</td>
<td>
<form:radiobutton path="gender" value="M" label="Male"/>
<form:radiobutton path="gender" value="F" label="Female"/>
</td>
</tr>
<tr>
<td>
<label>Profile Photo:</label>
</td>
<td>
<input name="profilePhoto" type="file"/>
</td>
</tr>
<tr>
<td>
<input type="submit" value="Submit"/>
</td>
<td>
<input type="reset" value="Reset">
</td>
</tr>
</table>
</form:form>
</body>
</html>
Controller class is ApplicationController.java
#Controller
public class ApplicationController {
#RequestMapping(value="/formExampleDetails",method=RequestMethod.POST)
public String formExampleDetails(#ModelAttribute FormExample formExample,
#RequestParam("profilePhoto") MultipartFile profilePhoto,ModelMap model){
System.out.println("User Name====>"+formExample.getUserName());
System.out.println("BirthDate====>"+formExample.getBirthDate());
System.out.println("Gender=======>"+formExample.getGender());
System.out.println("Salary=======>"+formExample.getSalary());
System.out.println("ProfilePhoto=>"+profilePhoto.getOriginalFilename());
return "index";
}
}
Pojo Class i.e FormExample.java is
package com.spring.pojo;
import java.io.Serializable;
import java.math.BigDecimal;
import java.sql.Blob;
import java.sql.Date;
public class FormExample implements Serializable{
private static final long serialVersionUID = 5527691555730303451L;
private String userName;
private Date birthDate;
private BigDecimal salary;
private Blob profilePhoto;
private Character gender;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public BigDecimal getSalary() {
return salary;
}
public void setSalary(BigDecimal salary) {
this.salary = salary;
}
public Blob getProfilePhoto() {
return profilePhoto;
}
public void setProfilePhoto(Blob profilePhoto) {
this.profilePhoto = profilePhoto;
}
public Character getGender() {
return gender;
}
public void setGender(Character gender) {
this.gender = gender;
}
}
spring configuration file is
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="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.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.xsd">
<context:component-scan base-package="com.spring"></context:component-scan>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="./"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="100000000"></property>
</bean>
</beans>
Have you seen this question on multipartFiles and blobs? Your form:form may require enctype="multipart/form-data" .
I haven't tried to run your code, but have you tried to either remove, rename profilePhoto and its getter and setter from FormExample, or set its type to MultipartFile ?
I suspect that despite your controller method having a parameter with the same name Spring might be trying to assign the parameter value to both the method parameter and the form property, and failing to convert MultipartFile to java.sql.Blob when assigning to the form property.

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

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.

Spring MVC form validation not working

I am using Spring 4.
My form contains the following variables:
#NotNull
#Email
private String email;
#NotNull
private String firstName;
#NotNull
private String lastName;
#Digits(fraction = 0, integer = 10)
private String phoneNo;
#NotNull
private String role;
My controller:
#Controller
#RequestMapping("/user")
public class UserController {
#RequestMapping(value = "/add", method = RequestMethod.POST)
public ModelAndView add(#ModelAttribute("user") #Valid UserBean user, BindingResult result) {
String message;
if (result.hasErrors() && user != null)
return new ModelAndView("userAdd");
else {
userService.addUser(user);
message = "Successfully added user";
}
return new ModelAndView("success", "message", message);
}
#RequestMapping(value = "/register")
public ModelAndView register(#ModelAttribute("user") UserBean user, BindingResult result) {
List<String> roles = new ArrayList<String>();
roles.add("Receiver");
roles.add("Resolver");
roles.add("Logger");
Map<String, List<String>> model = new HashMap<String, List<String>>();
model.put("roles", roles);
return new ModelAndView("userAdd", "model", model);
}
}
My jsp:
<c:url var="userAdd" value="user/add.do" />
<sf:form method="post" action="${userAdd}" modelAttribute="user">
<table>
<tr>
<td>First Name</td>
<td><sf:input path="firstName" /><br /> <sf:errors
path="firstName" cssClass="error" /></td>
</tr>
<tr>
<td>Last Name</td>
<td><sf:input path="lastName" /><br /> <sf:errors
path="lastName" cssClass="error" /></td>
</tr>
<tr>
<td>Email</td>
<td><sf:input path="email" /><br /> <sf:errors
path="email" cssClass="error" /></td>
</tr>
<tr>
<td>Phone No.</td>
<td><sf:input path="phoneNo" /><br /> <sf:errors
path="phoneNo" cssClass="error" /></td>
</tr>
<tr>
<td>Role</td>
<td><sf:select path="role" items="${model.roles}" /><br /> <sf:errors
path="role" cssClass="error" /></td>
</tr>
<tr>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</sf:form>
When I leave the the inputs blank, the form does not validate and does not throw any error. The BindingResult does not have any errors in it.
My libraries are:
My dispatcher-serlvet.xml is:
<?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/mvc http://www.springframework.org/schema/mvc/spring-mvc.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.xsd">
<!-- Scans for annotated #Controllers in the classpath -->
<context:component-scan base-package="com.mj.cchp.controller">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<bean id="myBeansValidator"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
<mvc:annotation-driven validator="myBeansValidator" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
My applicationContext is:
<?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.xsd">
<!-- Scans for annotated #Controllers in the classpath -->
<context:component-scan base-package="com.mj.cchp">
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.ibm.db2.jcc.DB2Driver" />
<property name="url" value="jdbc:db2://172.16.2.181:60000/CCHP" />
<property name="username" value="db2inst1" />
<property name="password" value="db2inst1" />
</bean>
</beans>
My web.xml is:
<?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"
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>CCHP</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/application-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>
</web-app>
You need to add
<bean id="myBeansValidator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
and
<mvc:annotation-driven validator="myBeansValidator">
and
<!-- Hibernate Validator -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.2.0.Final</version>
</dependency>
Should work!
I had a similar problem and in my case it was sufficient to just add dependency for hibernate validator: org.hibernate:hibernate-validator:5.2.4.Final.
The validation is done by LocalValidatorFactoryBean bean and documentation about it comes handy (here).
Yet at the same time it is worth mentioning that you do not have to instantiate LocalValidatorFactoryBean explicitly as long as you use #EnableWebMvc annotation : http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-config-validation
By default use of #EnableWebMvc or
automatically registers Bean Validation support in Spring MVC through
the LocalValidatorFactoryBean when a Bean Validation provider such as
Hibernate Validator is detected on the classpath.
Hope this helps.
I faced the same problem. I resolved by adding below statement in dispatcher-serlvet.xml file.
<mvc:annotation-driven />
I'm not sure whether you have found ways to fix this. I am facing the same issue as well. and I managed to solve it. The problem with my setting is totally manual and I'm doing big mistake by placing the whole hibernate-validator-5.1.3.Final-dist.zip inside lib folder.
So what I did is I get this 6 files inside "hibernate-validator-5.1.3.Final-dist.zip" in dist folder and place this with web app lib.
classmate-1.0.0.jar
hibernate-validator-5.1.3.Final.jar
javax.el-2.2.4.jar
javax.el-api-2.2.4.jar
jboss-logging-3.1.3.GA.jar
validation-api-1.1.0.Final.jar
This fixed my issue.
i also faced the same issue where my entire code was properly written.
The problem was the different version of jar files that i was using .
I had hibernate-validator-cdi- 5.0.7.Final and hibernate-validator-6.0.2.Final.
Just make sure your jar files are of the same version.
When i kept all the jars of same version, my issue got resolved. I hope this will help you .
You need to add #Valid in register method
#RequestMapping(value = "/register") public ModelAndView register(#Valid #ModelAttribute("user") UserBean user, BindingResult result) {
If you are using hibernate-validator, use version-6.2.4
Version 7 might not work.
In my case hibernate-validator jars are not available in run time. I've copied them to .../WEB-INF/lib/ then it worked correctly.
I added the usual stuff you have done (libraries in pom, #Valid on RequestBody etc)
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.1.3.Final</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.el</artifactId>
<version>3.0.1-b11</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
What the Spring docs (and many blogs) leave it as subtle is that Spring looks for an exit point to throw the error but if that exit doesn't exist, it will reply with 404. After reading a lot especially this blog, adding this class got Spring to recognize #Valid and find an exit point to throw the error
#RestControllerAdvice
#Order(1)
public class RestControllerExceptionHandler {
#RequestMapping(value = { "error/404" }, method = RequestMethod.GET)
#ExceptionHandler(Exception.class)
public String handleUnexpectedException(Exception e) {
return "views/base/rest-error";
}
#ResponseStatus(HttpStatus.BAD_REQUEST)
#ExceptionHandler(MethodArgumentNotValidException.class)
public String handlemethodArgumentNotValid(MethodArgumentNotValidException exception) { //
// TODO you can choose to return your custom object here, which will then get transformed to json/xml etc.
return "Sorry, that was not quite right: " + exception.getMessage();
}
#ResponseStatus(HttpStatus.BAD_REQUEST)
#ExceptionHandler(ConstraintViolationException.class)
public String handleConstraintViolation(ConstraintViolationException exception) { //
// TODO you can choose to return your custom object here, which will then get transformed to json/xml etc.
return "Sorry, that was not quite right: " + exception.getMessage();
}
}
i spent nearly 2 days fixing the same problem and ultimately found one solution, if you still have this problem, i would like to suggest you one answer, in my case, i tried using hibernate-validator-5.1.3.Final-dist.zip,5.2.4.Final-dist.zip, 7.0.0.Final-dist.zip but none of these worked for me but when i used *hibernate-validator-6.2.0.Final-dist*, it supports jarkarta validation but it works perfectly even though people say because of Jakarta Bean Validation it does not work in hibernate-validator's version post 5. it worked miraculously and believe me, it might work for you as well.

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

Spring 3 MVC: Show validation message with custom validator

I need help. I am beginner in jsp, MVC. I want to validate form input with custom validator in Spring 3 MVC.
My validator class
package validators;
import models.UserModel;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
#Component
public class UserValidator implements Validator {
#Override
public boolean supports(Class clazz) {
return UserModel.class.isAssignableFrom(clazz);
}
#Override
public void validate(Object target, Errors errors) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstname", "Enter firstname.");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "surname", "Enter surname.");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "login", "Enter login.");
}
}
Controller class
package controllers;
import java.util.ArrayList;
import models.UserModel;
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;
import org.springframework.web.servlet.ModelAndView;
import validators.UserValidator;
import database.UserDB;
#Controller
public class UserController {
#RequestMapping(value="pouzivatel/new", method=RequestMethod.POST)
public ModelAndView newUser(#ModelAttribute UserModel user, BindingResult result){
UserValidator validator = new UserValidator();
validator.validate(user, result);
if(result.hasErrors()){
return new ModelAndView("/user/new","command",user);
}
...
}
Model for User
package models;
public class UserModel {
private String firstname="";
private String surname="";
public String getFirstname() {
return firstname;
}
public String getSurname() {
return surname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public void setSurname(String surname) {
this.surname = surname;
}
}
JSP veiw new.jsp which is in directory /web-inf/user (it just only form)
<form:form method="post" action="new.html">
<fieldset>
<table>
<tr>
<td>
<form:label path="firstname">FirstName</form:label>
</td>
<td>
<form:input path="firstname" />
<form:errors path="firstname" />
</td>
</tr>
<tr>
<td>
<form:label path="surname">Surname</form:label>
</td>
<td>
<form:input path="surname" />
<form:errors path="surname" />
</td>
</tr>
</table>
</fieldset>
<div>
<button type="submit" id="btOk">Ok</button>
</div>
</form:form>
dispatcher 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:context="http://www.springframework.org/schema/context"
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="controllers" />
<context:component-scan base-package="validators" />
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
Problem is a display validation message in view. Validation is successful and in variable resut (BindingResult) are errors. Controller return follow part of code
if(result.hasErrors()){
return new ModelAndView("/user/new","command",user);
Another way is use Annotation validation (I preffer custom validator), but why i can not see validation messages on view, when input fields are empty.
Can you give me example how to do it right?
Thanks for reply.
This happens because of mismatch between default model attribute names in view and controller:
When you write <form:form> without modelAttribute (or commandName) attribute, it uses default model attribute name command.
When you write #ModelAttribute UserModel user in your controller, it assumes that the name of this attribute is a decapitalized class name, i.e. userModel.
That is, error messages produced by validator are bound to model attribute named userModel, while your view tries to show errors for model attribute command.
You need to set a model attribute name explicitly, either in the view (<form:form modelAttribute = "userModel" ...>) or in the controller (#ModelAttribute("command")).

Resources