弹簧 MVC @Path变量,带 { } 个大括号

2022-09-01 20:28:04

我正在开发一个使用弹簧启动的应用程序。在REST控制器中,我更喜欢使用路径变量(注释)。我的代码获取路径变量,但它在url中继续{ }大括号。请任何人建议我解决这个问题@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);
    }
}

网址

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

出入控制器

{约翰}


答案 1

用于改为提交您的请求。http://localhost:8080/user/item/john

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

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

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


答案 2

推荐