[標題]:[原]Struts2輸入校驗
[時間]:2009-7-26
[摘要]:替換struts默認的類型轉換錯誤信息、給Struts標簽指定主題、使用自定義業務方法和驗證方法。
[關鍵字]:浪曦視頻,Struts2應用開發系列,WebWork,Apache,輸入校驗,validate,validation
[環境]:struts-2.1.6、JDK6、MyEclipse7、Tomcat6
[作者]:Winty (wintys@gmail.com) http://www.tkk7.com/wintys
[正文]:
1、知識點
a.validate()中添加驗證錯誤信息
當校驗出錯時,可以向客戶端輸出兩種類型的Error:
addFiledError() //可以用<s:filederror />顯示,也可以直接由Struts輸入標簽自動顯示。
addActionError() //用<s:actionerror />顯示。
b.替換struts默認的類型轉換錯誤信息
例如:如果為int型的age輸入字母,將出現類型轉換錯誤信息:Invalid field value for field "age"。
這個信息是由Struts自動提供的,可以使用全局或局部配置文件對其進行替換。
a).替換struts默認的類型轉換錯誤信息的全局配置:
在struts.xml中增加constant,指明全局配置文件的名稱為"message":
<struts>
<constant name="
struts.custom.i18n.resources" value="message">
</constant>
</struts>
在struts.xml相同目錄下新建message.properties,message.properties內容可使用中文,但需要JDK的native2ascii進行轉換。內容如下({0}代表出現錯誤的字段):
xwork.default.invalid.fieldvalue={0} error
b).替換struts默認的類型轉換錯誤信息的局部配置:
在RegisterAction.java相同目錄下新建RegisterAction.properties("\u5E74\u9F84\u8F6C\u6362\u9519\u8BEF" = "年齡轉換錯誤"):
invalid.fieldvalue.age=\u5E74\u9F84\u8F6C\u6362\u9519\u8BEF
c.給Struts標簽指定主題
<s:textfield name="name" label="name"
theme="simple">
指定simple主題,則Struts不生成table等布局。
同時,不會顯示label,也不會顯示field errror。
但與HTML input不同的是,可以保存提交失敗后的值。
d.指定自定義業務方法register()替代execute()
在struts.xml中配置:
<action name="register"
class="wintys.struts2.validation.RegisterAction"
method="register">
并在類RegisterAction中添加方法register(),與execute()簽名相同:
public String register()throws Exception{
System.out.println("register()...");
return SUCCESS;
}
e.使用自定義驗證方法validateRegister()
在類RegisterAction中添加方法validateRegister(),與validate()簽名相同:
public void validateRegister(){
System.out.println("validateRegister()...");
}
validateRegister()并不替換validate(),而是先于validate()執行。Struts從struts.xml中的配置得知register(),而使用反射尋找validateRegister()。如果有validateRegister(),則執行之。然后再執行validate()。
執行流程:validateRegister() => validate() => register()。
f.最佳實踐
給默認execute()指定另一個validateExecute(),而不重寫validate()。不把所有驗證寫在validate()中,則可以根據需要執行個性化驗證。
2、詳細代碼
/StrutsHelloWorld/WebRoot/validation/input.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>struts validation</title>
</head>
<body>
<s:actionerror cssStyle="color:red"/>
<s:fielderror></s:fielderror>
<s:form name="register" action="register" theme="simple">
用戶名:<s:textfield name="name" label="用戶名"></s:textfield><br/>
密碼:<s:textfield name="age" label="年齡"></s:textfield><br/>
<s:submit value=" 確定 "></s:submit> <br/>
</s:form>
</body>
</html>
/StrutsHelloWorld/WebRoot/validation/output.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
</head>
<body>
<s:property value="name"/><br/>
<s:property value="age"/><br/>
</body>
</html>
/StrutsHelloWorld/src/wintys/struts2/validation/RegisterAction.java:
package wintys.struts2.validation;
import com.opensymphony.xwork2.ActionSupport;
/**
*
* @author Winty (wintys@gmail.com)
* @version 2009-07-26
* http://www.tkk7.com/wintys
*/
@SuppressWarnings("serial")
public class RegisterAction extends ActionSupport {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public void validate() {
System.out.println("validate()...");
//Action Error
if(name == null || name.length() < 6 || name.length()>10){
addActionError("invalid name");
}
//Filed Error
if(age <= 0 || age > 150){
addFieldError("age", "invalid age");
}
}
@Override
public String execute() throws Exception {
System.out.println("execute()...");
return SUCCESS;
}
/**
* 自定義驗證方法,用于驗證register()。
*
* 如果客戶端請求的action name="register" ,
* 該驗證會自動執行。
*/
public void validateRegister(){
System.out.println("validateRegister()...");
}
/**
* 自定義method,代替execute(),
* 則最終只運行register() , 而不運行execute()。
*
* 需在struts.xml中配置:method="register"
* <action name="register"
* class="wintys.struts2.validation.RegisterAction"
* method="register">
*/
public String register()throws Exception{
System.out.println("register()...");
return SUCCESS;
}
}
/StrutsHelloWorld/src/wintys/struts2/validation/RegisterAction.properties:
invalid.fieldvalue.age=\u5E74\u9F84\u8F6C\u6362\u9519\u8BEF
/StrutsHelloWorld/src/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>
<!-- 定義全局錯誤信息資源文件message.properties -->
<constant name="struts.custom.i18n.resources" value="message"></constant>
<package name="MyStruts" extends="struts-default">
<action name="register" class="wintys.struts2.validation.RegisterAction" method="register">
<result name="success">/validation/output.jsp</result>
<result name="input">/validation/input.jsp</result>
</action>
</package>
</struts>
/StrutsHelloWorld/src/message.properties:
#chinese characters needs conversion by "native2ascii"
xwork.default.invalid.fieldvalue={0} error.
[參考資料]:
《浪曦視頻之Struts2應用開發系列》
[附件]:
源代碼:
http://www.tkk7.com/Files/wintys/struts_StrutsValidation.zip
posted on 2009-07-27 00:23
天堂露珠 閱讀(493)
評論(0) 編輯 收藏 所屬分類:
Struts