Struts2干貨筆記——第一天

目錄

1. 什么是Struts2
2. Struts2下載
3. Struts2的目錄結(jié)構(gòu)
4. Struts2中用到的一些jar包簡介
5. 第一個Struts2程序
6. Struts2的流程分析
7. Struts2配置
  • 7.1 Struts2的Action配置
  • 7.2 Struts2的常量配置
  • 7.3 指定多個struts配置文件
8. Action
  • 8.1 Action類的創(chuàng)建方式
  • 8.2 Action類的訪問
  • 8.3 Action訪問servlet api
9. Result結(jié)果類型

什么是Struts2

Struts2是一款優(yōu)秀的MVC框架,由傳統(tǒng)的struts1和webwork兩個經(jīng)典框架發(fā)展而來。

Struts2下載

下載地址:http://struts.apache.org/download.cgi

Struts2的目錄結(jié)構(gòu)

文件夾 內(nèi)容
apps 該文件夾包含了基于struts2的示例應(yīng)用
docs 該文件夾包含了struts2的文檔,包括struts2快速入門、struts2的文檔以及API等
lib 該文件夾包含了struts2框架核心類庫,以及struts2第三方插件類庫
src 該文件夾包含了struts2框架的全部源代碼

Struts2中用到的一些jar包簡介

  • struts2-core-2.3.15.1.jar Struts2框架的核心類庫
  • xwork-core-2.3.15.1.jar Command模式框架,WebWork和Struts2都基于xwork
  • ognl-3.0.6.jar Object Graph Navigation Language 對象圖導(dǎo)航語言,struts2框架通過它來讀寫對象的屬性
  • freemarker-2.3.19.jar Struts2的UI標簽的模板使用freeMarker編寫
  • commons-logging-1.1.3.jar ASD出品的日志包,Struts2框架使用這個日志包來支持Log4J和JDK1.4+的日志記錄
  • commons-lang3-3.1.jar 對java.lang包的增強
  • commons-io-2.0.1.jar 傳輸文件依賴的jar包
  • commons-fileupload-1.3.jar 文件上傳組件,2.1.6版本后需要加入此文件
    開發(fā)中為了方便,基礎(chǔ)的jar包可以直接導(dǎo)入apps\struts2-blank\WEB-INF\lib中的jar包

第一個Struts2程序

  1. 創(chuàng)建web應(yīng)用
  2. 導(dǎo)入必要的jar包
  3. 編寫jsp頁面
  4. 編寫Action服務(wù)端頁面
  5. 進行框架配置web.xml和struts.xml
  6. 運行測試

本次用到的是struts-2.3.15.1,只是舉一個簡單的例子讓大家知道什么是struts2,后面再詳細介紹。

編寫jsp頁面
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>helloword</title>
</head>
<body>
    <a href="${pageContext.request.contextPath }/hello">helloword</a>
</body>
</html>
編寫一個success頁面

action處理成功后跳轉(zhuǎn)到success頁面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>struts2</title>
</head>
<body>
    <h1>hello,struts2</h1>
</body>
</html>
編寫Action處理訪問的請求
package com.java.action;
public class HelloAction {
    public String execute(){
        System.out.println("hello world");
        return "success"; 
    }
}
配置Struts2核心控制器

在web.xml中配置Struts2

  <filter>
    <filter-name>Struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>Struts2</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
配置struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
    <package name="default" namespace="/" extends="struts-default">
        <action name="hello" class="com.java.action.HelloAction">
            <result name="success">/success.jsp</result>
        </action>
    </package>
</struts>
測試成功
struts2_1.1.png
struts2_1.2.png

Struts2的流程分析

簡要:
用戶發(fā)起請求 → StrutsPrepareAndExecuteFilter核心控制器 → interceptor攔截器 → Action類中 execute → result 結(jié)果頁面 →響應(yīng)

詳細流程圖

Struts2配置

  • default.properties:默認的常量配置。該文件保存在struts2-core-2.3.7.jar中org.apache.struts2包里面
  • struts-default.xml:Bean、攔截器、結(jié)果類型。該文件保存在struts2-core-2.3.7.jar
  • struts-plugin.xml:插件的配置信息。該文件保存在struts-Xxx-2.3.7.jar
  • struts.xml:web應(yīng)用默認的struts配置文件,配置action或常量。
  • struts.properties:配置常量。該文件是Struts的默認配置文件
  • web. xml:配置struts2,監(jiān)聽器,過濾器,常量。該文件是 Web 應(yīng)用的配置文件

后加載文件中struts2常量會覆蓋之前加載文件常量內(nèi)容

Struts2的Action配置

當(dāng)我們編寫完Action類后,就可以在struts.xml文件中配置該Action。在struts.xml中配該Action就是讓Struts2容器知道該Action的存在,并且能調(diào)用該Action來處理用戶請求。
Struts 2使用包來組織Action,因此,將Action定義放在包定義下完成,定義Action通過使用<package>下的<action>標簽來完成。定義action同時要給出name屬性和class屬性。

package的屬性

  • name:包名稱,在struts2的配置文件中,包名不能重復(fù) ,name并不是真正包名,只是為了管理Action
  • namespace:namespace屬性和name屬性,決定 Action的訪問路徑 (以/開始 )
  • extends:extends表示繼承自哪個包,通常開發(fā)中繼承 struts-default 包 (struts-default包在 struts-default.xml定義 )

action的屬性

  • name:該action的名字,同時也是也是需要處理的URL前半部分。<action>的name 和 <package>的namespace屬性 共同決定 Action的訪問路徑
    例如 :
    <package name="default" namespace="/user" extends="struts-default">
    <action name="hello" class="com.java.struts2.HelloAction">
    訪問路徑 /user/hello.action
  • class:指定了該Action的實現(xiàn)類,如果不指定,默認ActionSupport類

Action只是一個控制器,它并不直接對瀏覽器生成響應(yīng),所以在Action處理完用戶的請求后,Action需要將指定的視圖資源展示給用戶,要配置映射關(guān)系,用<result>標簽。<result>元素有兩個屬性,name和type,系統(tǒng)默認name屬性是success,type屬性是dispatch。

每個result標簽都代表了一個可能輸出的結(jié)果。當(dāng)Action類的方法執(zhí)行完成時,它返回一個字符串作為結(jié)果,框架根據(jù)這個結(jié)果選擇對應(yīng)的result(result的name屬性),向用戶輸出結(jié)果頁面。在com.opensymphony.xwork2.Action接口中定義了一組標準的結(jié)果代碼,可供開發(fā)人員使用,當(dāng)然了只有我們的action繼承ActionSupport 這個類才可以使用下面的結(jié)果代碼,后面再來詳細總結(jié)結(jié)果類型

public interface Action{
       public static final String SUCCESS = “success”;
       public static final String NONE = “none”;
       public static final String ERROR = “error”;
       public static final String INPUT = “input”;
       public static final String LOGIN = “l(fā)ogin”;
  }

name屬性值

返回結(jié)果 解釋
SUCCESS Action執(zhí)行成功,返回相應(yīng)的視圖,success是 name屬性的默認值
NONE Action執(zhí)行成功,但并不返回任何視圖
ERROR Action執(zhí)行失敗,返回到 錯誤處理視圖
INPUT Action在執(zhí)行時需要從前端界面獲取參數(shù),INPUT就是代表這個輸入?yún)?shù)的界面,通常會對這些參數(shù)進行驗證,如果驗證沒有通過,將自動返回到該視圖
LOGIN Action因為用戶沒有登陸,將返回該登陸視圖,要求用戶進行 登陸驗證

Struts2的常量配置

在default.properties文件中聲明了許多常量
手動設(shè)置常量:

  • 1.struts.xml(應(yīng)用最多)
    <constant name="常量名稱" value="常量值"></constant>
  • 2.struts.properties(基本不使用)
  • 3.web.xml(了解)
    配置常量,是使用StrutsPrepareAndExecuteFilter的初始化參數(shù)來配置的.
    <init-param>
    <param-name>struts.action.extension</param-name>
    <param-value>do,,</param-value>
    </init-param>
    常用常量
  • <constant name="struts.i18n.encoding" value="UTF-8"/>
    相當(dāng)于request.setCharacterEncoding("UTF-8"); 解決post請求亂碼
  • <constant name="struts.action.extension" value="action"/>
    訪問struts2框架Action訪問路徑擴展名struts.action.extension=action,默認以.action結(jié)尾,不寫擴展名也會分發(fā)給 Action
  • <constant name="struts.serve.static.browserCache" value="false"/>
    false不緩存,true瀏覽器會緩存靜態(tài)內(nèi)容,產(chǎn)品環(huán)境設(shè)置true、開發(fā)環(huán)境設(shè)置false
  • <constant name="struts.devMode" value="true" />
    提供詳細報錯頁面,修改struts.xml后不需要重啟服務(wù)器

指定多個struts配置文件

隨著網(wǎng)站規(guī)模增加,Action數(shù)量也會增加,導(dǎo)致struts.xml配置文件非常臃腫,可以用一個struts.xml文件包含其他配置文件。

<struts>
  <include file=""struts1.xml>
  <include file=""struts2.xml>
</struts>

Action

HTTP請求提交給Struts2的StrutsPrepareAndExecuteFilter 核心控制器,根據(jù)請求分發(fā)給不同Action

Action類的創(chuàng)建方式

  1. 創(chuàng)建一個POJO類
    POJO類指簡單的java對象(Plain Old Java Objects),指的是沒有實現(xiàn)任何借口,沒有繼承任何父類的類(除object)。
    優(yōu)點:無耦合
    缺點:所有功能都要自己完成
  2. 創(chuàng)建一個類,實現(xiàn)Action接口.com.opensymphony.xwork2.Action
    優(yōu)點:耦合低,提供了五種結(jié)果視圖,定義了一個行為方法。
    public static final String SUCCESS = "success"; // 數(shù)據(jù)處理成功 (成功頁面)
    public static final String NONE = "none"; // 頁面不跳轉(zhuǎn) return null; 效果一樣
    public static final String ERROR = "error"; // 數(shù)據(jù)處理發(fā)送錯誤 (錯誤頁面)
    public static final String INPUT = "input"; // 用戶輸入數(shù)據(jù)有誤,通常用于表單數(shù)據(jù)校驗 (輸入頁面)
    public static final String LOGIN = "login"; // 主要權(quán)限認證 (登陸頁面)
    缺點:所以工作都要自己實現(xiàn)。
  3. 創(chuàng)建一個類,繼承ActionSupport類(經(jīng)常使用). com.opensymphony.xwork2.ActionSupport
    ActionSupport類已經(jīng)實現(xiàn)了Action接口。
    優(yōu)點:表單校驗、錯誤信息設(shè)置、讀取國際化信息 三個功能都支持.
    缺點:耦合度高

Action類的訪問

  1. 通過設(shè)置method的值,來指定訪問action類中的哪一個方法
    如果沒有指定method指,默認執(zhí)行execute方法.
    <action name="regist" class="com.java.struts2.RegistAction">
    如果設(shè)置method,則執(zhí)行相應(yīng)方法
    <action name="regist" class="com.java.struts2.RegistAction" method="regist">
  2. 使用通配符來簡化配置
    在配置<action>元素時,允許在指定name屬性時,使用通配符*來代表一個或多個任意字符,在class、method屬性以及<result>子元素中通過{N}形式代表前面第N個*匹配字符串。
    簡單案例:
<action name="*" class="com.java.struts.HelloAction" method="{1}">
      // * 匹配訪問字符串,例如 http://localhost:8080/struts/add,則匹配add
      //   method中的{1}指前面第一個匹配的字符串 :method="add"
      <result name="success">/{1}.jsp</result>
      //   /add.jsp
</action>

復(fù)雜案例:

<action name="*_*" class="com.java.struts.{1}" method="{2}">
      // 匹配兩個字符串 訪問http://localhost:8080/struts/UserAction_login,
      // {1}則匹配UserAction  {2}則匹配login
      <result name="success">/{2}.jsp</result>
      //  /login.jsp
</action>
  1. 動態(tài)方法調(diào)用(了解)
    可以通過url動態(tài)的指定調(diào)用Action哪個方法而無需配置<action>的method屬性。使用 !方法名 指定調(diào)用Action中哪個方法。
    訪問:localhost:8080/struts2/user!add 會執(zhí)行UserAction中add的方法
    前提是struts.enable.DynamicMethodInvocation = true 常量值 為true
<action name="add" class="com.java.struts2.UserAction">
  <result>/success.jsp</result>
</action>

Action訪問servlet api

在struts2中獲取servlet api有三種方式:

1. 通過ActionContext來獲取(重點)
Servlet API最常見操作就是表單提交請求參數(shù)獲取,向request、session、application三個范圍存取數(shù)據(jù)
actionContext = ActionContext.getContext(); 返回actionContext實例對象

  1. actionContext.getParameters(); 獲得所有請求參數(shù)Map集合
  2. actionContext.put("name", "小明");存一個值,相當(dāng)于setAttribute方法
  3. actionContext.get("name") 獲得request對應(yīng)的key值
  4. actionContext.getSession(); 獲得session數(shù)據(jù)Map
  5. actionContext.setSession(Map);將該Map里的key-value保存為HttpSession中的屬性名和值
  6. actionContext.getApplication(); 獲得ServletContext數(shù)據(jù)Map
  7. actionContext.setApplication(); 將該Map里的key-value保存為ServletContext中的屬性名和值

2. 接口注入方式獲取(IOC)
struts2在實例化一個action對象時,如果發(fā)現(xiàn)他實現(xiàn)了相關(guān)的Aware接口,就會把相應(yīng)的資源通過Aware接口方法注入進去,所以叫做注入方式(IOC方式),以request為例,實現(xiàn)了ServletRequestAware接口,就會有一個setServletRequest()方法獲取request對象,Aware接口實際上是一種攔截器,他會在執(zhí)行Action前執(zhí)行,把相關(guān)的servlet對象設(shè)置進來

  • 要求action類必須實現(xiàn)提定接口
  • 重寫接口中的方法
  • 聲明一個對象,使用接口中的方法的參數(shù)對聲明的對象賦值
  private HttpServletRequest request;
  public void setServletRequest(HttpServletRequest request) {
        this.request = request;
    }

原理是由struts2中的一個interceptor完成的
<interceptor name="servletConfig" class="org.apache.struts2.interceptor.ServletConfigInterceptor">

 if (action instanceof ServletRequestAware) { 
         //判斷action是否實現(xiàn)ServletRequestAware接口
HttpServletRequest request = (HttpServletRequest) context.get(HTTP_REQUEST); 
        //得到request對象.
((ServletRequestAware) action).setServletRequest(request);
        //將request對象通過action中重寫的方法注入。
}

3. 通過ServletActionContext獲取
在ServletActionContext中的方法都是static
ServletActionContext.getRequest() 獲得request對象
ServletActionContext.getResponse() 獲得response 對象
ServletActionContext.getServletContext() 獲得ServletContext對象

Result結(jié)果類型

Action處理完用戶請求后,將返回一個普通字符串,struts2根據(jù)這個字符串來決定響應(yīng)哪個結(jié)果,處理結(jié)果使用<result>元素來配置。

  • 局部結(jié)果:將<result>作為<action>的子元素進行配置
    <action name="result" class="com.java.struts2.ResultAction">

    <result name="success">/result.jsp</result>
    </action>

  • 全局結(jié)果:將<result>作為<global-results>的子元素進行配置
    <global-results>

    <result name="success">/result.jsp</result>
    </global-results>

配置<result>有兩個屬性:name和type
name:該屬性配置的邏輯視圖名
type:該屬性的結(jié)果類型

在struts-default.xml文件中定義了type可以取的值

<result-type name="chain" class="com.opensymphony.xwork2.ActionChainResult"/>
<result-type name="dispatcher" class="org.apache.struts2.dispatcher.ServletDispatcherResult" default="true"/>
<result-type name="freemarker" class="org.apache.struts2.views.freemarker.FreemarkerResult"/>
<result-type name="httpheader" class="org.apache.struts2.dispatcher.HttpHeaderResult"/>
<result-type name="redirect" class="org.apache.struts2.dispatcher.ServletRedirectResult"/>
<result-type name="redirectAction" class="org.apache.struts2.dispatcher.ServletActionRedirectResult"/>
<result-type name="stream" class="org.apache.struts2.dispatcher.StreamResult"/>
<result-type name="velocity" class="org.apache.struts2.dispatcher.VelocityResult"/>
<result-type name="xslt" class="org.apache.struts2.views.xslt.XSLTResult"/>
<result-type name="plainText" class="org.apache.struts2.dispatcher.PlainTextResult" />

重點:chain dispatcher redirect redirectAction stream

  • dispatcher:是最常用的結(jié)果類型,代表的是請求轉(zhuǎn)發(fā),也是struts2框架默認的類型,一般用于從action跳轉(zhuǎn)到一個頁面。將控制權(quán)轉(zhuǎn)發(fā)給程序里的某個資源,不能是外部資源,若需要把控制權(quán)重定向到一個外部資源,應(yīng)該使用redirect結(jié)果類型。
  • redirect:重定向要另一個資源,而不是轉(zhuǎn)發(fā),一般用于從action跳轉(zhuǎn)到一個頁面。
  • redirectAction: 代表重定向 它一般用于從action跳轉(zhuǎn)另一個action。
  • stream:代表的是服務(wù)器端返回的是一個流,一般用于下載。
  • chain:相當(dāng)于請求轉(zhuǎn)發(fā)。它一般情況下用于從一個action跳轉(zhuǎn)到另一個action。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容