首页 > 解决方案 > 我可以从 /info/{login} 获得价值吗?

问题描述

我有这门课

@RestController
public class TestController {

    @RequestMapping(value = "/info/{login}", method = RequestMethod.GET)
    public @ResponseBody String getLogin() {
       String login = ?
       return login;
    }
}

我可以以某种方式解析 {login} 的值吗?

例如:

http://localhost:8080/info/1234

我的方法返回“1234”;

http://localhost:8080/info/298

我的方法返回“298”。

标签: javaspringhttp

解决方案


您只需要为登录值声明一个变量并使用以下内容进行注释@PathVariable

@RestController
public class TestController {

  @RequestMapping(value = "/info/{login}", method = RequestMethod.GET)
  public @ResponseBody String getLogin(@PathVariable("login") String login) {
    return login;
  }
}

Baeldung 对强大的选项有很好的解释:https ://www.baeldung.com/spring-requestmapping#path-variable


推荐阅读