Understanding the use of @ModelAttribute and @RequestAttribute annotations in Spring MVC

I am new to Spring MVC. I am currently studying the Spring MVC Showcase , which demonstrates the features of the Spring MVC web framework.

I have some problem to understand how the custom resolved web arguments are handled in this example.

In practice, I have the following situation. In my view of home.jsp, I have the following link:

<a id="customArg" class="textLink" href="<c:url value="/data/custom" />">Custom</a> 

This link generates an HTTP request at the URL: "/ data / custom"

The controller class containing the method that processes this request has the following code:

 @Controller public class CustomArgumentController { @ModelAttribute void beforeInvokingHandlerMethod(HttpServletRequest request) { request.setAttribute("foo", "bar"); } @RequestMapping(value="/data/custom", method=RequestMethod.GET) public @ResponseBody String custom(@RequestAttribute("foo") String foo) { return "Got 'foo' request attribute value '" + foo + "'"; } } 

The method that processes this HTTP request is custom () . Therefore, when the previous link is clicked, the HTTP request is processed using a custom method.

I have some problem to understand what the @RequestAttribute annotation does exactly . I think in this case it binds a request attribute with the name foo to the new String foo variable. But where did this attribute come from? Is this variable taken using Spring?

OK, my idea is that this request attribute is taken from an HttpServletRequest object. I think so, because in this class I also have a beforeInvokingHandlerMethod () method that has a speaking name, so it seems that this method sets an attribute that has name = foo and value = bar inside the HttpServletRequest object, and then like that that the custom () method can use this value.

Actually my conclusion:

Request attribute value 'foo' 'bar'

Why is beforeInvokingHandlerMethod () called before the custom () method?

And why is beforeInvokingHandlerMethod () annotated with @ModelAttribute annotation? What does this mean in this case?

+6
source share
1 answer

RequestAttribute is nothing but the parameters that you passed in the form view. Let's look at an example with examples

Suppose I have the following form

 <form action="..."> <input type=hidden name=param1 id=param1 value=test/> </form> 

Now, if I have a controller below that maps to the request URL, which maps to the form view, as shown below.

 @Controller public class CustomArgumentController { @ModelAttribute void beforeInvokingHandlerMethod(HttpServletRequest request) { request.setAttribute("foo", "bar"); } @RequestMapping(value="/data/custom", method=RequestMethod.GET) public @ResponseBody String custom(@RequestAttribute("param1") String param1 ) { // Here, I will have value of param1 as test in String object which will be mapped my Spring itself } 
+1
source

All Articles