get j_username in j_security_check JSF 2.0

本小妞迷上赌 提交于 2019-12-12 01:03:54

问题


I have simple page, I want to retrieve j_username to save it in session as a logged in user, i can't fetch it from the form. here Server it self perform authentication in this code

<h:form id="login" onsubmit="document.getElementById('login').action='j_security_check';" prependId="false">
                <h:panelGrid columns="2">
                    <p:outputLabel for="j_username" value="Username" />
                    <p:inputText id="j_username" name="j_username"/>            
                    <p:outputLabel for="j_password" value="Password" />
                    <p:password id="j_password" name="j_password" value=""/>
                    <p:commandButton style="font-size:15px" type="submit"  value="Login" ajax="false"/>
                    <p:commandButton style="font-size:15px" type="clear" value="Clear" ajax="false"/>
                </h:panelGrid>
            </h:form>

回答1:


It's available by HttpServletRequest#getRemoteUser() which is in JSF context delegated by ExternalContext#getRemoteUser().

So, this should do either in the view:

<ui:fragment rendered="#{empty request.remoteUser}">
    <p>This is only rendered when someone's NOT logged in.</p>
</ui:fragment>
<ui:fragment rendered="#{not empty request.remoteUser}">
    <p>This is only rendered when someone's been logged in.</p>
    <p>Welcome, you're logged in as #{request.remoteUser}!</p>
</ui:fragment>

or in the managed bean:

ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
String username = ec.getRemoteUser();
// ...

Unrelated to the concrete problem: it's better to get rid of that onsubmit nonsense and just use plain <form> instead of <h:form>.

<form id="login" action="j_security_check">

This way it'll also work on JS-disabled clients.

See also:

  • Performing user authentication in Java EE / JSF using j_security_check


来源:https://stackoverflow.com/questions/21546511/get-j-username-in-j-security-check-jsf-2-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!