10

我有 Spring MVC REST 频道:

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

我有我的方法:

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

现在我需要登录用户的名称。通常我可以通过方法来完成

HttpServletRequest.getUserPrincipal()

但是如何在这里得到它?我有标头 ( @RequestHeader) 甚至 cookie ( @CookieValue) 的注释。但是我怎样才能得到Principal我的方法呢?

4

2 回答 2

24

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

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

有关更多信息,请参阅弹簧参考手册

于 2013-07-18T11:49:26.507 回答
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 }
于 2016-09-22T11:52:03.193 回答