`
lxq_xsyu
  • 浏览: 65260 次
  • 性别: Icon_minigender_1
  • 来自: 西安
文章分类
社区版块
存档分类
最新评论

Struts2——(7)拦截器组件

 
阅读更多

AOP:面向切面编程(通过配置文件来指定作用到目标对象)

OOP:面向对象编程

AOP具有很好的可插拔特性,很灵活。

可用于封装共通的业务处理,之后可以通过配置作用到Action组件上。

共通的业务处理有:登录检查,日志记录,性能检测,事务处理。

1、拦截器规范

(1)必须实现Intercepter接口,实现interceptor方法。

(2)拦截器组件可以继承AbstractIntercepter类(实现了Intercepter接口)。

(3)拦截器组件可以继承MethodFilterIntercepter类(继承自AbstractIntercepter),增加了方法过滤功能(上面两种方式是拦截所有方法,这个方法可以拦截指定方法)。

2、拦截器相关配置(可参考struts-default.xml中的配置)

(1)声明

<interceptor name="拦截器名" class="包名.类名"/>

(2)引用

<interceptor-ref name="拦截器名或拦截器栈名"/>

(3)注意:当为Action组件引用了拦截器后,需要将默认的defaultStack拦截器显式引入。

3、示例

(1)示例一:记录操作日志

package xsyu.intercepter;

import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Map;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class LoggerIntercepter extends AbstractInterceptor{

	public String intercept(ActionInvocation invocation) throws Exception {
		String result = invocation.invoke(); //调用后续的拦截器或者action业务方法
		//记录用户操作
		Map<String, Object> session = (Map<String, Object>) invocation.getInvocationContext().getSession();
		//获取action名称
		String actionName = invocation.getProxy().getActionName();
		//获取类名
		String clasName = invocation.getProxy().getAction().toString();
		//获取方法名称
		String methodName = invocation.getProxy().getMethod();
		String user = "大碗干拌";
		String msg = "用户" + user + "在" + new Date() + 	"执行了" + actionName + "中" + methodName + "方法";
		FileWriter fw = new FileWriter("D:\\demo.log", true);
		PrintWriter pw = new PrintWriter(fw);
		pw.println(msg);
		pw.close();
		
		return result;
	}

}

<!DOCTYPE struts PUBLIC 
           "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
           "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
	<package name="pack1" extends="struts-default">
		<interceptors>
            <interceptor name="mylogger" class="xsyu.intercepter.LoggerIntercepter"/>
        </interceptors>
		<global-results>
			<result name="fail">/fail.jsp</result>
		</global-results>
		<action name="index">
			<result name="success" type="redirect">/add.jsp</result>
		</action>
		<action name="person" class="xsyu.action.PersonAction">
			<interceptor-ref name="mylogger"/>
			<interceptor-ref name="defaultStack"/>
			<result name="list">/index.jsp</result>
			<result name="init">/update.jsp</result>
			<result name="view">/view.jsp</result>
		</action>
		<action name="list" class="xsyu.action.ListAction">
			<result name="success">/list.jsp</result>
		</action>
	</package>
</struts>

注意:要添加默认拦截器。

一般是写两个拦截器,第一个拦截器先判断登录,第二个拦截器再记录日志。






分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics