论坛首页 Java企业应用论坛

自己做了个支持DispatchAction的struts拦截器

浏览 10891 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2005-04-01  
/*
 * 创建日期 2005-3-31
 *
 */
package com.bupticet.strusinterceptor;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.struts.config.ActionConfig;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 * <p>Title: InterceptorConfig</p>
 *
 * <p>Description: 配置文件读取类</p>
 *
 * <p>Copyright: Copyright (c);北京邮电大学网络教育技术研究所[www.buticet.com] 2005</p>
 *
 * <p>Company: 北京邮电大学网络教育技术研究所[www.buticet.com] </p>
 * 
 * @author LJ-silver E-mail:LJ-silver@163.com
 * @version 1.0
 */
public class InterceptorConfig {
	private static HashMap config;
	
	private final static String filePathName = "/struts-interceptor.xml";  
	
	static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(InterceptorConfig.class);;
	
	public static void init();{
		if(config==null);{
			initResource();;
		}
	}
		
	private static void initResource();{
		Document document = null;
		try{
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();;
			DocumentBuilder db = dbf.newDocumentBuilder();;
			InputStream is = InterceptorConfig.class.getResourceAsStream(filePathName);;
			document = db.parse(is);;
			Element root = document.getDocumentElement();;
			NodeList interceptors = root.getElementsByTagName("interceptor-definition");;
			Map map = new HashMap();;
			for(int i = 0;i<interceptors.getLength();;i++);{
				Element interceptor = (Element); interceptors.item(i);;
				if(map.containsKey(interceptor.getAttribute("name");););{
					logger.error("In initResource();, Exception Occured !Info :不能重复配置interceptor-definition元素:"+interceptor.getAttribute("name"););;
				}else{
					map.put(interceptor.getAttribute("name");,interceptor.getAttribute("type"););;
				} 
			}
			NodeList actions = document.getElementsByTagName("action");;
			config = new HashMap();;
			for(int i = 0;i<actions.getLength();;i++);{
				Element action = (Element); actions.item(i);;
				String path = action.getAttribute("path");;
				NodeList methods = action.getElementsByTagName("method");;
				Map temp = new HashMap();;
				for(int j = 0;j<methods.getLength();;j++);{
					Element method = (Element); methods.item(j);;
					String name = method.getAttribute("name");;
					List actionInterceptorList = new ArrayList();;
					NodeList actionInterceptors = method.getElementsByTagName("interceptor");;
					for(int k = 0;k<actionInterceptors.getLength();;k++);{
						Element actionInterceptor = (Element); actionInterceptors.item(k);;
						String interceptorName = actionInterceptor.getAttribute("name");;
						if(map.containsKey(interceptorName););{
							actionInterceptorList.add(map.get(interceptorName););;
						}else{
							logger.error("In initResource();, Exception Occured !Info :没有"+interceptorName+"对应的interceptor-definition元素!" );;
						}

					}
					String[] allMethods = name.split(",");;
					for(int m = 0;m<allMethods.length;m++);{
						if(temp.containsKey(allMethods[m]););{
							logger.error("In initResource();, Exception Occured !Info :不能重复配置method元素:"+allMethods[m] );;
						}else{
							temp.put(allMethods[m],actionInterceptorList);;
						}
					}
				}
				if(config.containsKey(path););{
					logger.error("In initResource();, Exception Occured !Info :不能重复配置path元素:"+path );;
				}else{
					config.put(path,temp);;
				}
			}		
		}catch(IllegalArgumentException  e);{
			logger.error("In initResource();, Exception Occured ! 找不到文件/WEB-INF/classes/struts-interceptor.xml!,Info :" + e.getLocalizedMessage(););;
			e.printStackTrace();;
		}catch(SAXException e);{
			logger.error("In initResource();, Exception Occured ! XML文件/WEB-INF/classes/struts-interceptor.xml语法错误!,Info :" + e.getLocalizedMessage(););;
			e.printStackTrace();;
		}catch(Exception e);{
			logger.error("In initResource();, Exception Occured !Info :" + e.getLocalizedMessage(););;
			e.printStackTrace();;
		}
	}
	
	
	public static List getInterceptorList(String path,String method);{
		init();;
		List list = new ArrayList();;
		if(config.containsKey(path););{
			HashMap map = (HashMap);config.get(path);;
			if(map.containsKey(method););{
				list = (ArrayList);map.get(method);;
			}
		}
		return list;
	}
	
	public static List getInterceptorList(HttpServletRequest request);{
		ActionConfig actionConfig = (ActionConfig);request.getAttribute("org.apache.struts.action.mapping.instance");;
		String path = actionConfig.getPath();;
		String method = null;
		String parameter = actionConfig.getParameter();; 
		if(parameter!=null&&!"".equals(actionConfig.getParameter();););{
			method = request.getParameter(parameter);;
		}
		if(method==null||"".equals(method););{
			method = "execute";
		}
		return getInterceptorList(path,method);;
	}
	
