struts2 使用Validation框架验证数据

model

public class User implements java.io.Serializable {

 // Fields

 private Integer userId;
 private String userName;
 private String userTrueName;
 private String userPassword;
 private Date createDate;

....

get

set

}

 

action

public class UserAction extends ActionSupport{

private IUserService userService;
 private User user;
 private int userId;

 

public String userLogin() throws Exception{
  String userName = user.getUserName();
  String userPassword = user.getUserPassword();
  if(userName != null && !userName.equals("")) {
   //System.out.println(userName);
   User u = userService.findByName(userName);
   if(u == null || u.equals("")) {
    this.addFieldError("user.userName", "用户名不正确,请重新输入");
    return "error";
   } else if(!u.getUserPassword().equals(userPassword)) {
    this.addFieldError("user.userPassword", "密码不正确,请重新输入");
    return "error";
   } else {
    getSession().setAttribute("userId", u.getUserId());
    getSession().setAttribute("userName",userName);
    getSession().setAttribute("userTrueName",u.getUserTrueName());
    getSession().setAttribute("password",userPassword);
    return "success";
   }
  } else {
   return "input";
  }
 }

....

get

set

}

同个包下:UserAction-validation.xml

<?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE validators PUBLIC
    "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
    "
http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">

<validators>
 <field name="user.userName">
  <field-validator type="requiredstring">
   <message>登录的用户名不能为空</message>
  </field-validator>
  <field-validator type="regex">
   <param name="expression">^[a-zA-Z][a-zA-Z0-9_]{1,15}$</param>
   <message>登录的用户名必须以字母开始,后面跟字母、数字或_,长度为1-15位</message>
  </field-validator>
 </field>
 
 <field name="user.userPassword">
  <field-validator type="requiredstring">
   <message>登录的密码不能为空</message>
  </field-validator>
  <field-validator type="regex">
   <param name="expression">^[a-zA-Z0-9!@#]{1,15}$</param>
   <message>登录的密码可以由字母、数字和! @ # 组成,长度为1-15位</message>
  </field-validator>
 </field>
</validators>

 

 出错提示文字字体颜色,添加样式

 .label {font-style:italic; }
.errorLabel {font-style:italic;color:red; }
.errorMessage {color:red; }

你可能感兴趣的:(struts2 使用Validation框架验证数据)