获取URL路径的最后一部分

时间:2016-01-04 03:05:09

标签: java spring spring-mvc

我正在尝试使用此请求处理程序获取用户之后的最后一个字符串。是不是可以做到这一点而不是hacky?

 @Controller
 @RequestMapping("/user/*")
 public class Student{
      @RequestMapping(method = RequestMethod.GET)
      public String getUser(ModelMap model, /*, parameter that gets user id */) {
          // function that gets user id
          model.addAttribute("foo", "foo");
          return "bar";
      }
}

2 个答案:

答案 0 :(得分:4)

Spring也有@PathVariable

@Controller
 public class Student{
      @RequestMapping("/user/{id}")
      public String getUser(ModelMap model, @PathVariable String id) {
          // function that gets user id
          model.addAttribute("foo", "foo");
          return "bar";
      }
}

这里我假设用户ID是String类型,您可以根据需要更改id的类型。

答案 1 :(得分:0)

尝试使用@RequestParam,如下所示:

  @Controller
  public class Student{
  @RequestMapping(value="/user/{user_id}", method = RequestMethod.GET)
  public String getUser(ModelMap model, @RequestParam(value="user_id") Long user_id){
      // function that gets user id
      model.addAttribute("foo", "foo");
      return "bar";
  }
}

或使用@PathVariable

 @Controller
  public class Student{
  @RequestMapping(value="/user/{user_id}", method = RequestMethod.GET)
  public String getUser(ModelMap model, @PathVariable("user_id") Long user_id){
      // function that gets user id
      model.addAttribute("foo", "foo");
      return "bar";
  }
}