2016-01-04 119 views
-1

我想要獲取用戶使用此請求處理程序後的最後一個字符串。有沒有可能做到這一點,而不是哈克?獲取URL路徑的最後部分

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

請解釋你試過的。 SO不是一種編碼服務。 – jasonszhao

回答

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字符串類型,您可以更改的id類型根據自己的需要。

+0

正是我在找什麼。謝謝! – cinderblock

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