How to get username j_security_check as bean property
In my managed bean, I want to get the username j_security_check
that auths to the LDAP server as a property of the bean.
Basically, I want to output the username from
<input type="text" name="j_username" />
after it is sent and everything is complete and use it in the following:
@Override
public String getName() {
return getId();
}
How to use
FacesContext.getExternalContext().getUserPrincipal();
to get the username as a bean property?
This is full bean support in case you need to know what it does. I used to manually force the user to enter the username in the textbox, now I want to stop this and pull the username automatically.
//@Named("user")
@SessionScoped
public class UserBean implements Serializable, Principal {
private static final long serialVersionUID = 1L;
@NotNull(message = "The username can not be blank")
@Size(min = 6, max = 12, message = "Please enter a valid username (6-12 characters)")
//@Pattern(regexp = "[a-zA-Z0-9_]", message = "Please enter a valid username consiting of only characters that are from the alphabet or are numeric ")
//@Pattern(regexp = "(a-z)(A-Z)(0-9))", message = "Please enter a valid username consiting of only characters that are from the alphabet or are numeric ")
private String id;
public String getId() {
return id;
}
public void setId(String newValue) {
id = newValue;
}
private String fileText;
@NotNull(message = "You must select a file to upload")
public String getFileText() {
return fileText;
}
public void setFileText(String fileText) {
this.fileText = fileText;
}
/**
* public void getName(HttpServletRequest req, HttpServletResponse res)
* throws ServletException, java.io.IOException { id = req.getRemoteUser();
* }
*/
@Override
public String getName() {
return getId();
}
/*
* @Override
*
* public String request.remoteUser() { return getId();
*
* }
* .
*/
}
source to share
Initialize it in @PostConstruct
.
private String username;
@PostConstruct
public void init() {
username = FacesContext.getCurrentInstance().getExternalContext().getRemoteUser();
}
Or, if you only need it during processing, submit the form, just get it in the action method.
Note that getRemoteUser()
basically returns the same as getUserPrincipal().getName()
.
Unrelated to the specific issue: This kind of bean should not be session scope, but a view or conversation scope is available instead. Also, it doesn't have to implement the interface Principal
. It doesn't make any sense.
source to share