Struts2的過濾器實現功能的過程詳解


Struts2是在Struts1的基礎上融合了WebWork框架(大部分)

的一個Web應用框架,采用了先進的設計理念,Struts2中的action也進行了改進

 

解決了Struts1由於action依賴於ServletAPI的一系列問題

 

一、過濾器

過濾器是Struts2中用來攔截前台發出的請求的功能,我們使用Struts2得在web.xml中配置過濾器,其中/*表示攔截所有請求,代碼如下:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app id="WebApp_ID" version="2.4"
 3          xmlns="http://java.sun.com/xml/ns/j2ee"
 4          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 5          xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
 6          http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
 7         <filter>
 8             <filter-name>struts2</filter-name>
 9             <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
10         </filter>
11         <filter-mapping>
12             <filter-name>struts2</filter-name>
13             <url-pattern>/*</url-pattern>
14         </filter-mapping>
15 </web-app>

二、獲取表單中的action值,如下代碼獲取請求的項目路徑中的hello值:

 1 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 2 <html>
 3   <head>
 4     <title>$Title$</title>
 5   </head>
 6   <body>
 7           <form action="${pageContext.request.contextPath}/hello" method="get">
 8               <button>提交</button>
 9           </form>
10   </body>
11 </html>

三、到src下的struts.xml,用dom4j解析后找到name為hello的action(注釋請忽略):

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 
 3 <!DOCTYPE struts PUBLIC
 4         "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
 5         "http://struts.apache.org/dtds/struts-2.3.dtd">
 6 
 7 <struts>
 8     <!-- 用於配置包名后綴。默認為action、actions、struts-->
 9     <!--<constant name="struts.convention.package.locators" value="actions" />-->
10     <!--用於配置類名后綴,默認為Action,設置后,Struts2只會去找這種后綴名的類做映射-->
11     <!--<constant name="struts.convention.package.locators" value="Action"/>-->
12     <!-- 編碼格式 -->
13     <!--<constant name="struts.i18n.encoding" value="UTF-8" />-->
14     <package name="PrintHello" extends="struts-default" namespace="/" >
15         <!--根據name得到action的路徑然后使用反射實現功能-->
16         <action name="hello" class="zm.HelloAction">
17             <result name="ok">/hello.jsp</result>
18         </action>
19     </package>
20 </struts>

四、得到name為hello的action標簽的class,然后進行反射執行action中的路徑的類的execute方法,代碼如下:

1 Class clazz = Class.forName("action全路徑");
2 //得到名稱是execute的方法
3 Method m = class.getMethod("execute");
4 //方法執行
5 Object obj = m.invoke();

五、得到返回值到action中找到result如果返回值與name相同則跳轉到配置的頁面中,代碼如下:

 

1 public class HelloAction {
2     public String execute(){
3         return "ok";
4     }
5 }

 

從上面的action類可以看出來,返回值為ok,與上方result的name相同

 

1 <result name="ok">/hello.jsp</result>

 

 

    --2019.7.2

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM