gpt4 book ai didi

java - Spring MVC 项目中的@RequestAttribute 不获取值

转载 作者:行者123 更新时间:2023-11-30 11:34:11 29 4
gpt4 key购买 nike

Spring MVC 项目中的

@RequestAttribute 未获取值。

我使用了一个@ModelAttribute。这里 foo 属性被设置为 bar

@ModelAttribute  
void beforeInvokingHandlerMethod(HttpServletRequest request)
{
request.setAttribute("foo", "bar");
}

我尝试使用 @RequestAttribute("foo") 调用 foo 的请求属性值。但是值为空。

然后我尝试使用 request.getAttribute("foo") 并打印值。我不知道以下代码有什么问题:

@RequestAttribute("foo"). 
@RequestMapping(value="/data/custom", method=RequestMethod.GET)
public @ResponseBody String custom(@RequestAttribute("foo") String foo, HttpServletRequest request) {
System.out.println("foo value : " + foo); //null printed
System.out.println("request.getAttribute : " + request.getAttribute("foo")); //value printed

return foo;
}

最佳答案

@RequestAttribute 不是 Spring 注释。如果你想传递一个值,你可以做一个请求参数

@RequestMapping(value="/data/custom", method=RequestMethod.GET)  
public @ResponseBody String custom(@RequestParam("foo") String foo) {
System.out.println("foo value : " + foo); //null printed
return foo;
}

或者如果你想在你可以做的路径中传递值

@RequestMapping(value="/data/custom/{foo}", method=RequestMethod.GET)  
public @ResponseBody String custom(@PathVariable("foo") String foo) {
System.out.println("foo value : " + foo); //null printed
return foo;
}

关于java - Spring MVC 项目中的@RequestAttribute 不获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15787602/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com