Reputation: 913
What can be the approach to append the user object in every request and response in Spring MVC 3. So that on the Jsp if I do the request.getAttribute("user"), then I should be able to get the User Object.
Thanks to all.
Upvotes: 1
Views: 2095
Reputation: 2592
User
object in a session attribute
You can put your User
object in a session attribute:
@Controller
public class MyMvcController
{
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String hello(HttpServletRequest request)
{
User user = ... // initialise your User object here
request.getSession().setAttribute("user", user);
return "hello";
}
}
If you put the User
object in a session attribute, it will be stored on the server between HTTP requests, so you need to initialize it only once somewhere in your application.
In JSP, you can access the User
object with session.getAttribute("user")
, or with EL: ${user.id}
, ${user.name}
...
User
object in an MVC model
Alternatively, if you do not want to store your object in the session attributes, you can create a new User
object in every request and put it in your MVC model as described in this answer:
@ControllerAdvice
public class GlobalControllerAdvice {
@ModelAttribute
public void myMethod(Model model) {
User user = // initialise your User object here
model.addAttribute("user", user);
}
}
See the original answer for details.
In JSP, you can access the User
object with request.getAttribute("user")
, or with EL: ${user.id}
, ${user.name}
...
Upvotes: 2
Reputation: 8973
You want User object in every request and response.
@Controller
@SessionAttribute("user")
public class UserController{
}
JSP code:
<form:form modelAttribute="user">...</form:form>
You can use that user object as you want:
${user.name} //equivalent to request.getAttribute("user").getName();
${user.age}
Upvotes: 0