使用基于XML配置方式实现输入校验时,action也要继承ActionSupport,并且提供校验文件,校验文件和action类放在同一个包下,文件的取名格式为:ActionClassName-validate.xml,其中ActionClassName为简单类名,-validate为固定写法。
输入页面index.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:fielderror/> <form action="${pageContext.request.contextPath}/control/manage_save.action" method="post"> 管理用户名:<input type="text" name="username" />不能为空<br> 手机号码:<input type="text" name="mobilephone" /> 不能为空,并且要符合手机号码格式1,3/5/8,后面9位数字<br> <input type="submit" value="提交" /> </form> </body> </html>
package struts2.validate.action; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; public class PersonAction extends ActionSupport{ private String username; private String mobilephone; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getMobilephone() { return mobilephone; } public void setMobilephone(String mobilephone) { this.mobilephone = mobilephone; } public String update() { ActionContext.getContext().put("message", "更新成功!"); return "message"; } public String save() { ActionContext.getContext().put("message", "保存成功"); return "message"; } }
校验文件PersonAction-validation.xml
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.3//EN" "http://www.opensymphony.com/xwork/xwork-validator-1.0.3.dtd"> <validators> <field name="username"> <field-validator type="requiredstring"> <param name="trim">true</param> <message>用户名不能为空!</message> </field-validator> </field> <field name="mobilephone"> <field-validator type="requiredstring"> <param name="trim">true</param> <message>手机号码不能为空!</message> </field-validator> <field-validator type="regex"> <param name="expression"><![CDATA[^1[358]\d{9}$]]></param> <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.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <package name="csdn" namespace="/control" extends="struts-default"> <action name="manage_*" class="struts2.validate.action.PersonAction" method="{1}"> <result name="message">/WEB-INF/page/message.jsp</result> <result name="input">/index.jsp</result> </action> </package> </struts>
时间: 2024-10-14 22:16:36