Spring MVC - Form Data & Session Data

Propagate HTML form Data to a Spring MVC POJO Object

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

<form:form commandName="order">
    Customer Name: <form:input path="customerName" /> 
    Order Id:  <form:input path="order" />
    <input type="submit" value="Submit" />
</form:form>
  • The HTML form will be pre-propagated by the "order" object
  • When a form is submitted, propagate the POJO "order" with the form data

Create a POJO for Data Binding

class Order {
   private String customerName;
   private int order;

   ... get & setter method ...
}

Map a POJO to a Controller method's Parameter

In the JSP, the POJO is named "order"

Use @ModelAttribute to bind it to a Controller method's parameter

@RequestMapping("/order/submit")
public String submit(@ModelAttribute("order") Order order, BindingResult result, SessionStatus status) {

   // Validate the POJO and store any validation error if any   
   new OrderValidator().validate(order, result);
   if (result.hasErrors()) {
      return "orderEditForm";
   } else {
      ...

      status.setComplete();
      return "order_confirm";
   }
}

Display Validation Error in the Form Page

Display all errors

<form:errors path="*" cssClass="myCSS" />

Display individual errors

Customer Name: <form:input path="customerName" /> <form:errors path="firstName" />

Passing a POJO Object to a View

We see how @ModelAttribute is used at the parameter level. When it is used at method level,

  1. With the @ModelAttribute annotation, Spring store the POJO object in the JSP's view with the name specify in @ModelAttribute "my_option_values"
    @ModelAttribute("my_option_values")
    public List<String> getValues() {
            List<String> values = new ArrayList<String>();
            values.add("Option 1");
            values.add("Option 2");
            return values;
    }
    
  2. JSP can access the value as
    <form:select path="option" items="${my_option_values}" />
    

Data Conversion

Form data can be converted to a particular Object type with a custom convertor

@Controller
public class MyController {

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat format = new SimpleDateFormat("MM/dd/YYYY");
        dateFormat.setLenient(false);
        binder.setRequiredFields(new String[] {"order", "name"});
        binder.registerCustomEditor(Date.class, new CustomDateEditor(format, false));
    }
}

Or creating MyBindingInitializer implementing WebBindingInitializer

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="cacheSeconds" value="0" />
    <property name="webBindingInitializer">
        <bean class="com.domain....MyBindingInitializer" />
    </property>
</bean>

Storing Session Data using Spring MVC

Stores data in the session with name "name"

@Controller
@RequestMapping("/find")
@SessionAttributes("name")
public class MyObject {
   void find(ModelMap model) {
        ...
        model.addAttribute("name", obj);
        ...
   }
   ...
}

To invalidate the above session data, mark a SessionStatus as complete. All session data identified by @SessionAttributes in the controller will be removed from the session

String controllerMethod(SessionStatus status, ...) {
  status.setComplete();
}