Sunday 25 November 2018

Spring web mvc: BindingResult : Handle data binding error

This is continuation to my previous posts. In my previous post, I explained how spring binds the request parameters to a java model object using @ModelAttribute annotation.

But in some cases, user may enter wrong inputs. For example, you developed a registration form, where you are expecting below information.

Information
Type
userName
String
age
int
hobbies
Collection

If user enter age as ‘Twenty Five’, where you are expecting an integer. Spring throws an exception.




As you see above registration form, I given ‘Twenty Five’ as the value for the field ‘Age’. When I click on submit button, I got below exception.

As you see above error page, I do not get any meaningful error message. To solve this problem, spring provides 'BindingResult' interface.


BindingResult interface
General interface that represents binding results. If any error occurs, at the time of binding the request parameters to java model object, we can use this interface to retrieve the number of errors, error messages.

@RequestMapping("/registerMe")
public ModelAndView getHelloMessage(@ModelAttribute("studentInfo") Student student, BindingResult bindingResult) {
         if (bindingResult.hasErrors()) {
                  ModelAndView modelAndView = new ModelAndView("registration");
                  return modelAndView;
         }

         .....
         .....
         .....
}

As you see above snippet, I am using bindingResult.hasErrors() method to check whether there is any errors.

you can use the  <form:errors /> tag to render those field error messages in an HTML page.

Example
<form:errors path="studentInfo.*" />

Above tag displays the error message, if the binding of the request parameters to the studentInfo object is not successful.

Find the below working application.

HelloWorldController.java
package com.sample.myApp.controllers;

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.servlet.ModelAndView;

import com.sample.myApp.model.Student;

@Controller
public class HelloWorldController {
 @RequestMapping("/registration")
 public String getRegistrationpage() {
  return "registration";
 }

 @RequestMapping("/registerMe")
 public ModelAndView getHelloMessage(@ModelAttribute("studentInfo") Student student, BindingResult bindingResult) {
  if (bindingResult.hasErrors()) {
   ModelAndView modelAndView = new ModelAndView("registration");
   return modelAndView;
  }

  ModelAndView modelAndView = new ModelAndView("welcome");

  modelAndView.addObject("message", "Dear User, your details are registered");

  return modelAndView;
 }

}

Student.java
package com.sample.myApp.model;

import java.util.List;

public class Student {
 private String userName;
 private int age;
 private List<String> hobbies;

 public String getUserName() {
  return userName;
 }

 public void setUserName(String userName) {
  this.userName = userName;
 }

 public int getAge() {
  return age;
 }

 public void setAge(int age) {
  this.age = age;
 }

 public List<String> getHobbies() {
  return hobbies;
 }

 public void setHobbies(List<String> hobbies) {
  this.hobbies = hobbies;
 }

}
Create registration.jsp, welcome.jsp files under WEB-INF/jsp folder.


registration.jsp
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<title>User Information Page</title>
</head>

<body>
 <h2 style="color:red;"><form:errors path="studentInfo.*" /></h2>

 <form method="post" action="/springdemo/registerMe" id="f1">
  <table>
   <tr>
    <td>User Name :</td>
    <td><input type="text" name="userName" value="" /></td>
   </tr>
   <tr>
    <td>Age :</td>
    <td><input type="text" name="age" value="" /></td>
   </tr>
   <tr>
    <td>Hobbies :</td>
    <td><select multiple name="hobbies">
      <option value="cricket">Cricket</option>
      <option value="chess">Chess</option>
      <option value="football">Football</option>
      <option value="tennis">Tennis</option>
    </select></td>
   </tr>
   <tr>
    <td><input type="submit" name="submit" value="submit"
     style="font-size: 18px;" /></td>
   </tr>
  </table>
 </form>

</body>
</html>

welcome.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!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>Hello World Spring Web MVC</title>
</head>
<body>
 <h1>${message}</h1>

 <h3>
  User Name : ${studentInfo.userName} <br /> 
  Age : ${studentInfo.age} <br />
  Hobbies: ${studentInfo.hobbies}
 </h3>
</body>
</html>
Create web.xml, HelloWorld-servlet.xml files under WEB-INF folder.


web.xml
<web-app id="WebApp_ID" version="2.4"
 xmlns="http://java.sun.com/xml/ns/j2ee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
   http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

 <display-name>Spring MVC Hello WorldApplication</display-name>

 <servlet>
  <servlet-name>HelloWorld</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
 </servlet>

 <servlet-mapping>
  <servlet-name>HelloWorld</servlet-name>
  <url-pattern>/</url-pattern>
 </servlet-mapping>

</web-app>

HelloWorld-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="com.sample.myApp" />

 <bean
  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix" value="/WEB-INF/jsp/" />
  <property name="suffix" value=".jsp" />
 </bean>

</beans>

Create index.jsp file under webapp folder.


index.jsp
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<title>Welcome Page</title>
</head>

<body>
 <h1>Hello World</h1>
</body>
</html>

Project structure looks like below.

Run the application on server.

I entered ‘Twenty Five’ in the Age field, When I click on submit button, it shows the error information.



Previous                                                 Next                                                 Home

No comments:

Post a Comment