	public static void test();{
		init();;
		for(Iterator it = config.keySet();.iterator();;it.hasNext();;);{
			String key = (String);it.next();;
			System.out.println(key);;
			Map map = (HashMap);config.get(key);;
			for(Iterator ite = map.keySet();.iterator();;ite.hasNext();;);{
				String key2 = (String);ite.next();;
				System.out.println("------------------------"+key2);;
				List list = (ArrayList);map.get(key2);;
				for(Iterator iter = list.iterator();;iter.hasNext();;);{
					System.out.println("------------------------"+"     "+"------------------------"+(String);iter.next(););;
				}
			}
		}
		
	
	}
}



/*
 * 创建日期 2005-3-31
 *
 */
package com.bupticet.strusinterceptor;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.web.struts.DelegatingActionProxy;

/**
 * <p>Title: InterceptorActionProxy</p>
 *
 * <p>Description: 拦截器代理Action类</p>
 *
 * <p>Copyright: Copyright (c);北京邮电大学网络教育技术研究所[www.buticet.com] 2005</p>
 *
 * <p>Company: 北京邮电大学网络教育技术研究所[www.buticet.com] </p>
 * 
 * @author LJ-silver  E-mail:LJ-silver@163.com
 * @version 1.0
 */
public class InterceptorActionProxy extends DelegatingActionProxy {
	
	static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(InterceptorActionProxy.class);;
	/**
	 * Pass the execute call on to the Spring-managed delegate Action.
	 * @see #getDelegateAction
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
															 HttpServletResponse response); throws Exception {
		Action delegateAction = getDelegateAction(mapping);;
		ActionForward forward = null;
		List interceptorList = InterceptorConfig.getInterceptorList(request);;
		int size = interceptorList.size();;
		if(size > 0);{
			ActionInterceptor[] interceptorArray = new ActionInterceptor[size];
			for(int i = 0;i<size;i++);{
				interceptorArray[i] = (ActionInterceptor);Class.forName((String);interceptorList.get(i););.newInstance();;
			}
			try{
				for(int i = 0;i<size;i++);{
					forward = interceptorArray[i].beforeAction(mapping, form, request, response);;
					if(forward!=null);{
						return forward;					
					}
				}						
				forward = delegateAction.execute(mapping, form, request, response);;
				for(int i = 0;i<size;i++);{
					interceptorArray[i].afterAction(mapping, form, request, response);;
				}
			
			}catch(Exception e);{
				e.printStackTrace();;
				logger.error("In execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response);, Exception Occured ! Info :" + e.getLocalizedMessage(););;
				for(int i = 0;i<size;i++);{
					forward = interceptorArray[i].throwsAction(mapping, form, request, response,e);;
					if(forward!=null);{
						return forward;
					}
				}
			}
		}else{
			forward = delegateAction.execute(mapping, form, request, response);;
		}
		return forward;
	}	

}



/*
 * 创建日期 2005-3-31
 *
 */
package com.bupticet.strusinterceptor;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 * <p>Title: ActionInterceptor</p>
 *
 * <p>Description: 拦截器接口</p>
 *
 * <p>Copyright: Copyright (c);北京邮电大学网络教育技术研究所[www.buticet.com] 2005</p>
 *
 * <p>Company: 北京邮电大学网络教育技术研究所[www.buticet.com] </p>
 * 
 * @author LJ-silver  E-mail:LJ-silver@163.com
 * @version 1.0
 */
public interface ActionInterceptor {
	/**
	 *  Called before an action is executed
	 *
	 *@param  mapping               The action mapping
	 *@param  form                  The action form
	 *@param  request               The request object
	 *@param  response              The response object
	 *@exception  IOException       If something goes wrong
	 *@exception  ServletException  If something goes wrong
	 */
	public ActionForward beforeAction(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response);
		throws IOException, ServletException;

	/**
	 *  Called after an action is executed
	 *
	 *@param  mapping               The action mapping
	 *@param  form                  The action form
	 *@param  request               The request object
	 *@param  response              The response object
	 *@exception  IOException       If something goes wrong
	 *@exception  ServletException  If something goes wrong
	 */
	public void afterAction(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response);
		throws IOException, ServletException;
		
	/**
	 *  Called when exception is throwed
	 *
	 */
	public ActionForward throwsAction(ActionMapping mapping,
	ActionForm form, HttpServletRequest request,
	HttpServletResponse response,Exception e);
		throws Exception;	
}

   发表时间:2005-04-01  
<?xml version="1.0" encoding="UTF-8"?> 
<!-- interceptor in SSH(Struts+Spring+Hibernate); created by LJ-silver-->
<struts-interceptor>

	<interceptor-definition name="login" type="com.bupticet.example.struts.interceptor.LoginPermissionInterceptor"/>


	<action path="/example/loginT">
		<method name="login">
			<interceptor name="login"/>
		</method>
	</action>

</struts-interceptor>
0 请登录后投票
   发表时间:2005-04-01  
/*
 * 创建日期 2005-3-31
 *
 */
package com.bupticet.example.struts.interceptor;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.Globals;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import com.bupticet.strusinterceptor.ActionInterceptor;

/**
 * <p>Title: </p>
 *
 * <p>Description: </p>
 *
 * <p>Copyright: Copyright (c);北京邮电大学网络教育技术研究所[www.buticet.com] 2005</p>
 *
 * <p>Company: 北京邮电大学网络教育技术研究所[www.buticet.com] </p>
 * 
 * @author LJ-silver
 * @version 1.0
 */
public class LoginPermissionInterceptor implements ActionInterceptor {

	/* 
	 * @see com.bupticet.strusinterceptor.ActionInterceptor#beforeAction(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse);
	 */
	public ActionForward beforeAction(
		ActionMapping mapping,
		ActionForm form,
		HttpServletRequest request,
		HttpServletResponse response);
		throws IOException, ServletException {
		HttpSession session = request.getSession();; 
		if(session.getAttribute(com.bupticet.example.Constants.USER_ATTRIBUTE);!=null);{
			ActionMessages errors = new ActionMessages();;
			errors.add(ActionMessages.GLOBAL_MESSAGE ,new ActionMessage("error.login.alreadylogin"););;
			request.setAttribute(Globals.ERROR_KEY, errors);;
			return mapping.findForward("failure");;
		}
		return null;
	}

	/* 
	 * @see com.bupticet.strusinterceptor.ActionInterceptor#afterAction(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse);
	 */
	public void afterAction(
		ActionMapping mapping,
		ActionForm form,
		HttpServletRequest request,
		HttpServletResponse response);
		throws IOException, ServletException {

	}

	/* 
	 * @see com.bupticet.strusinterceptor.ActionInterceptor#throwsAction(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Exception);
	 */
	public ActionForward throwsAction(
		ActionMapping mapping,
		ActionForm form,
		HttpServletRequest request,
		HttpServletResponse response,
		Exception e);
		throws Exception {
		return null;
	}

}

0 请登录后投票
   发表时间:2005-04-01  
突然发现strutsinterceptor写成strusinterceptor了,幸好用的eclipse,重构一下了,hoho


package com.bupticet.strusinterceptor;
0 请登录后投票
   发表时间:2005-04-01  
这个做法很值得提倡。 intercptor可以直接代替filter。而且可以很好的与action mapping进行结合。 不过要更好的实现,可能需要对struts进行一些重构!

可以参考webwork的interceptor实现,给struts加入interceptor支持。
好的interceptor实现需要实现如下几个features:
1) intercetpr chain stacks定义

2)default interceptor 支持

3)支持对struts module 统一 interceptor定义
0 请登录后投票
   发表时间:2005-04-01  
看过实现,发现无法指定interceptor的执行顺序,由于是采用dom模型,实际上执行顺序是在xml文件的先后顺序。这个在某些条件下也许会成为一个问题。

每次执行一个action都会导致重新创建interceptor对象,这样的效率上问题不知是否考量过。

另外如果其中一个interceptor抛出exception,导致整个系统出错。能否考虑在其中一个interceptor出错情况下系统继续执行。

强烈建议采用intercetpr chain。
0 请登录后投票
   发表时间:2005-04-01  
yimlin 写道
看过实现,发现无法指定interceptor的执行顺序,由于是采用dom模型,实际上执行顺序是在xml文件的先后顺序。这个在某些条件下也许会成为一个问题。

每次执行一个action都会导致重新创建interceptor对象,这样的效率上问题不知是否考量过。

另外如果其中一个interceptor抛出exception,导致整个系统出错。能否考虑在其中一个interceptor出错情况下系统继续执行。

强烈建议采用intercetpr chain。
很有道理,我将继续改进。


清外请介绍一下intercetor chain,谢谢。
0 请登录后投票
   发表时间:2005-04-02  
interceptor chain其实就是一个单向链表,在chain的各个节点都保存有下一个节点的引用,这样只要调用chain的首节点,整个chain各个节点都会被执行。

更多可以参考Jboss的实现。
0 请登录后投票
   发表时间:2005-04-05  
拦截器是干什么的?
0 请登录后投票
   发表时间:2005-04-06  
这里是对应的spring配置片断:
http://www.iteye.com/viewtopic.php?t=11937
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics