posts - 11, comments - 0, trackbacks - 0, articles - 0

          Struts小介紹

          Posted on 2011-03-15 22:56 HsiangYu 閱讀(205) 評論(0)  編輯  收藏 所屬分類: Struts

               一、為什么要使用Struts

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

          1. 使用 MVC 設計模式

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

              2). Servlet的職責:

                 接受請求獲取請求參數。

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

                 封裝數據到一個JavaBean,比如將用戶信息封裝到UserBean中。

                 調用方法,處理業務邏輯。

                 確定要派發的頁面。

                 派發頁面。

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

                 Servlet僅負責頁面派發,此時Servlet有些浪費。

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

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

                 進行國際化,比較麻煩。

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

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

           

                 二、Struts原理與應用

                   1.Struts流程:

           

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

           

          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生成的錯誤信息。關于ActionForm請繼續向下看。

           

                   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”的請求都交由它處理。它需要一個初始化參數——struts-config.xmlStruts的配置文件)!在的開發中,如果不記得web.xml的配置方式,可以到struts包目錄下的apps目錄下解壓一個示例文件(*.war),在示例文件中有相關配置。

           

                   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>

                   各項配置,可以參看這里,轉: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 = newActionMessage("errors.username.null");

                     errors.add("username", message);

                 }

                 // 校驗密碼

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

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

                     errors.add("password", message);

                 }

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

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

                     errors.add("password2", message);

                 }

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

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

                     errors.add("password2", message);

                 }

                

                 // 校驗生日

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

                     ActionMessage message = newActionMessage("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 = newActionMessage("errors.brithday.validate");

                        errors.add("birthday", message);

                        e.printStackTrace();

                     }

                 }

                 return errors;

              }

          }

           

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

           

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

           

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

          public ActionForward execute(ActionMapping mapping, ActionForm form,

                     HttpServletRequest request, HttpServletResponse response)

                     throws Exception {

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

                 // form數據復制到User

                 User user = new User();

                 BeanUtils.copyProperties(user, form);

                 request.setAttribute("user", user);

                 // 成功返回

                 return mapping.findForward("success");

              }

           

           

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

          @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("請指定預轉換到的類信息!");

                        }

                     }

                 }, Date.class);

              }

           

                   Ok,完成了!

           

                   接下來我們看一下頁面整個請求到響應的過程:

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

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

              3).

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

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

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

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

                    

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

                          return;

                      }

                     

                      若驗證沒有通過將頁面派發到 input 屬性指定的頁面方法結束此時請求不會到達 Action

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

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

                   調用 action  execute() 方法

                   派發頁面


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


          網站導航:
           
          主站蜘蛛池模板: 洛宁县| 清流县| 卢湾区| 英超| 若羌县| 巫溪县| 湟中县| 张家港市| 三亚市| 靖远县| 兴化市| 四会市| 肇庆市| 小金县| 泸溪县| 凤翔县| 民勤县| 梧州市| 樟树市| 莱西市| 苍山县| 葫芦岛市| 桐庐县| 吴堡县| 樟树市| 乌什县| 博罗县| 文安县| 西畴县| 阜新市| 宕昌县| 涡阳县| 若尔盖县| 长子县| 义乌市| 济宁市| 龙陵县| 沧州市| 山阴县| 锡林郭勒盟| 武城县|