Spring MVC-存储和检索@PathVariable Map<String,String>[英] Spring MVC- Storing and Retrieving @PathVariable Map<String, String>

问题描述

我已经使用了 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";
}
<块引用>

我的请求网址是: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 版开始就存在了.

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

<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/>
...

我在此链接上找到了它.

本文地址:https://www.itbaoku.cn/post/978427.html