public class Login extends ActionSupport{ private User user=new User();//封装表单信息的JavaBean //必须提供set,get public User getUser() { return user; } public void setUser(User user) { this.user = user; } public void validate() { // TODO Auto-generated method stub super.validate(); if(null==user.getUsername()||"".equals(user.getUsername())){ addFieldError("user.username", getText("username_null")); } if(null==user.getPassword()||"".equals(user.getPassword())){ addFieldError("user.password",getText("password_null")); } } public String execute(){ if(user.getUsername().equals("tazi") && user.getPassword().equals("123456")){ //ServletActionContext addActionMessage(getText("success")); return Action.SUCCESS; }else{ addActionError(getText("fail")); return Action.INPUT; } } }
在jsp页面中表单的name属性设置为user.username,user.password
在资源文件中带参的引用Action属性的地方也要写成${user.password}
在Login-validation.xml 中field的name要改为user.username
在jsp页面中访问存储在值栈中的出错信息
由addFieldError("user.username","XXX")产生的可以用${errors['user.username'][0]}访问