简体   繁体   中英

Get last part of URL path

I'm trying to get the last string after user with this request handler. Is it possible to do this without being 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";
      }
}

Spring has @PathVariable for the same.

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

Here I have assumed that user id is of String type, you may change the type of id as per your need.

Try to use @RequestParam like this:

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

Or use @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";
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM