Building UI using Spring MVC - Part II

In continuation of my previous blog, in this blog we will see how session is handled and little more about spring tags.

Session Handling:

Spring MVC provides an annotation '@SessionAttributes' which will identify objects which need to be put in session. Spring container will take care of adding and updating these objects into the Session.

For eg.,
public class UserController{

The above annotation will inform the container that the object identified by "user" attribute in the Model will be stored in session. Further, in the controller method, we will create a ModelAndView object as usual and add the User object to it. 

The point to note here is that:

  1. Before a controller method is invoked, the sessionAttribute values are retrieved from session and the model object is updated.
  2. After controller method returns, the updated model values (only those annotated with SessionAttributes) are put back in session.
So, though the HttpSession object is available to you in controller methods, it is safer to use SessionAttributes instead.

Let us say, we need to put the logged in user's username into the session and retrieve it at different locations.

public class LoginController {
        @RequestMapping(value="/exampleweb/login", method=RequestMethod.POST) 
     public String login(@ModelAttribute @Valid User user, BindingResult result ) {
         boolean loginResult = loginService.login();
             return "loginFailure";
         ModelAndView mav = new ModelAndView("home");
         /*Put the username in session*/

Once the login method returns, the username is updated into the session scope. Later for example, in any of the JSP pages, we can retrieve this user name by using "${loggedInUserName}".

Custom binding of properties:

Lets say we need to have a custom conversion of the data sent in form post. For eg, Let us say, User has date of birth field as 'birthDate'. The UI will have a input field mapped to 'birthDate'. In order to convert this string to a proper date, we can use @initBinder annotation as below in the controller.
protected void initBinder(WebDataBinder binder) {

    binder.setValidator(new UserValidator());  
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    binder.registerCustomEditor(Date.class, "birthDate", new CustomDateEditor(dateFormat, false));


The initBinder is mapped to model attribute "user". Also, we have created a SimpleDateFormat object to format date. This along with
Spring's CustomDateEditor is used to register our custom editor. You can also create your own extension of PropertyEditor and register that.

Note that we have registered this editor against a field "birthDate". If the user provides invalid date format, then this will throw an exception back.

Spring tags:

Apart from the form tag, spring tag offers quite a few interesting things as below:
1.  spring:bind tag:

<spring:bind path="birthDate">

The spring:bind tag allows us to get the error details specific to a field (birthdate in above example). The status variable will indicate if there is a error for this field.

2.  spring:url tag:

In order to create a url which has parameters in it, we can use the spring:url tag as below:

<spring:url value="/exampleweb/users/user/{userId}" var="formUrl">
 <spring:param name="userId" value="${user.userId}"/>


Popular posts from this blog

Pivotal Cloud Foundry (PCF) Integration with Elastic Cloud Storage (ECS)

Restful code example using Spring MVC

Spring Integration - Bulk processing Example