Get UserDetails object from Security Context in Spring MVC controller

前端 未结 6 454
栀梦
栀梦 2020-12-04 06:26

I\'m using Spring Security 3 and Spring MVC 3.05.

I would like to print username of currently logged in user,how can I fetch UserDetails in my Controller?

         


        
6条回答
  •  感情败类
    2020-12-04 07:17

    If you just want to print user name on the pages, maybe you'll like this solution. It's free from object castings and works without Spring Security too:

    @RequestMapping(value = "/index.html", method = RequestMethod.GET)
    public ModelAndView indexView(HttpServletRequest request) {
    
        ModelAndView mv = new ModelAndView("index");
    
        String userName = "not logged in"; // Any default user  name
        Principal principal = request.getUserPrincipal();
        if (principal != null) {
            userName = principal.getName();
        }
    
        mv.addObject("username", userName);
    
        // By adding a little code (same way) you can check if user has any
        // roles you need, for example:
    
        boolean fAdmin = request.isUserInRole("ROLE_ADMIN");
        mv.addObject("isAdmin", fAdmin);
    
        return mv;
    }
    

    Note "HttpServletRequest request" parameter added.

    Works fine because Spring injects it's own objects (wrappers) for HttpServletRequest, Principal etc., so you can use standard java methods to retrieve user information.

提交回复
热议问题