如何在Spring MVC REST通道中获取登录的用户名/ Principal?

时间:2013-07-18 10:08:10

标签: java spring spring-mvc httprequest principal

我有Spring MVC REST频道:

@Controller
@RequestMapping("/rest")
public class REST {

我有我的方法:

@RequestMapping(value = "/doSomething")
public @ResponseBody DoSomethingResultDTO doSomething(
    @RequestBody DoSomethingRequestDTO)

现在我需要登录用户的名字。通常我可以通过方法

来完成
HttpServletRequest.getUserPrincipal()

但如何在这里得到它?我有标题(@RequestHeader),甚至是Cookie(@CookieValue)的注释。但是如何在我的方法中获得Principal

2 个答案:

答案 0 :(得分:23)

您可以将Principal对象注入控制器处理程序方法

@RequestMapping(value = "/doSomething")
public @ResponseBody DoSomethingResultDTO doSomething(
    @RequestBody DoSomethingRequestDTO, Principal principal)

请参阅the spring reference manual for more info

答案 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 }