【发布时间】:2016-03-10 01:20:30
【问题描述】:
我已经使用了 2 个 PathVariable,而不是单独使用这些,我想将这 2 个 PathVariables 存储到地图中并希望从地图中检索它。
在 Spring MVC 3.1.0 中,这是我的 Controller 类方法:
@Controller
@RequestMapping("/welcome")
public class HelloController {
@RequestMapping(value="/{countryName}/{userName}",method=RequestMethod.GET)
public String getPathVar(@PathVariable Map<String, String> pathVars, Model model) {
String name = pathVars.get("userName");
String country = pathVars.get("countryName");
model.addAttribute("msg", "Welcome " + name+ " to Spring MVC & You are from" + country);
return "home";
}
我的请求网址是: http://localhost:3030/spring_mvc_demo/welcome/India/ashrumochan123
但是当使用这个 url 发出请求时,我得到 HTTP 状态 400 -
说明:客户端发送的请求语法错误。
当我单独使用这些路径变量时,它工作正常。 这是代码-
@RequestMapping(value="/{countryName}/{userName}", method=RequestMethod.GET)
public String goHome(@PathVariable("countryName") String countryName,
@PathVariable("userName") String userName, Model model) {
model.addAttribute("msg", "Welcome " + userName
+ " to Spring MVC& You are from " + countryName);
return "home";
}
请告诉我是否做错了什么?
任何帮助将不胜感激。
【问题讨论】:
-
我认为您想要做的事情是不可能的。对于初学者,您正在尝试将
String强制转换为Map,这在您的注释和方法签名中命名不一致。为什么不在控制器方法中根据两个参数创建地图? -
@woemler,感谢您的快速回复,但这是可能的。我看过一些关于这个的视频演示。但对他们使用的 Spring MVC 版本感到困惑。
-
其实@Ashrumochan 是对的,方法是对的,但还有一些问题,我试过了,对我来说效果很好,请问你用的是什么spring 版本?
-
来自 Spring 文档:
If the method parameter is Map<String, String> or MultiValueMap<String, String> then the map is populated with all path variable names and values. Since: 3.0 -
我正在使用 Spring 4.2.5.RELEASE,也许你应该检查客户端请求,如果问题仍然存在,请尝试更新你的 spring。
标签: java spring spring-mvc