Spring MVC-存储和检索@PathVariable映射


问题内容

我已经使用了2个PathVariable,而不是将它们分开保存,我想将这2个PathVariables存储到Map中,并希望从Map中检索它。

在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";
}

我的请求URL是: 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";
    }

请告诉我我做错了什么吗?

任何帮助将不胜感激。


问题答案:

根据Spring文档,从3.2版本开始就存在。

对于@PathVariablewith Map<String,String>,我认为您缺少<mvc:annotation- driven/>Spring servlet配置:

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
                    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd     
                    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">

<mvc:annotation-driven/>
...

我在此链接上找到了它 。