Frage

In my managed bean, I wish to fetch the j_security_check username, which auths to a LDAP server, as a bean property.

Essentially, I want to pull the username from

<input type="text" name="j_username" />

once it is submited and all authed and use it in the following:

@Override
public String getName() {
    return getId();
}

How would I use

FacesContext.getExternalContext().getUserPrincipal();

to get the username as bean property?

This is the complete backing bean if you need to know what is doing. I used to manually have the user to enter a username in a text box, I want to now stop this and have it automatically pull the username.

//@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();
     *
     * }
     * .
     */
} 
War es hilfreich?

Lösung

Initialize it in @PostConstruct.

private String username;

@PostConstruct
public void init() {
    username = FacesContext.getCurrentInstance().getExternalContext().getRemoteUser();
}

Or, if you only need it during processing the form submit, just obtain it in action method instead.

Note that getRemoteUser() basically returns the same as getUserPrincipal().getName().


Unrelated to the concrete problem: this kind of bean shouldn't be session scoped, but instead view or conversation scoped. Also, it should not implement the Principal interface. That makes no utter sense.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top