官术网_书友最值得收藏!

How to do it...

We need to perform the following steps to try this recipe:

  1. Let's create a User class as the main object of our recipe:
public class User implements Serializable {

private String name;
private String email;

public User(String name, String email) {
this.name = name;
this.email = email;
}

//DON'T FORGET THE GETTERS AND SETTERS
//THIS RECIPE WON'T WORK WITHOUT THEM
}
  1. Now, we create a UserBean class to manage our UI:
@Named
@ViewScoped
public class UserBean implements Serializable {

private User user;

public UserBean(){
user = new User("Elder Moraes", "elder@eldermoraes.com");
}

public void userAction(){
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage("Name|Password welformed"));
}

//DON'T FORGET THE GETTERS AND SETTERS
//THIS RECIPE WON'T WORK WITHOUT THEM
}
  1. Now, we implement the Converter interface with a User parameter:
@FacesConverter("userConverter")
public class UserConverter implements Converter<User> {

@Override
public String getAsString(FacesContext fc, UIComponent uic,
User user) {
return user.getName() + "|" + user.getEmail();
}

@Override
public User getAsObject(FacesContext fc, UIComponent uic,
String string) {
return new User(string.substring(0, string.indexOf("|")),
string.substring(string.indexOf("|") + 1));
}

}
  1. Now, we implement the Validator interface with a User parameter:
@FacesValidator("userValidator")
public class UserValidator implements Validator<User> {

@Override
public void validate(FacesContext fc, UIComponent uic,
User user)
throws ValidatorException {
if(!user.getEmail().contains("@")){
throw new ValidatorException(new FacesMessage(null,
"Malformed e-mail"));
}
}
}
  1. And then, we create our UI using all of them:
<h:body>
<h:form>
<h:panelGrid columns="3">
<h:outputLabel value="Name|E-mail:"
for="userNameEmail"/>
<h:inputText id="userNameEmail"
value="#{userBean.user}"
converter="userConverter" validator="userValidator"/>
<h:message for="userNameEmail"/>
</h:panelGrid>
<h:commandButton value="Validate"
action="#{userBean.userAction()}"/>
</h:form>
</h:body>

Don't forget to run it in a Jakarta EE 8 server.

主站蜘蛛池模板: 永兴县| 茂名市| 彭水| 潞西市| 连平县| 泾阳县| 青田县| 辉南县| 都兰县| 黔江区| 德庆县| 镇坪县| 武安市| 深州市| 尼勒克县| 吉木萨尔县| 台东市| 资溪县| 河间市| 曲阳县| 武城县| 瑞安市| 大厂| 闽侯县| 巴楚县| 偏关县| 军事| 宜兰县| 普兰县| 长汀县| 阿鲁科尔沁旗| 盱眙县| 嘉荫县| 得荣县| 崇明县| 正镶白旗| 天镇县| 广水市| 泌阳县| 葵青区| 靖宇县|