开发者

How to attemp sec:loggedInUserInfo into a variable in gsp

开发者 https://www.devze.com 2023-03-08 05:54 出处:网络
I want to get value of sec:loggedInUserInfo and attempt into a variable named user. My cod开发者_Python百科e looks like this:

I want to get value of sec:loggedInUserInfo and attempt into a variable named user.

My cod开发者_Python百科e looks like this:

<sec:loggedInUserInfo field="username" /> 

<%
  def user = *value of field loggedInUserInfo *
%>

Is it possible for doing that?


This is simpler and works fine for me:

<g:set var="user" value="${sec.username()}" />


To assign any field of the UserDetails instance referred to by <sec:loggedInUserInfo> to a variable you can use:

<g:set var="fullName" value="${sec.loggedInUserInfo(field:'fullName')}" />

(see also Custom User Details)


If you want the user object in the gsp, just pass it back as part of the model map from the controller. in a controller action do

def user = springSecurityService.getCurrentUser()
render view: 'yourgsp', model: [user: user]


I am not sure if we can use that tag directly, I couldn't find it earlier, so I have made my custom tag for this purpose

<m:userName id="${session.SPRING_SECURITY_CONTEXT?.authentication?.principal?.id}"/>

def userName = { attrs ->
Long id = attrs['id'] ? attrs['id'].toLong() : null
User user = User?.get(id);
out << user?.firstName

}


I have created one taglib as loggedinUser which is added on gsp page as :

Welcome <g:loggedInUser/> ! 

Which is showing logged In username on top of each gsp in my project. In custom tag library my code is as follows :

def springSecurityService

def loggedInUser={
    if(springSecurityService.getPrincipal().equals("anonymousUser")){
        response.sendRedirect("${request.contextPath}/login/auth")
    }else{
        out <<"${springSecurityService.currentUser.username}"
        out << """ [${link(controller:"logout"){"Logout"}}]"""
    }
}

So it's showing on each page as : Welcome USERNAME[Logout] !

0

精彩评论

暂无评论...
验证码 换一张
取 消