1.导包
2.在web.xml里配置struts2过滤器
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>Text</display-name>
<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>
<!-- struts2过滤器,用来拦截所有的.action请求 -->
<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>*.action</url-pattern>
</filter-mapping>
</web-app>
3.创建一个struts.xml(struts.xml文件要在包外面),并进行配置
主要属性说明:package-name:用于区别不同的package;必须是唯一的、可用的变量名;用于其它package来继承;
1.package标签和属性解释
package表示分模块管理,不同的模块action放在不同的package下
name:表示package的名称,可以自定义,但是不允许重复
namespace:命名空间,/代表根路径,也可以自定义路径,访问action使用该名名空间
extends:继承的父package名称,这里只需要知道继承struts-default即可
2.action标签及属性解释
action表示配置指定的servlet处理类和映射路径
name:表示action的映射路径
1)和package的命名空间息息相关
2)如果web.xml配置的是过滤*.action,那么名称无需写XX.action
class:表示servlet处理类的全路径(包名+类名),如果不写交由ActionSupport类处理
method:表示使用哪个方法处理请求,默认使用execute方法处理
3.result标签及属性解释
result表示结果集的配置
name:表示action返回的字符串,可以自定义,本例是success
type:表示处理请求后跳转的方式,默认为dispatcher(转发)
常用的还有redirect(重定向)等等
result中配置的是跳转的页面或其他action,本例是test.jsp
下面是struts .xml配置完的图片
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<package name="default" namespace="/" extends="struts-default">
<action name="loginpost" class="com.znsd.text.Jingr">
<!-- 结果为“success”时,跳转至success.jsp页面 -->
<result name="success">/WEB-INF/pages/login.jsp</result>
<!-- 结果为"error"时,跳转至fail.jsp页面 -->
<result name="error">/WEB-INF/pages/welcome.jsp</result>
</action>
<action name="login" class="com.znsd.text.LoginAction">
<!-- 结果为“success”时,跳转至success.jsp页面 -->
<result name="success">/WEB-INF/pages/login.jsp</result>
</action>
</package>
</struts>