struts2(1)介紹及快速入門

目錄

struts2介紹

struts2快速入門

1.下載struts開發包

2.解壓struts開發包

3.創建一個web工程,導入jar包這個導入的jar包是實例程序中的blank中的基本jar包

4.創建一個action

5.配置struts.xml  struts2的配置文件

6.配置web.xml  struts2核心過濾器的配置

struts的工作步驟 


struts2介紹

struts2是一個機遇mvc涉及模式的web應用框架,它本質上相當於一個servlet,在mvc涉及模式中,struts2作爲控制器(controller)來建立模型與視圖的數據交互,struts2是struts的下一代產品,是在struts1和webwork的技術基礎上進行了合併的新的struts2框架。其全新的struts2的體系結構與struts1的體系結構差別很大。struts2以webwork爲核心,採用攔截器的機制來處理用戶的請求,這樣的涉及也使得業務邏輯控制器能夠與servletAPI完全脫離開,所以struts2是webwork的更新產品,雖然從struts1到struts2有這太大的變化,但是相對於webwork,struts2的變化很小。

struts1  基於servlet  線程不安全

struts2的優勢:

1.提供exception處理機制

2.result方式的頁面導航,通過result標籤很方便的實現重定向和頁面跳轉

3.通過簡單、集中的配置來調度業務類,是的配置和修改都非常容易。

4.提供簡單、統一的表達式語言來訪問所有的可供訪問的數據

5.提供標準、強大的驗證框架和國際性框架。

6.提供強大的、可以有效減少頁面代碼的標籤

7.提供良好的ajax支持

8.擁有簡單的插件,只需要放入相應的jar包就能擴展struts框架,比如實現自定義的結果類型、自定義標籤。

常見的web層框架

struts1

struts2

webwork

springmvc

web層框架都會有一個特點,就是基於前段控制器模式來實現的。

 

struts2快速入門

1.下載struts開發包

https://struts.apache.org/

2.解壓struts開發包

apps 官方提供的示例程序

docs官方api

lib struts核心庫

src源碼

3.創建一個web工程,導入jar包這個導入的jar包是實例程序中的blank中的基本jar包

4.創建一個action

HelloACtion

package cn.ycsj.hiber.test;
public class HelloAction {
    public  String Hello(){
        System.out.println("hello,world");
        return  "success";
    }
}

5.配置struts.xml  struts2的配置文件

<?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="hello" namespace="/hello" extends="struts-default">
        <action name="HelloAction" class="cn.ycsj.hiber.test.HelloAction" method="Hello">
        <result name="success">/Hello.jsp</result>
        </action>
    </package>
</struts>

這個文件中定義了類文件和訪問地址的拼接,這個簡單的配置拼接的地址是localhost:8080/StrutsTest/hello/HelloAction  如果這個action返回success 就轉發到Hello.jsp頁面

6.配置web.xml  struts2核心過濾器的配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
<!--將struts2 核心過濾器配置到web.xml-->
<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>
</web-app>

通過訪問localhost:8080/StrutsTest/hello/HelloAction  可以看到控制檯打印出來消息並且頁面轉發到Hello.jsp頁面。

這樣一個最簡單的struts2流程就已經通了。

struts的工作步驟 

服務器啓動加載web.xml配置文件中的過濾器,這裏是對所有的請求都進行過濾。----------->過濾器處理請求的url ---------->   將url拆分爲namespace命名空間和action  ------------>查詢struts中定義的namespace --------->查詢對應namespace下的action name 如果對應--------->根據配置的class找到對應的action對象 根據反射創建實例 獲取其中的方法、執行方法------>根據返回值轉發或者重定向。

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章