struts2 基本流程

时间:2023-03-09 19:35:12
struts2 基本流程

一、配置过程

1.在web.xml中配置过滤器

  <filter>
<filter-name>StrutsPrepareAndExecuteFilter</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter> <filter-mapping>
<filter-name>StrutsPrepareAndExecuteFilter</filter-name>
<url-pattern>/*</url-pattern>

 

2.导入struts2框架包

struts2 基本流程

3.在src目录下创建struts.xml(必须在src下创建)

文件开头(dtd文件版本跟导入的struts2的基本一致)

<?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">

 

4.在Preference中添加struts-2.3文件,并加入key值,key值为struts.xml文件开头“

-//Apache Software Foundation//DTD Struts Configuration 2.3//EN

struts2 基本流程

二、struts2基本流程

1.请求

   	测试有命名空间的hello world:<br>
<a href="${pageContext.request.contextPath}/base/HelloWorldAction.action">有命名空间</a><br> 测试没有命名空间的hello world:<br>
<a href="${pageContext.request.contextPath }/HelloWorldAction.action">没有命名空间</a><br>

请求对应图

struts2 基本流程

2.通过web.xml文件进行过滤,跳转至struts.xml配置文件中

3.struts.xml配置文件和action的代码为:

<?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"> <!-- 导入dtd文件 -->
<struts>
<!-- package
1.为包,能方便进行action管理
2.属性
name:
代表包的名称
主要用于继承
name的名称是唯一的
namespace:
命名空间
在客户端访问action时使用,也就是说在url中使用
如果没有命名空间
http://localhost:8080/struts2/a.action
http://localhost:8080/struts2/b.action
上面写的url没有模块的概念,但是如果有命名空间,就有模块的概念
如果namespace有值,则在result中,会把命名空间加入到响应的路径中,如果是重定向,那么就会重定向到该命名空间下的action
extends
配置文件中的继承
-->
<package name="helloworld" namespace="/base" extends="struts-default">
<action name="HelloWorldAction" class="com.struts2.action.HelloWorldAction">
<!--
result
struts2会根据result进行转发或者重定向
属性
name
为result名称
属性的值和action中execute方法的返回值一致
如果不写name属性,则会默认为name的值为success
type
代表返回方式
选择重定向还是转发,还可以重定向到action
如果type没有设定,则为默认值。这个默认值可以从struts-default.xml中得出结论
<result-type name="dispatcher"
class="org.apache.struts2.dispatcher.ServletDispatcherResult"
default="true"/>
-->
<result>success.jsp</result>
</action>
</package>
</struts>

 

package com.struts2.action;

import com.opensymphony.xwork2.Action;

public class HelloWorldAction implements Action {

	public String execute() throws Exception {
System.out.println("Hello World");
return SUCCESS;
} }

  

会寻找与请求对应的action,并在result中做出相对应的反馈,取得反馈的值后会经过两个struts2中的2个框架类进行转发(内部也是servlet),最后跳转到相应的页面

总流程为:

struts2 基本流程