1 Struts1.2
1.1 Struts內部機制
MVC模式
MVC(Model模型,View視圖,Controller控制器)
模型:
用於表示業務數據,調用業務邏輯,由系統狀態Bean ActionForm和商業邏輯的JavaBean來構建
視圖:
由JSP和Struts提供的自定義標籤來實現
控制器:
負責控制流程,由ActionServlet負責讀取struts-config.xml,並使用ActionMapping來查找對應的Action
1.2 添加Struts開發環境
1.2.1 使用MyEclipse添加
MyEclipse->add struts capabilities
Struts支持的包列表:
l antlr.jar
l commons-beanutils.jar
l commons-digester.jar
l commons-fileupload.jar
l commons-logging.jar
l commons-validator.jar
l jakarta-oro.jar
l struts.jar
1.2.2 Struts配置文件列表:
在/WebRoot/WEB-INF下添加了下列配置文件
l struts-config.xml
l struts-config.mex
l struts-html.tld
l struts-bean.tld
l struts-logic.tld
l struts-tiles.tld
l struts-nested.tld
1.2.3 手動添加
1、 添加Struts的jar支持包(8個)
…/WebRoot/WEB-INF/lib目錄下
2、 添加Struts的tld標籤文件(5個)
…/WebRoot/WEB-INF目錄下
3、 添加Struts的核心配置文件Struts-config.xml
…/WebRoot/WEB-INF目錄下
4、 在web.xml中添加Struts的ActionServlet配置
…/WebRoot/WEB-INF目錄下
1.2.4 配置Struts日誌組件
1、 添加日誌組件包
Log4j-1.2.12.jar、commons-logging.jar,複製這兩個文件到項目/WebRoot/WEB-INF/lib目錄下即可。
2、 添加日誌配置文件
commons-logging.properties(放入項目/WebRoot/WEB-INF目錄下)
log4j.properties (放入項目web-inf/class目錄下)
3、 修改commons-logging.properties調用log4j
在默認情況下commons-logging.properties中會配置使用SimpleLog,要配置使用Log4j,只需註釋掉SimpleLog行,添加log4j即可
##set Log as Log4J org.apache.commons.logging.Log=org.apache.commons.logging.impl.Log4JLogger ## set Log as SimpleLog #org.apache.commons.logging.Log=org.apache.commons.logging.impl.SimpleLog
4、 Log4j配置文件log4j.properties
## LOGGERS ## #define a logger log4j.rootLogger=INFO,console,file ## APPENDERS ## # define an appender named console, which is set to be a ConsoleAppender log4j.appender.console=org.apache.log4j.ConsoleAppender # define an appender named file, which is set to be a RollingFileAppender log4j.appender.file=org.apache.log4j.RollingFileAppender log4j.appender.file.File=../logs/jdbc_bk.log #set the log's size log4j.appender.file.MaxFileSize=1000KB log4j.appender.file.MaxBackupIndex=20 ## LAYOUTS ## # assign a SimpleLayout to console appender log4j.appender.console.layout=org.apache.log4j.SimpleLayout # assign a PatternLayout to file appender log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern=[%-5p][%d{yyyy-MM-dd HH:mm:ss}] %m%n
注:
log4j.properties文件需要放到web-inf/class目錄下面,在eclipse裏面放到src目錄下面,會自動拷貝到class目錄下面去。否則在tomcat啓動的時候,會出現以下警告,且日誌不會輸出。
log4j:WARN No appenders could be found for logger (org.apache.commons.digester.Digester.sax).
log4j:WARN Please initialize the log4j system properly.
1.3 工作流程
1、 輸入表單頁面
如:
<form action="test.do" method="post"> <input type="text" name="str1"> <input type="text" name="str2"> <input type="submit"> </form>
2、 ActionServlet接收用戶請求(Request)
在Web.xml中定義
<servlet> <servlet-name>action</servlet-name> <servlet-class>org.apache.struts.action.ActionServlet</servlet-class> <init-param> <param-name>config</param-name> <param-value>/WEB-INF/struts-config.xml</param-value> </init-param> ... ... </servlet> <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping>
表示Struts能夠接收*.do的請求
3、 ActionMapping映射Action
通過struts-config.xml中的<action-mappings>來對應Action類
<action-mappings> <action path="/test" name="testForm" scope="request" type="com.demo.struts.forms.TestAction" input="/input.jsp"> <forward name="success" path="/success.jsp"></forward> <forward name="failure" path="/error.jsp"></forward> </action> </action-mappings>
此處的test對應test.do
4、 ActionMapping映射ActionForm
通過struts-config.xml中的<form-beans>來對應ActionForm類
<form-beans> <form-bean name="testForm" type="com.demo.struts.forms.TestForm"></form-bean> </form-beans>
此處name="testForm",對應<action-mappings>中的name="testForm"
5、 ActionForward轉發
Action處理完後返回ActionForward對象,對應<action-mappings>中轉發的URL
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { ActionErrors errors=new ActionErrors(); TestForm testForm = (TestForm) form; ActionForward forward =new ActionForward(); try{ String str1=testForm.getStr1(); String str2=testForm.getStr2(); }catch(Exception e){} if(!errors.isEmpty()){ forward=mapping.findForward("failure"); }else{ forward=mapping.findForward("success"); } return forward; }
此處的failure,success分別對應:<action-mappings>中的forward
1.4 Struts配置文件詳解
1.4.1 配置ActionForm:<form-beans>元素
1.4.2 配置映射關係:<action-mappings>
1.4.3 其他
1.4.4 分離Struts配置文件
1.5 ActionForm Bean開發技術
1.5.1 使用默認表單ActionForm
org.apache.struts.action.ActionForm
表示HTTP窗體中的數據,可以將其看做是模型和視圖的中介
1.5.2 使用動態表單DynaActionForm
org.apache.struts.action.DynaActionForm
1.5.3 使用自動校驗表單
org.apache.struts.validator.DynaValidatorForm
其中validator.xml和validator-rules.xml分別表示驗證定義和驗證規則的內容
1.6 Action組件開發技術
org.apache.struts.action.*
1.6.1 使用默認的Action
注:視圖級的驗證工作放在ActionForm來完成,比如輸入不能爲空、E-Mail格式是否正確等;而與具體業務相關的驗證則放入Action中,這樣就可以獲得最大ActionForm重用性的可能。在執行業務邏輯的JavaBean中不要引用任何與Web應用相關的對象,比如HttpServletRequest、HttpServletResponse等對象,而應該將其轉換爲普通的Java對象
1.6.2 可直接轉發的ForwardAction
1.6.3 可包含文件的IncludeAction
1.6.4 可自動分發的DispatchAction
通常,如果繼承默認的Action類,只能完成一種業務操作。如果要完成一組業務操作,例如對用戶進行update、insert、delete操作,則需要建立多個操作類,分別來接收響應。但DispatchAction來實現函數的分發。它的作用就是實現按業務實體劃分類。
1、<action>中添加一個parameter
<action path="/test" parameter=”method” name="testForm" scope="request" type="com.demo.struts.forms.TestAction" input="/input.jsp"> ... </action>
在<form>請求地址中傳遞了參數”method=test”
<form action="test.do?method=test" method="post"> ... </form>
在Action類中新建參數值對應的函數
public ActionForward test(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { ... return forward; }
1.6.5 可進行多個提交的LookupDispatchAction
1.6.6 可實現交換的SwitchAction
1.7 使用Struts標籤進行頁面國際化
1.7.1 軟件國際化與本地化
I18N:Internationalization的縮寫,意即在i和n之間有18個字母,本意是指軟件的“國際化”。支持多種語言,但同一時間只能是英文和一種選定的語言,例如英文+中文。
L10N:Localization。本意是軟件的“本地化”。支持2種語言,英文和另外一種語言(例如中文)
M17N:Multilingualization。本意指軟件的“多語言庫”,用以實現各國語言間的代碼移植。可以在同一時間支持多種語言,例如你可以在一個頁面裏看到中文、英文、德文等。
1.7.2 軟件本地化的設置方法
1、 用戶在軟件操作界面中選擇需要顯示的語言來顯示該軟件。
2、 軟件根據操作系統的語言設置,自動顯示默認的操作語言。
爲IE添加英語和中文顯示的列表,工具->Internet選項->語言。
1.7.3 軟件編碼
1、 ASCII(單字節)
編碼字符集:ISO-8859-1
英文DOS
2、 ANSI編碼(雙字節)
GB2312、BIG5等,中文DOS、中文/日文Windows95/98
3、 Unicode編碼
UTF-8、UTF-16、UTF-32,WindowsNT/2K/XP、linux
1.7.4 Java對國際化的支持
1、 Locale類
Java.util.Locale類是最重要的Java I18N類
1) 通過構造函數創建Locale對象
如:
Locale chLocale=new Locale(“zh”,”CN”);//中國中文
第一個參數是語言代碼,語言代碼由兩個小寫字母組成,遵從ISO-639規範。
第二個參數是國家代碼,由兩大寫字母組成,遵從ISO-3166規範。
使用默認定義的Locale對象
Locale locale1=Locale.JAPAN; Locale locale2=new Locale(“ja”,”JP”);
取得操作系統的默認Locale對象
Locale defaultLocale=Locale.getDefault();
在Web應用中訪問客戶端的Locale對象
調用HttpServletRequest對象的以下兩個方法來取得包含Web客戶的Locale信息
Public java.util.Locale getLocale(); Public java.util.Enumeration getLocales();
ResourceBundle類
Java.util.ResourceBundle類提供存放和管理與Locale相關的資源的功能。這些資源包括文本域、按鈕的Label、狀態信息、圖片名、錯誤信息和網頁標題等。
1.7.5 Struts對國際化的支持
1、 創建Struts的ResourceBundle資源文件
2、 訪問Resource Bundle資源文件
3、 在Struts應用中訪問Resource Budle的方法
4、 在Struts應用中訪問Resource Budle的組件。
1.7.6 Struts頁面國際化的過程
1、 定義Struts的資源文件
在strust-config.xml中通過<message-resources>定義
<message-resources parameter="com.demo.struts.ApplicationResources" />
2、 創建Struts的資源文件
我們應該在包com.demo.struts.resources中創建UTF-8資源文件,這裏的資源文件會被編譯到/WEB-INF/classes/com.demo.struts.resources下。每一個資源文件是“鍵=值”對的集合。
資源文件的格式爲:默認資源文件名_國別_語言.properties。其中每個文件都是通過%JAVA_HOME%/bin/native2ascii.exe工具轉換而來。
如:
//ApplicationResources.properties;默認資源文件,通常裏面的內容是英文的 Label.name=USERNAME; Lable.password=PASSWORD; //ApplicationResources_zh_CN.bak;默認資源文件,通常裏面的內容是英文的 //它需要工具將其中的內容處理成UTF-8 Label.name=用戶名; Lable.password=密 碼;
上面的中文資源文件中寫的是中文,還需要用如下的命令專爲UTF-8編碼的資源文件。
native2ascii -encoding utf-8 ApplicationResources_temp.properties ApplicationResources_zh_CN.properties
3、 定義JSP頁面的字符集合
<%@ page contentType="text/html;charset=UTF-8"%>
4、 在JSP頁面獲取資源文件裏面的內容
<table width="200" border="1">
<tr>
<td align=”right”><bean:message key=”label.username”></td>
</tr>
<tr>
<td align=”right”><bean:message key=”label.password”></td>
</tr>
</table>
在這個頁面顯示的時候,如果客戶的IE的語言集合是zh_CN的話,就會顯示:
用戶名:
密 碼:
如果客戶的IE的語言是en的話,就會顯示:
USERNAME:
PASSWORD:
1.7.7 Struts HTML標籤
使用Struts HTML標籤需要通過以下配置
1、 在web.xml中註冊標籤庫
2、 確信將struts-html.tld文件複製到WEB-INF目錄中。
3、 在運用標籤庫的每個JSP頁面中,插入下面的<taglib>指示符
1.7.7.1 用於生成基本的HTML元素的標籤
1、 <html:html>標籤
用於生成HTML的<html>元素
2、 <html:base>
3、 <html:link>
4、 <html:rewrite>
1.7.7.2 用於生成HTML表單的標籤
1、 <html:form>
2、 數據輸入標籤
<html:text>
<html:password>
<html:hidden>
<html:textarea>
<html:radio>
<html:checkbox>
<html:select>
<html:option>
3、 提交按鈕標籤
<html:submit>
<html:cancel>
<html:reset>
<html:button>
<html:image>
1.7.7.3 用於顯示錯誤或正常消息的標籤
<html:errors>:用於顯示錯誤消息
<html:messages>:用於顯示正常消息
1.7.8 Struts Bean標籤
1.7.8.1 用於訪問HTTP請求信息或JSP隱含對象
1、 <bean:cookie>
2、 <bean:header>
3、 <bean:parameter>
4、 <bean:page>
1.7.8.2 用於訪問Web應用資源
1、 <bean:message>:用於顯示ResourceBundle 中的消息。
用來從指定的locale中取回國際化的消息並輸出。這個過程可以傳遞5個以內的參數。Message標籤有兩種指定message key的方式,一是通過key屬性直接指定;二是通過name和property屬性間接的指定,其中message key是在message resources文件中定義的。
如:
<bean:message key=”login.page.title”>
2、 <bean:resource>
3、 <bean:struts>
4、 <bean:include>
1.7.8.3 用於定義或輸出JavaBean的Bean標籤
1、 <bean:define>
2、 <bean:write>
3、 <bean:size>
1.7.9 Struts Logic標籤
1.7.9.1 進行比較運算的Logic標籤
<logic:equal>
<logic:notEqual>
<logic:greaterEqual>
<logic:greaterThen>
<logic:lessEqual>
<logic:lessThan>
1.7.9.2 進行字符串匹配的Logic標籤
<logic:match>
<logic:notMatch>
1.7.9.3 判斷指定內容是否存在的Logic標籤
<logic:empty>和<logic:notEmpty>
<logic:present>和<logic:notPresent>
<logic:messagesPresent>和<logic:messagesNotPresent>
1.7.9.4 進行循環遍歷的Logic標籤
<logic:iterate>
1.7.9.5 進行請求轉發或重定向的Logic標籤
<logic:forward>
<logic:redirect>
1.8 Struts數據驗證
1.8.1 使用Validator校驗器組件
ActionForm Bean提供了Validator的一個ActionForm子類,它提供驗證或存儲錯誤消息的功能
Validator使用兩個XML配置文件來分別確定安裝哪個驗證程序,以及如何將它們用於給定的應用程序
Validator-rules.xml:說明應該被插入到框架中的驗證程序,並提供每個驗證的邏輯名稱
Validation.xml:確定哪個驗證程序應用到哪個ActionForm Bean。
配置使用Validator
1、 在struts-config.xml中配置使用validator插件
<plug-in className="ora.apache.struts.validator.ValidatorPlugIn"> <set-property property="pathnames" value="/WEB-INF/validator-rules.xml, /WEB-INF/validation.xml" /> </plug-in>
注:你的應用程序的struts-config.xml文件必須與Struts Configuration Document Type Definition(Struts配置文檔類型定義,DTD)一致,後者規定文件中元素出現的順序。所以必須把Validator插件定義放到該文件的適當位置,一般放到<message-resources>下
2、 Validator驗證程序配置文件validator-rules.xml
3、 使用Validator的兩個父類來創建自己的表單類
爲了使用Validator,你的應用程序的ActionFormBean必須歸到Validator的ActionForm的某一子類。Validator提供了兩個父類ValidatorForm和DynaValidatorForm
1) 使用普通的驗證表單類ValidatorForm
在struts-config.xml文件中配置這個特定的ActionForm Bean,與配置正常的方法相同
<form-bean name="loginForm" type="com.demo.struts.forms.LoginForm"></form-bean>
2) 使用動態表單類DynaValidatorForm
<form-bean name="loginForm" type="org.apache.struts.validator.DynaValidatorForm"> <form-property name=”username” type=”java.lang.String”/> <form-property name=”password” type=”java.lang.String”/> </form-bean>
4、 配置表單的驗證規則validation.xml
用於聲明將應用到ActionForm Bean的一組驗證。
5、 綁定驗證中的錯誤消息ApplicationResources.properties
使用Struts的資源綁定(Resource Bundle)機制將錯誤消息具體化。
1.8.2 在ActionForm中檢驗合法性
Validator框架針對表單數據的驗證提供了可配置的系統,從而爲核心Struts框架添加了很多有價值的功能。然而Validator的開發和配置過程,被設計了多個額外的配置文件,無疑讓開發更加複雜化。
我們可以在ActionFormBean對象的validate()方法中編寫驗證邏輯代碼。此外,還必須編寫代碼來存儲驗證失敗的出錯消息。
1.8.2.1 爲ActionForm添加表單驗證功能
1、 添加一個驗證函數validate(),該函數繼承其父類ActionForm
public ActionErrors validate(ActionMapping arg0, HttpServletRequest arg1) { ActionErrors errors=new ActionErrors(); String queryString=arg1.getQueryString(); if(queryString.equalsIgnoreCase("method=register")){ if(username==null||username.equals("")){ errors.add("username", new ActionMessage("register.error.username")); } if(password1==null||password1.equals("")){ errors.add("password1", new ActionMessage("register.error.password1")); } ... } arg1.setAttribute("registerFormBean", this); return errors; }
2、 ApplicationResources.properties中添加標籤
#loginForm
login.error.username=用戶名不能爲空
login.error.password=密碼不能爲空
3、 JSP頁面中輸出錯誤信息
<tr> <td><bean:message key="login.page.username" /></td> <td><input type="text" name="username"> <html:errors property="username"/> </td> </tr>
1.8.2.2 爲Action添加邏輯驗證功能
1、 Action的execute()中修改檢驗代碼
errors.add(ActionErrors.GLOBAL_MESSAGE,new ActionMessage("login.message.failed"));
2、 ApplicationResources.properties中添加標籤
#loginForm
login.message.failed=用戶名或密碼不存在!
3、 JSP中輸出這個全局錯誤信息
<html:errors property="org.apache.struts.action.GLOBAL_MESSAGE"/>
1.8.2.3 驗證出錯時維持表單輸入
1、 ActionForm的validate()後面添加如下代碼
request.setAttribute("loginFormBean", this);
2、 在Action的execute()後面添加
request.setAttribute("loginFormBean", loginForm);
3、 修改JSP表單
<tr> <td><bean:message key="login.page.username" /></td> <td> <logic:present name="loginFormBean"> <html:text property="username" name="loginFormBean" /> </logic:present> <logic:notPresent name="loginFormBean"> <input type="text" name="username"> </logic:notPresent> <html:errors property="username"/> </td> </tr>
使用<logic:present>標籤判斷Bean對象loginFormBean是否存在,如存在則使用<html:text>輸出屬性”username”的值;如不存在,則依然輸出空的HTML表單