posts - 78, comments - 34, trackbacks - 0, articles - 1
            BlogJava :: 首頁 :: 新隨筆 :: 聯(lián)系 :: 聚合  :: 管理

          2009-12-20傳智播客——Struts1

          Posted on 2009-12-21 00:19 長城 閱讀(427) 評論(0)  編輯  收藏

                   Today is first day of J2E高級部分。今天開始講解struts1,為什么要講1不講2呢?因為自struts1以來,就應用廣泛。即使Struts2已經(jīng)發(fā)布了,但使用struts1開發(fā)的WEB應用比較多見,因為Struts2Struts1有很大的差別,所以將以前使用Struts1開發(fā)的WEB應用移植到Struts2上來,不是一件容易的事。所以大家在工作中,可能會遇到有使用Struts1WEB應用。這是學習Struts1的原因,但我認為學習Struts1可以讓我在框架這片地方混的熟悉一些,學學框架的設計,而且過渡到Struts2也十分容易!

           

                 Struts1的課程由佟剛老師教授,佟老師也是傳智的一位名人。今日一見,名不虛傳!老佟十分幽默,而且細心。課上給同學們帶來歡笑的同時,課程內(nèi)容也一一被它記錄在記事文本文件中并放入工程。邏輯思路清晰,就是講課有點快。他說以后會慢慢提速,直到大家適應了快速。其實后續(xù)課程中還有項目等著大家呢,如果速度不提快,大家不努力適應上來,怎能做好項目。這是一個適應過程,保質(zhì)保量的完成項目!

           

                   既然很快,今天的內(nèi)容非常多。下面,我來總結(jié)一下主要內(nèi)容。

           

                 一、為什么要使用Struts

                   在之前的學習過程中,我們編寫的練習程序有以下特點。

          1. 使用 MVC 設計模式

              1). 原則: 所有的請求都必須提交到 Servlet

              2). Servlet的職責:

                 . 接受請求, 獲取請求參數(shù)。

                 . 進行簡單驗證,比如用戶名、密碼、email格式是否正確...

                 . 封裝數(shù)據(jù)到一個JavaBean,比如將用戶信息封裝到UserBean中。

                 . 調(diào)用方法,處理業(yè)務邏輯。

                 . 確定要派發(fā)的頁面。

                 . 派發(fā)頁面。

              3). 使用Servlet作為控制器有以下不足:

                 . Servlet僅負責頁面派發(fā),此時Servlet有些浪費。

                 . Servlet中進行簡單驗證,導致Servlet中的代碼比較臃腫。

                 . 因為要派發(fā)的頁面寫在了Servlet的代碼中,若需要更改派發(fā)的頁面,則需要修改源代碼。

                 . 進行國際化,比較麻煩。

                 . 處理表單重復提交,文件的上傳操作,表單的回顯等常用功能也比較麻煩。

              4). Struts可以解決上述問題

           

                 二、Struts原理與應用

                   1.Struts流程:

           

           

          Servlet/JSP 容器

          http請求

          http響應

           
          clip_image001

           

          圖中每個Action都可以設置一個FormBean用于校驗頁面提交的form數(shù)據(jù)。

           

          2.我們來編寫一個校驗用戶注冊信息的簡單應用

          index.jsp,我直接把這個頁面設置為注冊頁面(可以將名字改為“register.jsp”)。

          <%@ page language="java" contentType="text/html; charset=UTF-8"

              pageEncoding="UTF-8"%>

          <%@ taglib prefix="html" uri="http://struts.apache.org/tags-html" %>

             

          <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

          <html>

          <head>

          <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

          <title>Insert title here</title>

          </head>

           

          <body>

              <table align="center">

                 <form action="${pageContext.request.contextPath }/reg.do" method="post">

                     <tr>

                        <td>用戶名:</td><td><input type="text" name="username" value="${param.username }"/></td>

                        <td><html:errors property="username" /></td>

                     </tr>

                     <tr>

                        <td>密碼:</td><td><input type="password" name="password"/></td>

                        <td><html:errors property="password"/></td>

                     </tr>

                     <tr>  

                        <td>確認密碼:</td><td><input type="password" name="password2"/></td>

                        <td><html:errors property="password2"/></td>

                     </tr>

                     <tr>

                        <td>生日:</td><td><input type="text" name="birthday" value="${param.birthday }"/></td>

                        <td><html:errors property="birthday"/></td>

                     </tr>

                     <tr>

                        <td><input type="submit" value="注冊"/></td>

                        <td><input type="reset" value="重填"/></td>

                     </tr>

                 </form>

              </table>

          </body>

          </html>

           

                   注意里邊的“<html:errors…”,它是獲取Struts框架中ActionForm生成的錯誤信息。關(guān)于ActionForm請繼續(xù)向下看。

           

                   web.xmlWEB應用的配置文件:

          <?xml version="1.0" encoding="UTF-8"?>

          <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

            <display-name>091220StrutsLogin</display-name>

           

            <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>

           

            <welcome-file-list>

              <welcome-file>index.jsp</welcome-file>

            </welcome-file-list>

          </web-app>

           

                   注意其中的“org.apache.struts.action.ActionServlet”類,它是Struts的控制器,所有“*.do”的請求都交由它處理。它需要一個初始化參數(shù)——struts-config.xmlStruts的配置文件)!在的開發(fā)中,如果不記得web.xml的配置方式,可以到struts包目錄下的apps目錄下解壓一個示例文件(*.war),在示例文件中有相關(guān)配置。

           

                   struts-config.xmlstruts框架的配置文件:

          <?xml version="1.0" encoding="ISO-8859-1" ?>

           

          <!DOCTYPE struts-config PUBLIC

                    "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"

                    "http://struts.apache.org/dtds/struts-config_1_3.dtd">

          <struts-config>

              <form-beans>

                 <form-bean name="regForm" type="cn.itcast.cc.forms.RegForm">

              </form-bean>

              </form-beans>

              <action-mappings>

                 <action path="/reg"

                     type="cn.itcast.cc.actions.Register"

                     validate="true"

                     name="regForm"

                     input="/index.jsp">

                     <forward name="success" path="/success.jsp"></forward>

                 </action>

              </action-mappings>

             <message-resources parameter="MessageResources"></message-resources>

          </struts-config>

                   各項配置,可以參看這里,轉(zhuǎn):http://showmystage.javaeye.com/blog/183042

           

          Register.java,處理注冊請求的Action

          import javax.servlet.http.*;

          import org.apache.struts.action.*;

           

          public class Register extends Action {

              @Override

              public ActionForward execute(ActionMapping mapping, ActionForm form,

                     HttpServletRequest request, HttpServletResponse response)

                     throws Exception {

                 // 如果失敗了,則由ActionForm返回

                 // 成功返回

                 return mapping.findForward("success");

              }  

          }

           

                   這個Action只是在form信息通過驗證后,返回成功信息“success”。成功信息的處理方式在“struts-config.xml”中配置。

           

                   RegFrom.java,它是注冊請求信息處理的校驗類(ActionForm),就是常說的FormBean

          import java.text.ParseException;

          import java.text.SimpleDateFormat;

          import javax.servlet.http.HttpServletRequest;

          import org.apache.struts.action.*;

           

          public class RegForm extends ActionForm {

              private static final long serialVersionUID = 1L;

             

              private String username;

              private String password;

              private String password2;

              private String birthday;

           

              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 getPassword2() {

                 return password2;

              }

              public void setPassword2(String password2) {

                 this.password2 = password2;

              }

              public String getBirthday() {

                 return birthday;

              }

              public void setBirthday(String birthday) {

                 this.birthday = birthday;

              }

              public static long getSerialversionuid() {

                 return serialVersionUID;

              }

           

              @Override

              public ActionErrors validate(ActionMapping mapping,

                     HttpServletRequest request) {

                 ActionErrors errors = new ActionErrors();

                 // 校驗用戶名

                 if (this.username == null || this.username.trim().equals("")) {

                     ActionMessage message = new ActionMessage("errors.username.null");

                     errors.add("username", message);

                 }

                 // 校驗密碼

                 if (this.password == null || this.password.trim().equals("")) {

                     ActionMessage message = new ActionMessage("errors.password.null");

                     errors.add("password", message);

                 }

                 if(this.password2 == null || this.password2.trim().equals("")){

                     ActionMessage message = new ActionMessage("errors.password.null");

                     errors.add("password2", message);

                 }

                 if(!this.password.equals(this.password2)){

                     ActionMessage message = new ActionMessage("errors.password.diff");

                     errors.add("password2", message);

                 }

                

                 // 校驗生日

                 if(this.birthday == null || this.birthday.equals("")){

                     ActionMessage message = new ActionMessage("errors.birthday.null");

                     errors.add("birthday", message);

                 }else{

                     SimpleDateFormat df = new SimpleDateFormat("yyyy-mm-dd");

                     try {

                        df.parse(this.birthday);

                     } catch (ParseException e) {

                        ActionMessage message = new ActionMessage("errors.brithday.validate");

                        errors.add("birthday", message);

                        e.printStackTrace();

                     }

                 }

                 return errors;

              }

          }

           

                   它看起來更像一個Bean,它的成員名稱必須與form中的name屬性一致,否則會拋出異常。因為它繼承自ActionForm,并且在struts-config.xml中配置過。ActionServlet會自動調(diào)用它的“validate”方法,校驗form信息是否正確。如果errorsnullerrors.size0AcitonServlet認為form信息是成功通過校驗的,并返回到RegisterAciton中繼續(xù)處理。

           

                   上邊我們在Register中,如果校驗成功直接返回“success”,但在實際開發(fā)中,我們還需要向數(shù)據(jù)庫中添加用戶的注冊信息。按照以往的做法,我們需要定義一個UserBean,并在Register類中,通過“execute”方法的“ActionForm form”參數(shù)獲取表單信息并填充到UserBean,然后交由業(yè)務邏輯處理模塊,將其添加到數(shù)據(jù)庫中。如果有用戶登錄功能,我們還需要在登陸的Action中填充這個UserBean。在以后的應用中,我們可能需要在多處填充Bean,這種重復的工作,是需要改善的。

           

          在此提出了BeanUtils,可以調(diào)用它的靜態(tài)方法“BeanUtils.copyProperties(user, form);”。userUserBean的一個實例,formexecute的參數(shù)。只要一條語句就搞定了!在工程中添加一個User類,修改Register.javaececute方法

          public ActionForward execute(ActionMapping mapping, ActionForm form,

                     HttpServletRequest request, HttpServletResponse response)

                     throws Exception {

                 // 如果失敗了,則由ActionForm返回

                 // form數(shù)據(jù)復制到User

                 User user = new User();

                 BeanUtils.copyProperties(user, form);

                 request.setAttribute("user", user);

                 // 成功返回

                 return mapping.findForward("success");

              }

           

           

                   注意,struts框架是根據(jù)form的信息去填充user的。因此,user的成員名稱必須與form的成員名稱相同,且類型也必須相同。如果類型不同,必須編寫類型轉(zhuǎn)換器并使用“ConvertUtils.register”方法注冊到ConvertUtils中。比如,user中的birthday類型是java.util.Date,但form中的birthdayString類型。這時我們就需要編寫一個類型轉(zhuǎn)換器,類型轉(zhuǎn)換器最好在WEB應用被初始化時注冊到ConvertUtils中,下面是在ServletContextListenercontextInitialized方法中注冊類型轉(zhuǎn)換器的:

          @Override

              public void contextInitialized(ServletContextEvent arg0) {

                 ConvertUtils.register(new Converter(){

                     @Override

                     public Object convert(Class arg0, Object arg1) {

                        if(arg0 != null){

                            DateFormat df = new SimpleDateFormat("yyyy-mm-dd");

                             try {

                                return df.parse((String) arg1);

                            } catch (ParseException e) {

                               e.printStackTrace();

                               return  new RuntimeException("錯誤的日期時間格式!");

                            }

                        }else{

                            throw new RuntimeException("請指定預轉(zhuǎn)換到的類信息!");

                        }

                     }

                 }, Date.class);

              }

           

                   Ok,完成了!

           

                   接下來我們看一下頁面整個請求到響應的過程,時間太晚了,我就不把老佟總結(jié)的進行詳細的整理了,直接發(fā)上來吧:

              1). *.do 根據(jù)web.xml,請求到 org.apache.struts.action.ActionServlet

              2). ActionServlet中的doGet, doPost 調(diào)用 process() 方法, 再調(diào)用 Requestprocessor process 方法.

              3).

                 . 獲取 servletpath: String path = processPath(request, response);

                 . 根據(jù) path 獲取對應的<action>節(jié)點: ActionMapping mapping = processMapping(request, response, path);

                 . 獲取對應的 ActionForm 對象: ActionForm form = processActionForm(request, response, mapping);

                 . 若配置類 action validate 屬性為 true, 或使用默認值則. 調(diào)用 ActionForm validate() 方法進行簡單驗證:

                    

                     if (!processValidate(request, response, form, mapping)) {

                          return;

                      }

                     

                      若驗證沒有通過, 將頁面派發(fā)到 input 屬性指定的頁面. 方法結(jié)束, 此時請求不會到達 Action

          (在配置文件struts-config.xml中進行配置)

                   . 若驗證通過, 得到對應的 Action 對象: Action action = processActionCreate(request, response, mapping);

                   . 調(diào)用 action execute() 方法

                   . 派發(fā)頁面. 

           

                   加油!


          只有注冊用戶登錄后才能發(fā)表評論。


          網(wǎng)站導航:
           
          主站蜘蛛池模板: 临城县| 武平县| 都江堰市| 古丈县| 广东省| 武定县| 洛阳市| 通渭县| 开封县| 休宁县| 嘉禾县| 理塘县| 册亨县| 内江市| 江孜县| 永兴县| 临朐县| 奈曼旗| 阿城市| 和静县| 绥德县| 增城市| 海林市| 贵南县| 即墨市| 静海县| 临高县| 孟州市| 新竹市| 贵港市| 炎陵县| 台湾省| 绥滨县| 屯昌县| 米易县| 西乡县| 砚山县| 中卫市| 隆化县| 林甸县| 宣化县|