我有Spring MVC REST频道:
@Controller
@RequestMapping("/rest")
public class REST {
我有我的方法:
@RequestMapping(value = "/doSomething")
public @ResponseBody DoSomethingResultDTO doSomething(
@RequestBody DoSomethingRequestDTO)
现在我需要登录用户的名字。通常我可以通过方法
来完成HttpServletRequest.getUserPrincipal()
但如何在这里得到它?我有标题(@RequestHeader
),甚至是Cookie(@CookieValue
)的注释。但是如何在我的方法中获得Principal
?
答案 0 :(得分:23)
您可以将Principal对象注入控制器处理程序方法
@RequestMapping(value = "/doSomething")
public @ResponseBody DoSomethingResultDTO doSomething(
@RequestBody DoSomethingRequestDTO, Principal principal)
答案 1 :(得分:4)
您还可以通过注释来假设CustomUser实现UserDetails
@RequestMapping(value = { "/home" }, method = RequestMethod.GET)
public String home(@AuthenticationPrincipal CustomUser customUser, Model model, HttpServletRequest request,
HttpServletResponse response, Locale locale) throws Exception {
System.out.println("Entering Home Controller @AuthenticationPrincipal: " + customUser);
}
public class CustomUser implements UserDetails { // code omitted }