java - 在此 Spring MVC 展示示例中如何使用 @RequestAttribute 和 @ModelAttribute 注释?

标签 java spring spring-mvc model annotations

我是 Spring MVC 的新手。

这段时间我在研究Spring MVC showcase示例可从 STS 仪表板下载。

我在理解如何在此示例中处理自定义可解析 Web 参数时遇到了一些问题。

在实践中我有以下情况:

在我的 home.jsp View 中,我有以下链接:

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

此链接生成针对 URL 的 HTTP 请求:"/data/custom"

包含处理此请求的方法的 Controller 类具有以下代码:

@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 + "'";
}

 }

处理这个 HTTP 请求的方法是 custom()

因此,当单击上一个链接时,HTTP 请求由自定义方法处理...

我在理解 @RequestAttribute 注释时遇到问题。

我认为,在这种情况下,它将名为 foo 的请求属性绑定(bind)到一个新的 String foo 变量。

但是……这个属性是从哪里取来的?这个变量是Spring取的吗?

好的...我的想法是这个请求属性取自 HttpServletRequest 对象...

我认为这是因为,在这个类中,我也有 beforeInvokingHandlerMethod() 方法,它有一个 speacking name...所以看起来这个方法设置了一个属性,它有 name=foovalue=bar,在 HttpServletRequest 对象中...然后 custom() 方法可以使用这个值...

事实上我的输出是:

得到'foo'请求属性值'bar'

为什么beforeInvokingHandlerMethod()custom()方法之前调用?

为什么 beforeInvokingHandlerMethod()@ModelAttribute 注解了?这个案例是什么意思?

最佳答案

你对@RequestAttribute的假设是正确的,它不需要在beforeInvokingHandlerMethod中设置。假设您有一个映射到 /data/init 的方法,它将请求转发到 /data/custom。在这种情况下,也可以在 init 方法中设置请求属性。

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

And why the beforeInvokingHandlerMethod() is annoted by @ModelAttribute annotation? what means in this case?

你会在这里找到原因 http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/mvc.html#mvc-ann-modelattrib-methods

An @ModelAttribute on a method indicates the purpose of that method is to add one or more model attributes. Such methods support the same argument types as @RequestMapping methods but cannot be mapped directly to requests. Instead @ModelAttribute methods in a controller are invoked before @RequestMapping methods, within the same controller.

关于java - 在此 Spring MVC 展示示例中如何使用 @RequestAttribute 和 @ModelAttribute 注释?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13919307/

相关文章:

java - 如何将图像上传到tomcat或glassfish中的网络资源文件夹

java - 猜谜游戏java代码错误

java - Spring MVC中如何防止并发调用

java - 根据条件忽略RequestBody值

java - PropertyPlaceholderConfigurer 从 XML 文件中读取(Apache Commons 配置)

java - 如何检索作为 Multipart Post 的一部分发送的 Servlet 上的字符串

java - 如何解决系统找不到指定文件的错误?

java - org.springframework.dao.InvalidDataAccessApiUsageException : Multiple representations of the same entity

java.lang.NoSuchMethodException : org. springframework.boot.autoconfigure.http.HttpMessageConverters 问题

java - 使用相同的 servlet 上下文设置多个 Web 服务