1.输入校验
错误提示页面
<%@ 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=UTF-8">
<title>Insert title here</title>
</head>
<s:if test="fieldErrors!=null">
<s:property value="fieldErrors['msg'][0]"/>
</s:if>
<s:debug></s:debug>
</body>
</html>
Action类
public class ValidateAction extends ActionSupport {
private String age;
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String execute() {
System.out.println("execute()方法");
return SUCCESS;
}
@Override
public void validate() {
System.out.println("validate()方法");
//判断是否为数值型
boolean isNum = age.matches("[0-9]+");
if(Integer.parseInt(age)<=18||Integer.parseInt(age)>=60) {
this.addFieldError("msg", "年龄必须是18-60之间!");
}else {
this.addFieldError("msg", "您输入的用户名不合法!");
}
}
}
struts.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<constant name="struts.devMode" value="true"></constant>
<package name="jiangwenwen" namespace="/" extends="struts-default">
<action name="validate" class="cn.jiangwenwen.action.ValidateAction">
<result>/index.jsp</result>
<result name="input">/index.jsp</result>
</action>
</package>
</struts>
2.基于配置风格的校验
编写校验配置UserAction-loginAction-validation.xml,注意名字的组成,和Action放在同一个包下面
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC
"-//Apache Struts//XWork Validator 1.0.3//EN"
"http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
<validators>
<field name="username">
<field-validator type="stringlength">
<param name="minLength">6</param>
<param name="maxLength">12</param>
<message>长度只能在6-12位</message>
</field-validator>
<field-validator type="regex">
<param name="regexExpression">
<![CDATA[(^[^ ]{1,}$)]]>
</param>
<message>不能为空</message>
</field-validator>
</field>
<field name="userpwd">
<field-validator type="requiredstring">
<message>密码不允许为空</message>
</field-validator>
</field>
</validators>
编写struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<constant name="struts.devMode" value="true"></constant>
<package name="jiangwenwen" namespace="/" extends="struts-default">
<action name="loginAction" class="cn.jiangwenwen.action.UserAction" method="login">
<result name="input">/test.jsp</result>
</action>
</package>
</struts>