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() ;