Structs2 校验框架
代码结构:
使用Struts校验框架,保证输入学生的基本信息:学号、姓名、性别、出生年月、专业、总学分等,要求输入满足以下条件:
(1) 学号前两位大于“13”并且后面4位必须为数字;
(2) 出生年月必须保证年龄大于等于18岁;
(3) 专业不能为空;
(4) 总学分在0-80之间。
RegistAction.java
package com.action; import java.util.*; import com.bean.User; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; public class RegistAction extends ActionSupport { private User user; public User getUser() { return user; } public void setUser(User user) { this.user = user; } public String execute() throws Exception { if(hasErrors()){ return INPUT; } return SUCCESS; } public void validate(){ Calendar cal = Calendar.getInstance(); String[] str = user.getBir().split("-"); int yearNow = cal.get(Calendar.YEAR); int monthNow = cal.get(Calendar.MONTH)+1; int dayNow = cal.get(Calendar.DAY_OF_MONTH); int yearBirth=Integer.parseInt(str[0]); int monthBirth=Integer.parseInt(str[1]); int dayBirth=Integer.parseInt(str[2]); int age=yearNow-yearBirth; if(monthNow<=monthBirth || (monthNow == monthBirth && dayNow < dayBirth)) age--; if(age < 18){ addFieldError("user.bir", "出生年月必须保证年龄大于等于18岁!");//QAQ } } }
RegistAction-validation.xml
<?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="user.id"> <field-validator type="regex"> <param name="expression"><![CDATA[(^(1[4-9]|[2-9][0-9]\d).*\d{4}$)]]></param> <message>学号前两位大于“13”并且后面4位必须为数字!</message> </field-validator> <field-validator type="requiredstring"> <param name="trim">true</param> <message>学号不能为空!</message> </field-validator> </field> <field name="user.major"> <field-validator type="requiredstring"> <param name="trim">true</param> <message>专业不能为空!</message> </field-validator> </field> <field name="user.score"> <field-validator type="required"> <message>请输入用户考试成绩</message> </field-validator> <field-validator type="int"> <param name="min">0</param> <param name="max">80</param> <message>学分必须在0-80之间!</message> </field-validator> </field> </validators>
User.java
package com.bean; import java.util.Date; import com.bean.*;
public class User { //学号、姓名、性别、出生年月、专业、总学分等 private String id; private String username; private String agender; private String bir; //生日类/自定义类型转换/将生日的年月取出方便计算年龄 private int age; private String major; private int score; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getAgender() { return agender; } public void setAgender(String agender) { this.agender = agender; } public String getBir() { return bir; } public void setBir(String bir) { this.bir = bir; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getMajor() { return major; } public void setMajor(String major) { this.major = major; } public int getScore() { return score; } public void setScore(int score) { this.score = score; } }
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"> <struts> <package name="default" extends="struts-default"> <action name="myform" class="com.action.RegistAction"> <result name="success">/success.jsp</result> <result name="input">/index.jsp</result> </action> </package> </struts>
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@taglib uri="/struts-tags" prefix="s" %> <html> <head> <title>注册页面</title> <!-- <script type="text/javascript"> --> <!-- function validateAge(){ --> <!-- var birthday=$('#user.age').val(); //假设用户输入的是这种格式 birthday="2017-10-11" --> <!-- var birthday1=birthday.split('-'); --> <!-- var convert2Date= new Date(birthday1[0],birthday1[1],birthday1[2]);//把字符串转换成日期 --> <!-- var nowDate=new Date(); //获取当前时间 --> <!-- //var year=nowDate.getFullYear(); --> <!-- //var month=nowDate.getMonth()+1; --> <!-- //var date=nowDate.getDate(); --> <!-- //var nowDate=new Date(year,month,date); --> <!-- var age=nowDate.getTime()-convert2Date.getTime(); //毫秒 --> <!-- age=age/(24*3600*1000); //天数 至于转换成多少年(岁),详细的还要根据是否闰年计算 age/(24*3600*1000*366) 或者 age/(24*3600*1000*365) --> <!-- } --> <!-- </script> --> </head> <body> <s:form action="myform" method="post"> <s:textfield name="user.id" label="学号"></s:textfield> <s:textfield name="user.username" label="姓名"></s:textfield> <s:radio name="user.agender" list="#{1:'男',0:'女'}" label="性别" value="1"></s:radio> <s:textfield name="user.bir" label="生日" placeholder="xxxx-xx-xx"></s:textfield> <!-- <s:hidden name="user.age" label="年龄"></s:hidden> --> <s:textfield name="user.major" label="专业"></s:textfield> <s:textfield name="user.score" label="总学分"></s:textfield> <s:submit value="提交"></s:submit> </s:form> </body> </html>
success.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@taglib uri="/struts-tags" prefix="s" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>成功页面</title> </head> <body> 恭喜<s:property value="user.username"/>!您已经注册成功! </body> </html>