Struts2对服务器端的输入校验
<一>验证的实现
在 Action 类中重写父类 ActionSupport的vilidate()方法,达到对客户端发过来的请求进行校验,父类的vilidate()方法是空实现
<二>表单用struts2标签来实现
表单页面也可以用struts2标签来实现,提交方式struts2默认是POST方式,而且全部属性加了表格标签来实现,
如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'register.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<h3>用户注册</h3>
<s:actionerror cssStyle="color:red"/>
<s:fielderror cssStyle="color:green"></s:fielderror>
<!--
<form action="register.action">
用户名:<input type="text" name="usename" /><br/>
密码:<input type="password" name="password" /><br/>
确认密码:<input type="password" name="repassword" /><br/>
年龄:<input type="text" name="age" /><br/>
出生日期:<input type="text" name="birthday" /><br/>
毕业日期<input type="text" name="graduation" /><br/>
<input type="submit" value="提交" />
</form>
-->
<s:form action="register.action" >
<s:textfield name="usename" label="usename"></s:textfield>
<s:password name="password" label="password"></s:password>
<s:password name="repassword" label="repassword" ></s:password>
<s:textfield name="age" label="age"></s:textfield>
<s:textfield name="birthday" label="birthday"></s:textfield>
<s:textfield name="graduation" label="graduation"></s:textfield>
<s:submit value="提交"></s:submit>
</s:form>
</body>
</html>
也可以在 <s:form action="register.action" theme="simple" > 加上 theme="simple" 不去用struts2 标签
<三>比较 类型转换,校验的执行顺序:
1)先进行类型转换
2)然后调用 setXxx() 方法,对属性进行赋值
3)调用vilidate()方法,进行校验
小结:
只要类型转换,和校验中发现错误信息,都不会执行execute()方法,而会返回 action标签的子标签result对应的name属性值为 input ,所对应的页面,一般是返回当前页面,并且在当前页面加上Struts2提供的标签:
<s:actionerror cssStyle="color:red"/>
<s:fielderror cssStyle="color:green"></s:fielderror>
就可以把错误信息显示给用户看,该标签还可以加样式cssStyle="color:red"
把错误信息存起来主要有两种方式:
1) this.addActionError(String anErrorMessage);
底层是用arraylist集合存储的
2)this.addFieldError(String fieldName, String errorMessage);
底层是用 LinkedHashMap<String, List<String>>() 实现的,每个表单的属性对应的错误信息又用一个ArrayList
存储
当然如果出现了错误,可以把错误清除,也可成功进入success页面,清除错误只需调用
this.clearActionErrors(); //把出现的错误清楚
this.clearFieldErrors() ;