Struts2配置拦截器,struts2加载常量时的搜索顺序

时间:2023-01-01 18:24:32

1:struts2加载常量时的搜索顺序

  1.Struts-default.xml

  2.Struts-plugin.xml

  3.Struts.xml

  4.Struts-properties(自己创建的)

  5.web.xml

如果在多个文件中配置了同一个常量,则后一个文件中配置的常量值会覆盖前面的文件配置的常量值

2:Struts2拦截器配置

  1.在Struts.xml中配置一个默认请求的action

<!-- 没有找到action时默认执行的action -->
<default-action-ref name="defaultAction"></default-action-ref>
<!-- 默认action -->
<action name="defaultAction">
            <result>default.jsp</result>
</action>

  2.在Struts.xml中添加interceptor

    <interceptors>
<!-- 自定义拦截器 ,逻辑名指向创建的拦截器实体类 -->
<interceptor name="myInterceptor"
class="cn.cnsdhzzl.intercptors.LoginInterceptor"></interceptor>
<!-- 引用struts默认拦截器和自定义拦截器,并放入一个值栈中方便引用,并且当引用到mic时,不需再指定默认default-interceptor,引用mic时默认初始化stack中所有引用 -->
<interceptor-stack name="mic">
<!-- 引用struts默认拦截器 到mic -->
<interceptor-ref name="defaultStack"></interceptor-ref>
<!-- 引用struts默认拦截器 到mic -->
<interceptor-ref name="myInterceptor"></interceptor-ref>
</interceptor-stack>
</interceptors>

3.创建自己的interceptor类

public class LoginInterceptor implements Interceptor {

    @Override
public String intercept(ActionInvocation invocation) throws Exception {
// 拦截操作
System.out.println("对象:" + invocation);
// 返回action逻辑视图名
Object action = invocation.getAction();
//
System.out.println("++++++++++++++" + action + "***********");
//
String value;
//
Map<String, Object> session = ActionContext.getContext().getSession();
Object object = session.get("name");
String actionName = invocation.getProxy().getActionName();
//
invocation.getProxy().getNamespace();
//
System.out.println(actionName);
if (actionName.equals("loginAction")) {
value = invocation.invoke();
} else if (action != null) {
value = invocation.invoke();
String method = invocation.getProxy().getMethod();
System.out.println("方法:" + method);
} else {
value = "login";
}
return value;
}
//省略init方法和destroy方法
}

注:先走拦截器,后走default-action

最后奉上Struts执行流程图,清笑纳

Struts2配置拦截器,struts2加载常量时的搜索顺序

当接收到一个httprequest , 
a) 当外部的httpservletrequest到来时 
b) 初始到了servlet容器 传递给一个标准的过滤器链 
c) FilterDispatecher会去查找相应的ActionMapper,如果找到了相应的ActionMapper它将会将控制权限交给ActionProxy 
d) ActionProxy将会通过ConfigurationManager来查找配置struts.xml 
       i. 下一步将会 通过ActionInvocation来负责命令模式的实现(包括调用一些拦截Interceptor框架在调用action之前) 
       ii. Interceptor做一些拦截或者初始的工作 
e) 一旦action返回,会查找相应的Result 
f) Result类型可以是 jsp或者freeMark 等 
g) 这些组件和ActionMapper一起返回给请求的url(注意拦截器的执行顺序) 
h) 响应的返回是通过我们在web.xml中配置的过滤器 
i) 如果ActionContextCleanUp是当前使用的,则FilterDispatecher将不会清理sreadlocal ActionContext;如果ActionContextCleanUp不使用,则将会去清理sreadlocals。