java - 带有 { } 大括号的 Spring MVC @Path 变量

标签 java spring spring-mvc spring-boot

我正在使用 Spring Boot 开发应用程序。在 REST Controller 中,我更喜欢使用路径变量(@PathVariabale 注释)。我的代码获取路径变量,但它包含 { } 大括号,因为它在 url 中。请任何人建议我解决这个问题

@RequestMapping(value = "/user/item/{loginName}", method = RequestMethod.GET)
public void getSourceDetails(@PathVariable String loginName) {
    try {
        System.out.println(loginName);
        // it print like this  {john}
    } catch (Exception e) {
        LOG.error(e);
    }
}

网址

http://localhost:8080/user/item/{john}

Controller 输出

{约翰}

最佳答案

使用 http://localhost:8080/user/item/john 来提交您的请求。

你给 Spring 的路径变量 loginName 赋予一个值“{john}”,所以 Spring 用“{}”得到它

Web MVC framework声明

URI Template Patterns

URI templates can be used for convenient access to selected parts of a URL in a @RequestMapping method.

A URI Template is a URI-like string, containing one or more variable names. When you substitute values for these variables, the template becomes a URI. The proposed RFC for URI Templates defines how a URI is parameterized. For example, the URI Template http://www.example.com/users/{userId} contains the variable userId. Assigning the value fred to the variable yields http://www.example.com/users/fred.

In Spring MVC you can use the @PathVariable annotation on a method argument to bind it to the value of a URI template variable:

@RequestMapping(value="/owners/{ownerId}", method=RequestMethod.GET)
 public String findOwner(@PathVariable String ownerId, Model model) {
     Owner owner = ownerService.findOwner(ownerId);
     model.addAttribute("owner", owner);
     return "displayOwner"; 
  }

The URI Template " /owners/{ownerId}" specifies the variable name ownerId. When the controller handles this request, the value of ownerId is set to the value found in the appropriate part of the URI. For example, when a request comes in for /owners/fred, the value of ownerId is fred.

关于java - 带有 { } 大括号的 Spring MVC @Path 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26794198/

相关文章:

java - Spring REST/MVC & Security 异常处理 & 过滤链需求

java - 通过集成 Spring SAML(作为 SP)和 SimpleSAML(作为 IdP)转发错误

java - 根上下文和调度程序 servlet 上下文到底是如何进入 Spring MVC Web 应用程序的?

java - 无法使用 MongoDb GridFs 上传文件

java - 生成复合 PK null id

java - 如何将所有数据附加到一个对话框中?

java - 如何使用 Maven 插件从带有注释的现有实体生成 DDL?

java - Spring 3.0.5 和 Hibernate 3.5.3 - 包引用错误?

spring - 从 JUnit 测试访问 spring 上下文

java - 如何从另一台服务器获取请求url到spring mvc Controller 中