【问题标题】:How to get logged user name/Principal in Spring MVC REST channel?如何在 Spring MVC REST 通道中获取记录的用户名/主体?
【发布时间】:2013-07-18 10:08:09
【问题描述】:

我有 Spring MVC REST 通道:

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

我有我的方法:

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

现在我需要登录的用户名,一般我可以通过方法来完成

HttpServletRequest.getUserPrincipal()

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

【问题讨论】:

    标签: java spring spring-mvc httprequest principal


    【解决方案1】:

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

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

    the spring reference manual for more info

    【讨论】:

      【解决方案2】:

      假设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 }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-12-16
        • 2019-02-06
        • 2012-07-30
        • 1970-01-01
        • 2015-04-15
        • 2017-11-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多