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.
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?
Use (as of Spring 4.3) @RequestAttribute:
@RequestMapping(value = "someurl", method = RequestMethod.GET) public String handleSomeUrl(@RequestAttribute User user) { // ... do some stuff }
or if the request attribute name does not match the method parameter name:
@RequestMapping(value = "someurl", method = RequestMethod.GET) public String handleSomeUrl(@RequestAttribute(name="userAttributeName") User user) { // ... do some stuff }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With