Get Spring Security Principal in JSP EL expression

后端 未结 11 2039
终归单人心
终归单人心 2020-12-13 04:07

I am using Spring MVC and Spring Security version 3.0.6.RELEASE. What is the easiest way to get the user name in my JSP? Or even just whether or not the user is logged in? I

11条回答
  •  既然无缘
    2020-12-13 04:43

    1) MY CUSTOM USER CLASS with extra field mobile:

     public class SiteUser extends User {
    
        public SiteUser(String username, String password, Collection authorities,
                String mobile) {
            super(username, password, true, true, true, true, authorities);
            this.mobile = mobile;
        }
    
        private String mobile;
    
        public String getMobile() {
            return mobile;
        }
    
        public void setMobile(String mobile) {
            this.mobile = mobile;
        }
    
    }
    

    2) IN MY UserDetailsServiceImpl.java I POPULATED THIS CUSTOM SiteUser object.

    public SiteUser loadUserByUsername(String username)  {
            UserInfoVO userInfoVO = userDAO.getUserInfo(username);
            GrantedAuthority authority = new SimpleGrantedAuthority(userInfoVO.getRole());
    
            SiteUser siteUser = new SiteUser(userInfoVO.getUsername(), userInfoVO.getPassword(),
                    Arrays.asList(authority), userInfoVO.getMobile());
    
            return siteUser;
    }
    

    3) AND IN VIEW I AM ACCESSING IT AS:

    < a href="#" th:text="${#httpServletRequest.userPrincipal.principal.mobile}">

提交回复
热议问题