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

Ara*_*lur 23 java spring spring-mvc spring-boot

我正在使用弹簧靴开发应用程序.在REST控制器中,我更喜欢使用路径变量(@PathVariabale注释).我的代码获取路径变量,但它在网址中包含{}大括号.请任何人建议我解决这个问题

@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);
    }
}
Run Code Online (Sandbox Code Playgroud)

网址

http://localhost:8080/user/item/{john}
Run Code Online (Sandbox Code Playgroud)

输出控制器

{约翰}

Jas*_*key 43

使用http://localhost:8080/user/item/john提交请求来代替.

你给Spring一个值为"{john}"的值给路径变量loginName,所以Spring用"{}"得到它

Web MVC框架 声明了这一点

URI模板模式

URI模板可用于在@RequestMapping方法中方便地访问URL的选定部分.

URI模板是类似URI的字符串,包含一个或多个变量名称.当您为这些变量替换值时,模板将成为URI.建议的URI模板RFC定义了如何参数化URI.例如,URI模板 http://www.example.com/users/ {userId} 包含变量userId. 将值fred分配给变量会产生 http://www.example.com/users/fred.

在Spring MVC中,您可以在方法参数上使用@PathVariable批注将其绑定到URI模板变量的值:

@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"; 
  }
Run Code Online (Sandbox Code Playgroud)

URI模板"/ owners/{ownerId}"指定变量名称ownerId.当控制器处理此请求时,ownerId的值将设置为URI的相应部分中找到的值.例如,当一个请求进入/ owners/fred时,ownerId的值为fred.