Hayi
Hayi

Reputation: 6246

Difference between @ModelAttribute and HttpServletRequest Attribute

I use spring mvc and I want to undestand some stuff.
At this code:

    @RequestMapping(value="/enregistrerLostCard") 
public  @ResponseBody
void enregistrerLostCard(@ModelAttribute(value="auth") Auth auth2, HttpServletRequest request) {    

    Auth auth1 = (Auth) request.getAttribute("auth");

    System.out.println(auth2.getLogin()); //print the right value
    System.out.println(auth1.getLogin()); //i got nullpointer exception

}

@ModelAttribute(value="auth") and request.getAttribute("auth") isn't the same ?

Upvotes: 0

Views: 2400

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280072

HttpServletRequest is a Servlet container managed object. Its attribute store holds attributes that are useful in any part of the request handling by the Servlet container.

Model, ModelMap, ModelAndView, etc. are managed by Spring MVC (the DispatcherServlet stack). The attributes inside those are useful to the Spring side of the application.

In some cases, the Model attributes will be inserted into the HttpServletRequest attributes if needed. This typically happens when your handler method returns a String value as a view name. The model attributes will be pushed as HttpServletRequest attributes so that they can be used in the view, for example, in jsps.

Related:

Upvotes: 3

Related Questions