一、Struts2概述
Struts2是Apache發行的MVC開源框架。它只是表現層web(MVC)框架。
二、Struts2環境搭建
-
下載Struts2開發包:https://struts.apache.org/
- 創建web工程
- 導jar包
將Struts2開發包下常用jar包複製到web項目的lib文件夾下
- 添加配置文件
在src文件夾下新建struts.xml文件,內容如下,<struts>標籤中的內容我們後面再進行編寫。
<?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>
</struts>
- 配置struts過濾器
在web.xml中,配置Filter,配置的目的是用於攔截請求,由Struts的規則去處理請求,而不是用以前的servlet去處理。
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>Struts2Demo</display-name>
<!-- 配置struts的過濾器 【攔截所有請求】-->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<!-- struts過濾器攔截請求的規則 -->
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
- Tomcat運行web工程
運行Tomcat,若無報錯,則代表struts環境配置無誤。
三、Struts的Action配置講解
下面將在struts環境配置好後的基礎上實例一個demo。
1、新建包和類,並寫一個sayHello()方法
2、在struts.xml中配置package和action,寫如下代碼
<?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:包名,在struts.xml文件不能有相同的包名,包名是惟一
extends:繼承,固定struts-default
action:動作
name:相當於Servlet的映射路徑(@WebServlet)
class:處理請求的類,相當一個Servlet類
method:處理請求的方法
result:結果,寫返回的jsp頁面
-->
<package name="p1" extends="struts-default">
<action name="hello" class="com.hedong.helloStruts.helloAction" method="sayHello">
<result name="success">/success.jsp</result>
</action>
</package>
</struts>
3、在WebContent下新建success.jsp頁面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
hello! Struts2.
</body>
</html>
4、在瀏覽器地址欄中輸入http://localhost:8080/Struts2Demo/hello,即可正常打開success.jsp頁面。
四、流程分析
- tomcat啓動,加載web.xml
- 實例化並初始化過濾器
- 加載struts.xml配置文件
- 客戶端發送請求:hello
- 請求到達過濾器
- 截取請求的動作名稱name,並在struts.xml中找到對應動作
- 找到動作後實例化動作類
- 調用對應的動作方法method,方法有返回值
- 根據返回值找到name取值對應的結果視圖,即對應的success.jsp頁面
- 響應瀏覽器,展示結果