1. 导入jar包
2. 配置核心过滤器,只有配置了核心过滤器,struts2的功能才生效,在web.xml中,核心过滤器在struts-core-xx.jar下
<span style="white-space:pre"> </span><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>
3. 编写 struts.xml ,在 src 下,默认必须叫 struts.xml ,文件 dtd 在 struts-core-xx.jar 最下面, struts-2.1.7.dtd 在注释部分中找
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
"http://struts.apache.org/dtds/struts-2.1.7.dtd">
<struts>
<!-- 包管理:
name:自定义名称
extends:把struts-default.xml配置的内容直接继承过来
namespace:命名空间,所有管理的action都被映射到哪里,/表示webroot下
-->
<package name="default" extends="struts-default" namespace="/">
<action name="hello" class="com.bjsxt.smallming.action.HelloAction">
<result name="hello">index.jsp</result>
</action>
</package>
</struts>
4. 修改 struts.xml 默认名称及路径:
<span style="white-space:pre"> </span><filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
<init-param>
<param-name>config</param-name>
<param-value>struts-default.xml,struts01.xml</param-value>
</init-param>
</filter>
寻找路径从classes目录找起,struts01.xml放入到WEB-INF/config中配置如下
<span style="white-space:pre"> </span><filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
<init-param>
<param-name>config</param-name>
<param-value>struts-default.xml,../config/struts01.xml</param-value>
</init-param>
</filter>
Struts.xml配置详解
1 method属性:默认值execute,控制执行哪个方法
2 name:与方法返回值对应,默认值success
3 type:跳转类型
dispatcher:从Action转发到jsp
redirect:从Action重定向到jsp
chain:Action链,从action转发到action
redirectAction:从action重定向到action
stream:访问后返回I/O流内容
JSON:返回json对象
4 允许在在<action>name属性中存在任意个*,*表示任意内容,在class和method中通过{从1开始数字}调用第几个*对应的内容
在后期加强项目的用户体验度,设置默认action内容,防止出现404等问题
<span style="white-space:pre"> </span><default-action-ref name="mydefault"></default-action-ref>
<action name="mydefault" class="com.bjsxt.smallming.action.HelloAction" method="mydefault">
<result name="mydefault">mydefault.jsp</result>
</action>
把所有action的统一result提出到全局<package>下。编译器在寻找时,先找<action>下是否有对应name属性的<result>如果没有,去<global-results>寻找,如果还没有,出现404:
<global-results>
<result name="success">index.jsp</result>
</global-results>
处理500办法,也就是错误页面
<global-exception-mappings>
<exception-mapping result="error" exception="java.lang.ArithmeticException"></exception-mapping>
</global-exception-mappings>
Result属性:在<golbal-results>找对应名称的全局结果
exception属性:发生了什么类型的异常,包名.类名