Struts 学习笔记2(输入校验、国际化、异常处理)
項目文件結構
?
項目源文件下載地址:http://dl.dbank.com/c05qyg3yir
?
Struts2的輸入校驗
Struts2輸入校驗、執行流程:
1)首先進行類型轉換
2)然后進行輸入校驗(執行validate方法)
3)如果在上述過程中出現了任何錯誤,都不會再去執行 execute方法,會轉向 struts.xml 中該 action 的名為 input 的 result 所對應的頁面。
要點:
1. ActionSupport 類的 addActionError()方法的實現:首先創建一個ArrayList對象,然后將錯誤消息添加到該 ArrayList對象中。
2. 當調用 getActionErrors()方法返回 Action 級別的錯誤信息列表時,返回的實際上是集合的一個副本而不是集合本身,因此對集合副本調用 clear()方法清除的依舊是副本中的元素而非原集合中的元素,此時原集合中的內容沒有收到任何的影響。換句話說,Action級別的錯誤信息列表對開發者來說是只讀的。
3. Field Error 級別的錯誤信息底層是用 LinkedHashMap 實現的,該Map 的 key 是 String 類型,value 是 List<String>類型,這就表示一個 Field Name 可以對應多條錯誤信息,這些錯誤信息都放置在List<String>集合當中。
?
register.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
………………………………
<body>
<h2><font color="blue">用戶注冊</font></h2>
<s:actionerror cssStyle="color:red"/>
----------------------------------------
<s:fielderror cssStyle="color:blue"></s:fielderror>
?
<!--
<form action="register.action">
?
username: <input type="text" name="username" size="20"><br>
password: <input type="password" name="password" size="20"><br>
repassword: <input type="password" name="repassword" size="20"><br>
age: <input type="text" name="age" size="20"><br>
birthday: <input type="text" name="birthday" size="20"><br>
graduation: <input type="text" name="graduation" size="20"><br>
?
<input type="submit" value="submit"/>
?
</form>
-->
<s:form action="register.action" theme="simple"><!—-加theme="simple修飾以簡單表單呈現-->
username: <s:textfield name="username" label="username"></s:textfield><br>
password: <s:password name="password" label="password"></s:password><br>
repassword: <s:password name="repassword" label="repassword"></s:password><br>
age: <s:textfield name="age" label="age"></s:textfield><br>
birthday: <s:textfield name="birthday" label="birthday"></s:textfield><br>
graduation: <s:textfield name="graduation" label="graduation"></s:textfield><br>
<s:submit value="submit"></s:submit>
</s:form>
</body>
</html>
?
RegisterAction.java
package com.shengsiyuan.struts2;
?
import java.util.Calendar;
import java.util.Date;
?
import com.opensymphony.xwork2.ActionSupport;
?
public class RegisterAction extends ActionSupport
{
????private String username;
????private String password;
????private String repassword;
????private int age;
????private Date birthday;
????private Date graduation;
????public String getUsername()
????{
????????return username;
????}
????public void setUsername(String username)
????{
????????this.username = username;
????}
????public String getPassword()
????{
????????return password;
????}
????public void setPassword(String password)
????{
????????this.password = password;
????}
????public String getRepassword()
????{
????????return repassword;
????}
????public void setRepassword(String repassword)
????{
????????this.repassword = repassword;
????}
????public int getAge()
????{
????????return age;
????}
????public void setAge(int age)
????{
????????this.age = age;
????}
????public Date getBirthday()
????{
????????return birthday;
????}
????public void setBirthday(Date birthday)
????{
????????this.birthday = birthday;
????}
????public Date getGraduation()
????{
????????return graduation;
????}
????public void setGraduation(Date graduation)
????{
????????this.graduation = graduation;
????}
????@Override
????public String execute() throws Exception
????{
????????return SUCCESS;
????}
????@Override
????public void validate()
????{
????????if(null == username || username.length() < 4 || username.length() > 6)
????????{
????????????this.addActionError("username invalid");????//Action級別的錯誤
????????????this.addFieldError("username", "username invalid in field");//field級別的錯誤
????????}
????????if(null == password || password.length() < 4 || password.length() > 6)
????????{
????????????this.addActionError("password invalid");
????????}
????????else if(null == repassword || repassword.length() < 4 || repassword.length() > 6)
????????{
????????????this.addActionError("repassword invalid");
????????}
????????else if(!password.equals(repassword))
????????{
????????????this.addActionError("the passwords not the same");
????????}
????????if(age < 10 || age > 50)
????????{
????????????this.addActionError("age invalid");
????????}
????????if(null == birthday)
????????{
????????????this.addActionError("birthday invalid");
????????}
????????if(null == graduation)
????????{
????????????this.addActionError("graduation invalid");
????????}
????????if(null != birthday && null != graduation)
????????{
????????????Calendar c1 = Calendar.getInstance();????//獲取日期
????????????c1.setTime(birthday);
????????????
????????????Calendar c2 = Calendar.getInstance();
????????????c2.setTime(graduation);
????????????
????????????if(!c1.before(c2)) //如果c1不在c2前
????????????{
????????????????this.addActionError("birthday should be before graduation");
????????????}
????????}
????????//this.getFieldErrors().clear();????//clear()方法清空的只是副本
????????//this.getActionErrors().clear();
????????//this.clearActionErrors();????//清除Action級別的錯誤消息
????????//this.clearFieldErrors();????//清除field級別的錯誤消息
????????System.out.println("invoked!!!");
????}
}
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="struts2" extends="struts-default">
???? ?
????????<action name="login" class="com.shengsiyuan.struts2.LoginAction" method="myExecute">????<!-- 指定執行myExecute方法 -->
????????????<result name="success">/result.jsp</result><!-- 結果為success時,跳轉到result.jsp -->
????????</action>
????????
????????<action name="userAction" class="com.shengsiyuan.struts2.UserAction">
????????????<result name="success">/output.jsp</result>
????????</action>
????????
????????<action name="userAction2" class="com.shengsiyuan.struts2.UserAction2">
????????????<result name="success">/output.jsp</result>
????????</action>
????????
????????<action name="register" class="com.shengsiyuan.struts2.RegisterAction">
????????????<result name="success">/registerResult.jsp</result>
????????????<result name="input">/register.jsp</result>
????????</action>
????</package>
</struts>
?
截圖
提交之前截圖
以html標簽提交之后的截圖
以struts標簽,且未加theme="simple"屬性提交的結果
若使用<s:form action="register.action" theme="simple">則呈現的結果同以html提交一樣。不管是Action級別的,還是field級別的,在執行excute方法時,只要對應的錯誤容器中有錯誤消息,則轉到input對應的頁面,如果容器中沒有錯誤消息,則繼續往下執行。
?
----------------------------------------------------------
在tomcat中手動添加web項目:
????…………
<Context path="/myWebSite" docBase="D:/Workspace/servlet/myWebSite" reloadable="true"/>
</Host>
</Engine>
</Service>
</Server>
?
java.lang.ClassNotFoundException: javax.el.ELResolver錯誤解決方法:Remove of classpath server-api.jar and jsp-api.jar
-------------------------------------------------------------
?
Action級別的自定義方法的輸入校驗
要點:
1. Action中自定義方法的輸入校驗。對于通過action的method屬性所指定的自定義方法,其對應的自定義輸入校驗方法名為validateMyExecute(假設自定義的方法名為 myExecute) 。底層是通過反射來調用的。
2. 當在Action中指定了自定義的 execute方法時,首先會執行自定義的 execute 方法所對應的輸入校驗方法,然后再去執行標準的 validate 方法,執行完畢后如果出現了任何錯誤都不會再去執行自定義的execute方法,流程轉向了 input這個名字所對應的頁面上。
?
Login.jsp
…………
<body>
<form action="login.action">
username: <input type="text" name="username"><br>
password: <input type="password" name="password"><br>
age: <input type="text" name="age"><br>
date: <input type="text" name="date"><br>
<input type="submit" value="submit">
</form>
</body>
</html>
?
LoginAction
package com.shengsiyuan.struts2;
?
import java.util.Date;
?
import com.opensymphony.xwork2.ActionSupport;
import com.shengsiyuan.exception.PasswordException;
import com.shengsiyuan.exception.UsernameException;
?
public class LoginAction extends ActionSupport
{
????private String username;
????private String password;
????private int age;
????private Date date;
????
????public Date getDate()
????{
????????return date;
????}
?
????public void setDate(Date date)
????{
????????this.date = date;
????}
?
????public int getAge()
????{
????????return age;
????}
?
????public void setAge(int age)
????{
????????this.age = age;
????}
?
????public String getUsername()
????{
????????return username;
????}
?
????public void setUsername(String username)
????{
????????this.username = username;
????}
?
????public String getPassword()
????{
????????return password;
????}
?
????public void setPassword(String password)
????{
????????this.password = password;
????}
????
????public String execute() throws Exception
????{
????????if(!"hello".equals(username))
????????{
????????????throw new UsernameException("username invalid");
????????}
????????if(!"world".equals(password))
????????{
????????????throw new PasswordException("password invalid");
????????}
????????return SUCCESS;
????}
????
????//自定的execute方法,在struts.xml中指定了LoginAction中的method方法為myExecute
????public String myExecute() throws Exception
????{
????????System.out.println("myExecute invoked!!");
????????return SUCCESS;
????}
????
????//Action自定義方法的輸入校驗
????public void validateMyExecute()????//此驗證方法規定為將myExecute()方法名首字母大寫后,再加前綴validate構成
????{
????????System.out.println("validateMyExecute invoked!!");
????????this.addActionError("action error");
????}
????
????@Override
????public void validate()
????{
????????//System.out.println("validate invoked!");
????????//this.addActionError("action error");
????}
}
注:如果去除了struts.xml文件中的method="myExecute",則對應的自定義的校驗方法將無效。
<action name="login" class="com.shengsiyuan.struts2.LoginAction " method="myExecute">
????<result name="success">/result.jsp</result>
</action>
?
自定義Field級別的錯誤提示消息
要點:
1) 新建一個以 Action 名命名的 properties 文件 , 如RegisterAction.properties。 屬性文件名要求為對應的Action文件名字。
2) 然后在該屬性文件中指定每一個出錯字段的錯誤消息 invalid.fieldvalue.birthday=birthday invalid !!
?
Tip: jdk提供的一款中文轉換為unicode編碼的工具,在jdk的bin目錄下,native2ascii。在命令行下使用,使用方法如下:
?
struts2校驗框架
要點:
1) 首先執行校驗框架(xml文件)
2) 執行自定義方法的校驗方法(validateMyExecute)
3) 執行validate方法
?
xwork-validator.xml
<?xml version="1.0" encoding="UTF-8"?>
<!--
XWork Validators DTD.
Used the following DOCTYPE.
?
<!DOCTYPE validators PUBLIC
????????"-//OpenSymphony Group//XWork Validator 1.0.2//EN"
????????"http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
-->
<!ELEMENT validators (field|validator)+><!—字段優先與校驗器優先兩種-->
?
<!ELEMENT field (field-validator+)>
<!ATTLIST field
????name CDATA #REQUIRED
>
<!ELEMENT field-validator (param*, message)>
<!ATTLIST field-validator
????type CDATA #REQUIRED
short-circuit (true|false) "false"
>
<!ELEMENT validator (param*, message)>
<!ATTLIST validator
????type CDATA #REQUIRED
short-circuit (true|false) "false"
>
<!ELEMENT param (#PCDATA)>
<!ATTLIST param
name CDATA #REQUIRED
>
<!ELEMENT message (#PCDATA)>
<!ATTLIST message
key CDATA #IMPLIED
>
?
RegisterAcion-validation.xml
字段優先校驗
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN" "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
<validators>
????<field name="username"><!-- 對username設置校驗規則 -->
????????<field-validator type="requiredstring"><!-- 字符串必填規則設置 -->
????????????<param name="trim">false</param><!-- 不清除空格 -->
????????????<message>username can't be blank!</message><!-- 當校驗失敗提示的錯誤消息 -->
????????</field-validator>
????????<field-validator type="stringlength"><!-- 字符串長度規則設置 -->
????????????<param name="minLength">4</param><!-- 最小長度 -->
????????????<param name="maxLength">6</param><!-- 最大長度 -->
????????????<param name="trim">false</param>
????????????<!—讀取屬性文件,使用國際化,當校驗失敗提示的錯誤消息 --
????????????<message key="username.invalid"></message>>
????????</field-validator>
????</field>
????
????<field name="password">
????????<field-validator type="requiredstring">
????????????<message>password can't be blank!</message>
????????</field-validator>
????????<field-validator type="stringlength">
????????????<param name="minLength">4</param>
????????????<param name="maxLength">6</param>
????????????<message>length of password should be between ${minLength} and ${maxLength}</message>
????????</field-validator>
????</field>
????
????<field name="age">
????????<field-validator type="required">
????????????<message>age can't be blank!</message>
????????</field-validator>
????????<field-validator type="int">
????????????<param name="min">10</param>
????????????<param name="max">40</param>
????????????<!—在這里可以用${元素名} 引用上面的子元素-->
????????????<message>age should be between ${min} and ${max}</message>
????????</field-validator>
????</field>
????
????<field name="birthday">
????????<field-validator type="required">
????????????<message>birthday can't be blank!</message>
????????</field-validator>
????????<field-validator type="date">
????????????<param name="min">2005-1-1</param>
????????????<param name="max">2007-12-31</param>
????????????<message>birthday should be between ${min} and ${max}</message>
????????</field-validator>
????</field>
</validators>
?
?
校驗器優先校驗(混合)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN" "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
????<validator type="requiredstring">
????????<param name="fieldName">username</param>
????????<message>username can't be blank!</message>
????</validator>
????
????<validator type="stringlength">
????????<param name="fieldName">username</param>
????????<param name="minLength">4</param>
????????<param name="maxLength">6</param>
????????<!—在這里可以用${元素名} 引用上面的子元素-->
????????<message>length of username should be between ${minLength} and ${maxLength}</message>
????</validator>
????
????<field name="birthday">
????????<field-validator type="required">
????????????<message>birthday can't be blank!</message>
????????</field-validator>
????????<field-validator type="date">
????????????<param name="min">2005-1-1</param>
????????????<param name="max">2007-12-31</param>
????????????<message>birthday should be between ${min} and ${max}</message>
????????</field-validator>
????</field>
</validators>
?
打開com.opensymphony.xwork2.validator.validators可以發現一個default.xml文件,打開可以發現其中定義了各種校驗器,內容如下:
default.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC
"-//OpenSymphony Group//XWork Validator Config 1.0//EN"
"http://www.opensymphony.com/xwork/xwork-validator-config-1.0.dtd">
?
<!-- START SNIPPET: validators-default -->
<validators>
<validator name="required" class="com.opensymphony.xwork2.validator.validators.RequiredFieldValidator"/>
<validator name="requiredstring" class="com.opensymphony.xwork2.validator.validators.RequiredStringValidator"/>
<validator name="int" class="com.opensymphony.xwork2.validator.validators.IntRangeFieldValidator"/>
<validator name="long" class="com.opensymphony.xwork2.validator.validators.LongRangeFieldValidator"/>
<validator name="short" class="com.opensymphony.xwork2.validator.validators.ShortRangeFieldValidator"/>
<validator name="double" class="com.opensymphony.xwork2.validator.validators.DoubleRangeFieldValidator"/>
<validator name="date" class="com.opensymphony.xwork2.validator.validators.DateRangeFieldValidator"/>
<validator name="expression" class="com.opensymphony.xwork2.validator.validators.ExpressionValidator"/>
<validator name="fieldexpression" class="com.opensymphony.xwork2.validator.validators.FieldExpressionValidator"/>
<validator name="email" class="com.opensymphony.xwork2.validator.validators.EmailValidator"/>
<validator name="url" class="com.opensymphony.xwork2.validator.validators.URLValidator"/>
<validator name="visitor" class="com.opensymphony.xwork2.validator.validators.VisitorFieldValidator"/>
<validator name="conversion" class="com.opensymphony.xwork2.validator.validators.ConversionErrorFieldValidator"/>
<validator name="stringlength" class="com.opensymphony.xwork2.validator.validators.StringLengthFieldValidator"/>
<validator name="regex" class="com.opensymphony.xwork2.validator.validators.RegexFieldValidator"/>
<validator name="conditionalvisitor" class="com.opensymphony.xwork2.validator.validators.ConditionalVisitorFieldValidator"/>
</validators>
<!-- END SNIPPET: validators-default -->
錯誤消息國際化
在Action所在的包下建立兩個屬性文件,名字分別叫:
package_en_US.properties
username.invalid=username invalid
?
package_zh_CN.properties
username.invalid=\u7528\u6237\u540D\u4E0D\u5408\u6CD5\uFF01
#用戶名不合法
?
運行結果截圖
?
Struts2國際化
對于國際化的資源文件,其命名規則是: package_語言名_國家名,比如package_zh_CN,package_en_US 。
?
I18NTest1.java
package com.shengsiyuan.i18n;
import java.util.Locale;
public class I18NTest1
{
????public static void main(String[] args)
????{
????????Locale[] locales = Locale.getAvailableLocales();
?
????????for (Locale locale : locales)
????????{
????????????System.out.println(locale.getDisplayCountry() + " : "
????????????????????+ locale.getCountry());????????//顯示國家及國家代碼
//????????????System.out.println(locale.getDisplayLanguage() + " : " + locale.getLanguage());
????????}
????}
}
?
I18Ntest2.java
在src目錄(classpath)下,建立三個資源文件,分別如下(注 i18n即為資源文件的base name):
i18n_en_US.properties
hello=hello\:{0}
?
i18n_zh_CN.properties
hello=\u4F60\u597D\uFF1A{0}
?
i18n.properties
hello=hello world
?
I18Ntest2.java代碼如下 :
package com.shengsiyuan.i18n;
import java.util.Locale;
import java.util.ResourceBundle;
public class I18NTest2
{
????public static void main(String[] args)
????{
????????System.out.println(Locale.getDefault());
????????//綁定一個base name 為i18n的資源文件,Locale使用FRANCE(法國)
????????ResourceBundle bundle = ResourceBundle.getBundle("i18n", Locale.FRANCE);
????????//獲取hello字符串的值
????????String value = bundle.getString("hello");
????????System.out.println(value);
????}
}
?
I18Ntest3.java(傳入參數)
package com.shengsiyuan.i18n;
import java.text.MessageFormat;
import java.util.Locale;
import java.util.ResourceBundle;
public class I18NTest3
{
????public static void main(String[] args)
????{
????????Locale locale = Locale.CHINA;????//將locale定義為CHINA
????????//綁定到資源文件
????????ResourceBundle bundle = ResourceBundle.getBundle("i18n", locale);
????????//獲取資源文件中的字符串對象
????????String value = bundle.getString("hello");
????????//格式化字符串對象,并傳入參數,后邊的Object數組對象表示要插入到占位符上的具體的對象
????????String result = MessageFormat.format(value, new Object[]{"維唯為為"});
????????System.out.println(result);
????}
}
?
注意:調整瀏覽器的語言和字符編碼選項后,要注意,程序中輸入的日期格式,也要做相應的改變,不然會出現日期類型轉換錯誤。字符串國際化的同時,也要注意,日期的國際化。
?
Struts2異常處理及全局異常與結果
要點:
?
struts2異常處理實例
在第三層建一個包,取名exception ,并在包中建兩個類,分別取名為:
PasswordException.java
package com.shengsiyuan.exception;
public class UsernameException extends Exception
{
????private String message;
????public UsernameException(String message)
????{
????????super(message);
????????this.message = message;
????}
????public String getMessage()
????{
????????return message;
????}
????public void setMessage(String message)
????{
????????this.message = message;
????}
}
?
UsernameException.java
package com.shengsiyuan.exception;
public class PasswordException extends Exception
{
????private String message;
????public PasswordException(String message)
????{
????????super(message);
????????this.message = message;
????}
????public String getMessage()
????{
????????return message;
????}
????public void setMessage(String message)
????{
????????this.message = message;
????}
}
?
編輯loginAction的execute方法
????public String execute() throws Exception
????{
????????if(!"hello".equals(username))
????????{
????????????throw new UsernameException("username invalid");
????????}
????????if(!"world".equals(password))
????????{
????????????throw new PasswordException("password invalid");
????????}
????????return SUCCESS;
????}
?
編輯struts.xml文件
…………
<struts>
????<package name="struts2" extends="struts-default">
????????<action name="login" class="com.shengsiyuan.struts2.LoginAction">
????????????<exception-mapping result="usernameInvalid" exception="com.shengsiyuan.exception.UsernameException"></exception-mapping>
????????????<exception-mapping result="passwordInvalid" exception="com.shengsiyuan.exception.PasswordException"></exception-mapping>
????????????
????????????<result name="usernameInvalid">/usernameInvalid.jsp</result>
????????????<result name="passwordInvalid">/passwordInvalid.jsp</result>
????????????<result name="success">/result.jsp</result>
????????</action>
????………………
</struts>
?
…………
<struts>
????<package name="struts2" extends="struts-default">
????????<global-results>
????????????<result name="usernameInvalid">/usernameInvalid.jsp</result>
????????????<result name="passwordInvalid">/passwordInvalid.jsp</result>
????????</global-results>
????????<global-exception-mappings>
????????????<exception-mapping result="usernameInvalid" exception="com.shengsiyuan.exception.UsernameException"></exception-mapping>
????????????<exception-mapping result="passwordInvalid" exception="com.shengsiyuan.exception.PasswordException"></exception-mapping>
????????</global-exception-mappings>
????………………
</struts>
?
轉載于:https://www.cnblogs.com/luowei010101/archive/2012/02/07/2340764.html
總結
以上是生活随笔為你收集整理的Struts 学习笔记2(输入校验、国际化、异常处理)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 云计算相关资料/博客/网上收集的关于Op
- 下一篇: sql server 2008 日志处理