简体   繁体   中英

am i using correct way of JSF coding?

I'm new in JSF. Can i use this way of coding instead of using EL in JSF view? and correct me if there is something wrong in my coding or should i use better way.

@Named
@RequestScoped
public class RegistrationBacking extends Root {
    @EJB
    private UserManagerLocal userManager;
    public String register(){
        Map<String, Object> parameterMap = getRequestMap();
        User user = new User();
        user.setUserName((String) parameterMap.get("userName"));
        user.setPassword((String) parameterMap.get("password"));
        user.setEmail((String) parameterMap.get("email"));
        try{
            userManager.registerUser(user);
        } catch(UserExistsException ex) {
            Logger.getLogger(RegistrationBacking.class.getName()).log(Level.SEVERE, null, ex);
            getContext().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, getBundle().getString("loginExist"), ex.getMessage()));
            return null;
        } catch(Exception ex) {
            Logger.getLogger(RegistrationBacking.class.getName()).log(Level.SEVERE, null, ex);
            getContext().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, getBundle().getString("loginError"), ex.getMessage()));
            return null;
        }
        return "index";
    }
}

No. You're basically manually grabbing the submitted values from the request parameter map instead of binding the input values to the model. You're manually filling the model in the controller's action method. You won't be able to perform JSF-managed Conversion and Bean Validation on those inputs.

The right way is the following:

<h:form>
    <h:inputText value="#{registrationBacking.user.userName}" />
    <h:inputSecret value="#{registrationBacking.user.password}" />
    <h:inputText value="#{registrationBacking.user.email}" />
    <h:commandButton value="Register" action="#{registrationBacking.register}" />
</h:form>

And then in the backing bean:

private User user;

@PostConstruct
public void init() {
    user = new User();
}

public String register {
    try {
        // ...
    }
}

See also:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM