先看两个配置文件:web.xml 和 struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>struts2_01</display-name>
<!-- 过滤器配置 -->
<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>
<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>
<?xml version="1.0" encoding="UTF-8"?>
<!--1.创建struts2核心配置文件
核心配置文件名称和位置是固定的
位置必须在src下面,名称 struts.xml
2.引入dtd约束
-->
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<!--3.action配置 -->
<struts>
<package name="hellodemo" extends="struts-default" namespace="/">
<!--name:web访问名称
class:全路径的类名
-->
<action name="hello" class="struts2Test.HelloAction">
<!-- 配置方法的返回值到页码,这里配置好了,就相当于servlet里转发到jsp页面-->
<result name="ok">/hello.jsp </result>
</action>
</package>
</struts>
当在浏览器输入地址http://localhost:8080/struts2_01/hello时,struts框架执行的基本流程:
一、过滤器
先经过过滤器,过滤器是在服务器启动就创建好了,只有过滤器允许通过才能进行下一步。
二、得到请求路径中的hello
三、解析struts.xml
在项目的src下获得struts.xml,并用dom4j解析。对比请求路径中的hello和struts.xml <action>标签的name属性值是否一致,如果都是hello则执行下一步。
四、找到<action>标签中的class属性
得到这个类的全路径,使用反射实现这个类的功能
五、得到execute方法的返回值
这里我写的是"ok",struts.xml <reslut>标签中配置为“ok”
对比是否一致,如果一致,则跳转到配置的/hello.jsp页面
如下图: