本文主要介绍了struts2的手动校验表单提交的数据
login.jsp文件
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<s:form action="testValidator" name="gerForm" validate="true" >
<s:textfield label="用户名" name="name"></s:textfield>
<s:password label="密码" name="pwd"></s:password>
<s:textfield label="邮箱" name="email"></s:textfield>
<s:submit label="注册" ></s:submit>
</s:form>
<s:debug></s:debug>
</body>
</html>
MyValidator.java文件
<span style="font-size:14px;">package com;
import java.util.regex.Pattern;
import com.opensymphony.xwork2.ActionSupport;
public class MyValidator extends ActionSupport {
private String name;
private String pwd;
private String email;
public void validateRegister(){
System.out.println("validate start");
if(name==null || "".equals(name.trim())){
this.addFieldError("name", "用户名不能为空");
}else if(!Pattern.matches(".{5,10}", name.trim())){
this.addFieldError("name", "用户名长度应该为5-10个字符");
}else if(!Pattern.matches("\\w{5,10}",name.trim())){
this.addFieldError("name", "用户名只能是字母,数字,下划线");
}
if(pwd==null || "".equals(pwd.trim())){
this.addFieldError("pwd", "密码不能为空");
}else if(!Pattern.matches(".{5,10}", pwd.trim())){
this.addFieldError("pwd", "密码长度应该为5-10个字符");
}
if(email==null || "".equals(email.trim())){
this.addFieldError("email", "email不能为空");
}else if(!Pattern.matches( "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$", email.trim())){
this.addFieldError("email", "email不符合格式");
}
}
public String register() throws Exception {
return SUCCESS;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}</span>
验证结果如下: