Struts2的控制器
控制器(Controller)是MVC框架的核心部分,
Struts2框架的控制器由三种组件组成:过滤器、拦截器、Action类。
过滤器:
过滤器是Struts2控制器的最前端控制器,请求对象首先被过滤器过滤
1、ActionContextCleanUp过滤器:该过滤器是可选的,主要为了集成SiteMesh等插件。
2、其他过滤器:其他过滤器是根据需要配置的过滤器,例如,应用中使用到了SiteMesh这样的插件,就需要配置插件的相关过滤器。
3、FilterDispatcher过滤器:通过该过滤器的主要功能包括执行Action、清空ActionContext对象以及服务静态内容等,是Struts2应用中必须配置使用的过滤器。
web.xml中配置如下:
- <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>
<struts>
<package name="com.etc.chapther" extheds="struts-default">
<action name="Login" class="com.etc.action.LoginAction">
<result name="success">/welcome.jsp</result>
<result name="fail" >/index.jsp<result>
</action>
</package>
</struts>
上述struts.xml中的com.etc.chaper包没有定义默认拦截器引用,唯一的Action也没有定义拦截器引用,但是LoginAction仍然有拦截器。
因为配置文件struts.xml中的包都默认继承struts-defalut报,所以com.etc.chapter包定义了默认拦截器引用
<default-interceptor-ref name="defalutStack"/>
Action
Action是Struts2的第三层次的控制器,需要程序员自行开发。
------------------------------------------------
自定义拦截器
public class InterceptorTester implements Interceptor{
public void destroy(){
}
public void init(){
}
public String intercept(ActionInvocation arg0) throws Exception{
System.out.println("InterceptorTester拦截器被调用,拦截的Action的类名:"+arg0.getAction().getClass().getName());
arg0.invoke();
return null;
}
}
在struts.xml中配置
<package name="com.etc.chapther" extheds="struts-default">
<interceptors>
<interceptor name="tester" class="com.etc.interceptor.InterceptorTester"></interceptor>
</interceptors>
</package>
<package name="com.etc.chapther" extheds="struts-default">
<action name="Login" class="com.etc.action.LoginAction">
<interceptor-ref name="defaultStack" ></interceptor-ref>
<interceptor-ref name="tester"></interceptor-ref>
<result name="success">/welcome.jsp</result>
<result name="fail" >/index.jsp<result>
</action>
</package>