when using container managed authentication (as it seems is your case) the username gets stored in the container security context. The Servlet spec provides an API that allows access to the user principal (an instance of java.security.Principal
) which holds the user name.
So, once the user is logged in you can access the user principal with HttpServletRequest.getUserPrincipal()
or username HttpServletRequest.getRemoteUser()
from java code. Or with FacesContext.getCurrentInstance().getExternalContext().getRemoteUser()
To use it on a JSP/JSF file you could access it using the expression language this way: #{request.remoteUser}
as in:
<h:inputText id="username" value="#{request.remoteUser}" />
Addition:
Your user backing bean:
public class User implements Serializable {
private String name;
// other user attributes here
public String getName() {
return name;
}
}
Add JSF Filter:
public class SetupUserFilter implements Filter {
public void init(FilterConfig config) { }
public void destroy() { }
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpSession session = request.getSession(false);
if (session != null) {
User user = session.getAttribute("user");
if (user == null && request.getUserPrincipal() != null) {
// This means user has just logged in.
String username = request.getRemoteUser();
User user = ... // load the User instance from the database using the username
session.setAttribute("user", user);
}
}
chain.doFilter(req, res);
}
}
Configure your filter in your web.xml
:
<filter>
<filter-name>SetupUserFilter</filter-name>
<filter-class>com.example.SetupUserFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SetupUserFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Then rely always on the User
bean:
<h:inputText id="username" value="#{user.name}" />
Disclaimer: This is just an example, a bit old as it uses filters and other approaches may be valid as well but this one works even in non-JSF environments. Feel free to use it but understand that this is not the only way to get what you are looking for.