Spring MVC 3.1 - How to Get HttpSession in Controller Method

In Spring MVC 3.1, there is great improvement on ways how we get frequently used object during request processing life cycle. You may need to have access to following classes instances frequently in different controllers e.g. HttpServletRequest, HttpServletResponse, HttpSession, etc.

When Spring MVC 3.1 dispatcher receive the raw request, it introspect the parameters lists of user defined controller methods which is supposed to be executed (from URL pattern). Using reflections it introspect the types of parameters and pass the required object to that controller method. For example, there is a method names index which expect HttpSession, so that it could perform something related to session. the index() method can be declared just like this:

@Controller
@RequestMapping("/home")
public class HomeController {

@RequestMapping(method = RequestMethod.GET)
public String index(HttpSession session) {

// Use session object here, as you like

}

The Spring MVC 3.1 would automatically pass the required parameter i.e. HttpSession.

Comments