Spring MVC: bind request attribute to controller method parameter
java, spring, spring-mvc
Solution
Well, I finally understood a little bit how models work and what is `@ModelAttribute` for. Here is my solution.
@Controller
class MyController
{
@ModelAttribute("user")
public User getUser(HttpServletRequest request)
{
return (User) request.getAttribute("user");
}
@RequestMapping(value = "someurl", method = RequestMethod.GET)
public String HandleSomeUrl(@ModelAttribute("user") User user)
{
// ... do some stuff
}
}
The `getUser()` method marked with `@ModelAttribute` annotation will automatically populate all `User user` parameters marked with `@ModelAttribute`. So when the HandleSomeUrl method is called, the call looks something like `MyController.HandleSomeUrl(MyController.getUser(request))`. At least this is how I imagine it. Cool thing is that user is also accessible from the JSP view without any further effort.
This solves exactly my problem however I do have further questions. Is there a common place where I can put those `@ModelAttribute` methods so they were common for all my controllers? Can I somehow add model attribute from the inside of the `preHandle()` method of an Interceptor?
Problem
In Spring MVC, it is easy to bind request parameter to method paramaters handling the request. I just use `@RequestParameter("name")`. But can I do the same with request attribute? Currently, when I want to access request attribute, I have to do following: ``` MyClass obj = (MyClass) request.getAttribute("attr_name"); ``` But I really would like to use something like this instead: ``` @RequestAttribute("attr_name") MyClass obj ``` Unfortunately, it doesn't work this way. Can I somehow extend Spring functionality and add my own "binders"? EDIT (what I'm trying to achieve): I store currently logged user inside request attribute. So whenever I want to access currently logged user (which is pretty much inside every method), I have to write this extra line `user = (User) request.getAttribute("user");`. I would like to make it as short as possible, preferably inject it as a method parameter. Or if you know another way how to pass something across interceptors and controllers, I would be happy to hear it.