简述Struts2的基本原理
核心:
Struts2的核心用一句话概括:将用户的请求与展示分开。
原理:
a. 用户发送http请求http://localhost:8080/struts2_0100_introduction/hello.action。
b. 该请求会被应用服务器(tomcat)接收到,应用服务器会去解析url地址,解析是哪个webapp发送过来的请求(本例中webapp的名称为struts2_0100_introduction)。
c. 该webapp会参照web.xml继续进行执行。
d. 于是发现web.xml文件中有一个名字叫做struts2的filter。
e. 于是执行该filter,该filter的执行会参照struts.xml。
f. 在struts.xml文件中找到对应的namespace,继续找到名字为hello的action,再找到result,返回给客户端。
配置文件如下:
1、 struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<!-- Add packages here -->
<constant name="struts.devMode" value="true" />
<package name="default" namespace="/" extends="struts-default">
<action name="hello">
<result>
/hello.jsp
</result>
</action>
</package>
</struts>
2、 web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<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>