1.在浏览器输入访问地址
比如:
2.先加载web.xml文件
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <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> <context-param> <param-name>struts.i18n.encoding</param-name> <param-value>UTF-8</param-value> </context-param>
3.struts2过滤器去加载配置文件struts.xml
<?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> <!--i18n 国际化,相当于在servlet中设置的编码,解决了post请求的中文乱码--> <constant name="struts.i18n.encoding" value="UTF-8"></constant> <!--extension 使用设置action访问的扩展名 action,, 可以改成do 为什么改成do因为struts1用的是do --> <constant name="struts.action.extension" value="do"></constant> <!--developerMode 开发者模式 1.热部署,你修改配置文件后,等一段时间会自动加载 2.提高错误信息的提示(友好的错误提示) --> <constant name="struts.devMode" value="true"></constant> <!-- package:跟项目中的package没关系,这里的package是用来管理action name:给这个package起个名字,内有什么意义,一般情况下它的命名是按照package管理action的分类来命名 package和package的名字不能重复 namespace:访问路径地址前缀,跟name没有关系,跟其他的package中的namespace能不能重复,没有要求 extends:继承 继承自struts-default必须写,名字不能更改 它是从struts核心包struts-2.2-core下面的struts-default.xml这里配置了很多默认的属性 abstract:抽象 声明的一个标志,当前这个配置文件不能独立运行,等待被继承 --> <package name="hello" namespace="/hello" extends="struts-default"> <!-- action配置详解 name:给action起个名字,决定了访问路径最后的地址 class:类的完整路径(默认为ActionSupport类) method:访问类中的方法(默认值为execute) --> <action name="helloAction" class="cn.hd.hello.HelloAction" method="hello"> <!-- result:配置详解 name:对应的是action类中的method的返回值 名字和结果只要与action类中的返回值结果一样都可以 type:结果类型(默认值是转发,也可以设置为其他的值) dispatcher转发 redirect重定向 标签中的值:跳转的页面 --> <result name="success">/hello.html</result> </action> </package> <!--将其他目录下的struts.xml文件读取到struts.xml--> <include file="cn/hd/dynamic/struts01.xml"></include> <include file="cn/hd/default_demo/struts02.xml"></include> <include file="cn/hd/jump/struts03.xml"></include> <include file="cn/hd/servletApi/struts05.xml"></include> <include file="cn/hd/ajax/struts06.xml"></include> <include file="cn/hd/param/struts07.xml"></include>
4.路径中的第一个地址namespace遍历你的struts.xml中package属性,如果找到了和地址中匹配的就进入该.xml中,如果没有找到就会报异常
5.找到了该package再去访问路径后面的地址,然后去package找action的name属性,如果找到匹配的,就进入该action配置的Action类中
6.通过action的method属性去执行Action类对应的方法
7.根据执行的Action类中的方法获得的返回值,然后找到struts.xml里面的result。通过标签result中的配置打开对应的页面