天天看點

Struts1簡單開發流程梳理

共享資料的4種範圍

MVC設計模式

JSP model1、JSP model2

struts實作MVC機制(ActionServlet、Action)

struts-config.xml

ActionServlet、ActionForm、Action、ActionMapping、ActionForward

struts應用、servlet容器、jsp容器、Java web容器

struts入門應用:helloapp

1.建立視圖元件

hello.jsp、HelloForm Bean

建立jsp檔案(導入加載struts标簽庫)<%@ taglib uri=""%>

輸出到網頁上的文本内容都是由<bean:message key="hello.jsp.prompt.person"/>标簽生成的

<bean:write name="" property=""/>

<html:errors>、<html:form>(html表單字段與ActionFormBean關聯)、<html:text>

<logic:present>

2.建立消息資源檔案ResourceBundle

<bean:message key="hello.jsp.prompt.person"/>

application.properties(例如:hello.jsp.title=Hello!)

3.建立ActionForm Bean

當使用者送出HTML表單之後,struts架構自動把表單資料組裝到ActionForm Bean中

ActionForm Bean中的屬性和HTML表單中的字段一一對應

先繼承ActionForm抽象類比Java bean多了重置預設值reset和資料驗證validate方法 ActionErrors

4.資料驗證

表單驗證(ActionForm Bean中)、業務邏輯驗證(Action Bean中)

送出表單後,struts自動把資料組裝到ActionForm Bean中,架構調用ActionForm Bean的validate方法進行

表單驗證,若傳回Action Errors對象為null或者不包含任何ActionMessage對象,就表示沒有錯誤,通過。

struts1.2廢棄Action Errors對象,采用ActionMessage

5.建立控制器元件

包括ActionServlet類和Action類

ActionServlet類是struts架構自帶的,是整個架構的控制樞紐,通常不需要擴充

Action類是可擴充的,用來處理特定的Http請求(繼承Action類)

A.Action類的工作機制

繼承Action類,覆寫execute()方法當ActionForm Bean被建立并表單驗證通過後,struts架構就會調用Action類

的execute()方法。該方法傳回ActionForward對象,該對象包含了請求轉發路徑資訊。

execute方法參數: ActionMapping包含這個Action的配置資訊和struts-config.xml檔案中的<action>元素對應

         ActionForm 包含使用者的表單資料(ActionForm資料通過驗證才會調用execute方法)

        HttpServletRequest

        HttpServletResponse

B.通路封裝在MessageResources中的本地化文本

Action類中定義了getResources(HttpServletRequest req)方法,傳回預設的MessageResources對象,它封裝了Resource Bundle中

的文本内容。調用MessageResources對象(已經調用getResources方法傳回的對象)messages.getMessage("hello.jsp.title")擷取内容

C.業務邏輯驗證

Action類的execute方法執行業務邏輯驗證(ActionMessages對象的add方法)

(String)((HelloForm)form).getUserName();

Action類自帶方法saveErrors(request,errors);<html:errors>

ActionErrors繼承ActionMessages

ActionMessages與ActionMessage是聚集關系 1個包含多個

ActionError繼承ActionMessage

6.通路模型元件

建立PersonBean對象并調用方法(Action類一般會調用通路模型元件)

7.向視圖元件傳遞資料

Action類把資料存放在request或session範圍内,以便向視圖元件傳遞資料

request.setAttribute(Constants.PERSON_KEY,pb);

request.removeAttribute(mapping.getAttribute());

8.把HTTP請求轉發給合适的視圖元件

Action類把流程轉發給合适的視圖元件

return mapping.findForward("SayHello"); 傳回ActionForward對象

9.建立模型元件JavaBean、EJB

10.建立存放常量的Java檔案(request對象setAttribute以及getAttribute需要一個key值)

struts應用提倡将這些屬性key常量定義在一個Java檔案的Constants.java檔案中

public final class Constants{ public static final String PERSON_KEY="personbean";}

使用Constants.PERSON_KEY

11.建立配置檔案

建立web應用的配置檔案

web.xml對ActionServlet類進行配置

聲明web應用使用的Struts标簽庫(例如:Struts Bean、Struts Html、Struts Logic标簽)

建立Struts架構的配置檔案 struts-config.xml

<struts-config>、<form-beans>、<form-bean>、<action-mappings>、<action>、<forward>

<message-resources>

分析:<form-bean name="HelloForm" type="hello.HelloForm"/>

配置了一個Action Bean,名為HelloForm 類為hello.HelloForm

<action path="/HelloWord"

type="hello.HelloAction"

name="HelloForm"

scope="request"

validate="true"

input="/hello.jsp"

>

<forward name="SayHello" path="/hello.jsp"/>

</action>

配置Action元件,path請求通路Action路徑,type屬性指定Action的完整類名,

name指定需要傳遞給Action的ActionForm Bean,scope指定ActionForm Bean的存放範圍

validate指定是否執行表單驗證,input指定當表單驗證失敗時的轉發路徑

<forward>子元素定義請求轉發路徑

連結 /sysNotifyTodo.do?method=view 配置檔案的action标簽parameter="method"

指定調用action哪個方法,此時是view方法

<message-resources parameter="hello.application"/>定義了一個Resource Bundle

parameter屬性指定Resource Bundle使用的消息資源檔案,此時消息資源檔案名為application.properties

存放路徑為WEB-INF/classes/hello/application.properties

可以在web.xml或struts.xml配置,其中key屬性不是必要的

<message-resources parameter="application" key="local" />

可在頁面用struts标簽引用資源或在Action類中調用

MessageResources messageResources = this.getResources(request, "local");

String one = messageResources.getMessage("one");

12.釋出和運作應用

作為Java Web應用,目錄結構應符合Sun公司規範。導包jar檔案以及标簽庫描述檔案tld檔案。

(頁面的連結路徑要去掉.do才和struts.xml配置檔案的action的path路徑屬性比對)

注意一點,如果自定義的ActionClass中重寫了excute方法,那麼即使指定了method,

所有的請求還是會走excute方法,而不是指定的doAjax方法。

(頁面的原生的html标簽連結路徑前面不需要斜杆/,而struts.xml配置檔案需要/)

Struts1簡單開發流程梳理
web.xml檔案

<?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>myweb</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>/office/door.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <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.xml</param-value>
      </init-param>
  </servlet>
  <servlet-mapping>
      <servlet-name>action</servlet-name>
      <url-pattern>*.do</url-pattern>
  </servlet-mapping>
</web-app>      

struts.xml檔案

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

<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">
<struts-config>

    <!-- 表單 Bean -->
    <form-beans>
        <form-bean name="door" type="forms.Door" />
    </form-beans>

    <!-- 操作映射 -->
    <action-mappings>

        <action 
            path="/doors/entrance"

            
            type="actions.DoorAction"
            parameter="method"
            scope="request"
            name="door"
            validate="true"
            input="/error.jsp">
            
            <forward name="welcome"
                path="/office/welcome.jsp" />
        </action>

    </action-mappings>

    <message-resources parameter="application"
        key="local" />
</struts-config>      

door.jsp檔案

<body>
    <form action="doors/entrance.do">
        門名:<input type="text" name="dname"/>
        高度:<input type="text" name="height">
        <input type="hidden" name="method" value="myMethod"/>
        <input type="submit" value="送出"/>
    </form>
</body>      

DoorAction.java檔案

1 package actions;
 2 
 3 import javax.servlet.http.HttpServletRequest;
 4 import javax.servlet.http.HttpServletResponse;
 5 
 6 import org.apache.struts.action.ActionForm;
 7 import org.apache.struts.action.ActionForward;
 8 import org.apache.struts.action.ActionMapping;
 9 import org.apache.struts.actions.DispatchAction;
10 import org.apache.struts.util.MessageResources;
11 
12 public class DoorAction extends DispatchAction {
13 
14 //    @Override
15 //    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
16 //            HttpServletResponse response) throws Exception {
17 //        System.out.println("door execute action");
18 //        return mapping.findForward("welcome");
19 //    }
20     public ActionForward myMethod(ActionMapping mapping, ActionForm form, HttpServletRequest request,
21             HttpServletResponse response) throws Exception {
22         System.out.println("door myMethod action");
23         String heightstr = request.getParameter("height");
24         int height = Integer.parseInt(heightstr);
25         MessageResources messageResources = this.getResources(request, "local");
26         String one = messageResources.getMessage("one");
27         String two = messageResources.getMessage("two");
28         String three = messageResources.getMessage("three");
29         System.out.println(one+two+three);
30         if(height>=100){
31             System.out.println("高度大于等于100!");
32         }else{
33             System.out.println("高度小于100!");
34         }
35         request.setAttribute("dname", request.getParameter("dname"));
36         request.setAttribute("height", height);
37         return mapping.findForward("welcome");
38     }
39 
40 }      

Door.java檔案

1 package forms;
 2 
 3 import javax.servlet.http.HttpServletRequest;
 4 
 5 import org.apache.struts.action.ActionError;
 6 import org.apache.struts.action.ActionErrors;
 7 import org.apache.struts.action.ActionForm;
 8 import org.apache.struts.action.ActionMapping;
 9 import org.apache.struts.action.ActionMessage;
10 import org.apache.struts.action.ActionMessages;
11 
12 import com.sun.org.apache.xalan.internal.xsltc.compiler.util.ErrorMessages;
13 
14 public class Door extends ActionForm {
15 
16     /**
17      * 
18      */
19     private static final long serialVersionUID = 8910086866815354113L;
20 
21     private String dname = null;
22     private String height = null;
23 
24     public String getDname() {
25         return dname;
26     }
27 
28     public void setDname(String dname) {
29         this.dname = dname;
30     }
31 
32     public String getHeight() {
33         return height;
34     }
35 
36     public void setHeight(String height) {
37         this.height = height;
38     }
39 
40     @Override
41     public void reset(ActionMapping mapping, HttpServletRequest request) {
42         // TODO Auto-generated method stub
43         super.reset(mapping, request);
44     }
45 
46     @Override
47     public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
48         System.out.println("validate method!");
49         System.out.println(dname + ":" + height);
50         if (dname.trim().equals("") || height.trim().equals("")) {
51             System.out.println("空!!!");
52             ActionErrors actionErrors = new ActionErrors();
53             actionErrors.add("error", new ActionMessage("error", "no!!!") );
54 //            ActionMessages actionMessages = new ActionMessages();
55 //            actionMessages.add("error", new ActionMessage("error", "no!!!"));
56 //            ActionMessage actionMessage = new ActionMessage("error", "no!!!");
57             return actionErrors;
58         }
59         // return super.validate(mapping, request);
60         return null;
61     }
62 
63 }