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

因上努力,果上随缘
原文地址:https://www.cnblogs.com/zemengcheng/p/11123248.html