标签:struts2 方法校验 actionsupport invidate fielderror
有时我们需要对Action中注入的字段进行校验,这时我们就需要用到invidate()方法了。
首先需要Action实现ActionSupport,然后重写invidate()方法,在其中对字段进行校验。
如果校验合法,则执行action中的相应方法(一般为execute),请求转发到相应的jsp;
如果校验失败,可以通过addFieldError()方法将错误信息添加到FieldErrors中,
此时action中的相应方法(一般为execute)不会执行,struts2框架默认返回"input"结果,
此时可以在struts2.xml相应的action中声明结果<result name="input"></result>,
跳转回最初的输入页面。并在最初的输入页面用:
<s:fielderror fieldName="XXX" ></s:fielderror>输出错误信息。
输入页面person.jsp:
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <%@ taglib uri="/struts-tags" prefix="s"%> <!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> <body> <form action="${pageContext.request.contextPath }/invidateAction_execute1.action" method="post"> 用户名:<input type="text" name="username"><s:fielderror fieldName="username" ></s:fielderror><br> 手机号:<input type="text" name="tel"><s:fielderror fieldName="tel" ></s:fielderror><br> <input type="submit" value="提交"> </form> </body> </html>
<action name="invidateAction_*" class="com.itheima.action.InvidateAction" method="{1}"> <result name="success">/success.jsp</result> <result name="input">/person.jsp</result> </action>InvidateAction.jsva:
package com.itheima.action; import java.util.regex.Pattern; import com.opensymphony.xwork2.ActionSupport; public class InvidateAction extends ActionSupport{ private String username; private String tel; private String msg; public void setUsername(String username) { this.username = username; } public void setTel(String tel) { this.tel = tel; } public String getMsg() { return msg; } @Override public void validate() { if(username == null || "".equals(username.trim())) { addFieldError("username", "用户名不能为空"); } else if(tel == null || "".equals(tel.trim())) { addFieldError("tel", "手机号不能为空"); } else if(!Pattern.compile("^1[358]\\d{9}$").matcher(tel).matches()) { addFieldError("tel", "手机号格式不正确"); } } public String execute1() { msg = "execute1"; return "success"; } public String execute2() { msg = "execute2"; return "success"; } }
===================================================================================================
以上方式是对action中的所有方法进行校验,如果只针对某一方法进行校验,则只需要invidate()方法改为
invidateXXX()方法即可。这里:
invidateExecute1():只对excute1()方法进行校验
invidateExecute2():只对excute2()方法进行校验
标签:struts2 方法校验 actionsupport invidate fielderror
原文地址:http://blog.csdn.net/m631521383/article/details/40710545