问题
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