---
title: "使用自定义拦截器加载字典表"
author: "fosa0989"
date: "2009-04-22T17:20:13Z"
tags: []
categories: ["企业架构"]
slug: "untitled"
draft: false
lastmod: "2009-05-04T00:19:08Z"
id: 372831
url: "https://hchen229.iteye.com/blog/372831"
---

使用自定义拦截器可以直接实现接口com.opensymphony.xwork2.interceptor.Interceptor，也可以继承com.opensymphony.xwork2.interceptor.AbstractInterceptor。
1 定义Interceptor

```java

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

import com.config.Constants;
import com.dal.dao.DictDataDao;
import com.vo.DicData;
import com.vo.DicType;

import java.util.*;
/**
 * @author CHH
 */
public class LoadDictInterceptor extends AbstractInterceptor{
	private DictDataDao dictDataDao;
	/* (non-Javadoc)
	 * @see com.opensymphony.xwork2.interceptor.AbstractInterceptor#intercept(com.opensymphony.xwork2.ActionInvocation)
	 */
	@Override
	public String intercept(ActionInvocation ai) throws Exception {
        Map session = ai.getInvocationContext().getSession();
 
		if(session.get(Constants.AREA_LIST)==null){
			List<DicData> areas=dictDataDao.findByType(DicType.TYPE_AREA);
			session.put(Constants.AREA_LIST, areas);
		}
		
		if(session.get(Constants.ORGTYPE_LIST)==null){
			List<DicData> areas=dictDataDao.findByType(DicType.TYPE_ORGANIZATION_TYPE);
			session.put(Constants.ORGTYPE_LIST, areas);
		}  
         
		return ai.invoke();
	}
	/**
	 * @return the dictDataDao
	 */
	public DictDataDao getDictDataDao() {
		return dictDataDao;
	}
	/**
	 * @param dictDataDao the dictDataDao to set
	 */
	public void setDictDataDao(DictDataDao dictDataDao) {
		this.dictDataDao = dictDataDao;
	}


}

```

2 配置Interceptor
Struts.xml

```java

	<package name="pmanage"  extends="struts-default">
		<!-- 定义Interceptor -->
        <interceptors>
            <!-- 定义加载字典拦截器,interceptor在spring中配置 -->
            <interceptor name="dictData" class="initDictInterceptor" />
            <!-- 定义一个包含加载字典的拦截器栈 -->
            <interceptor-stack name="mydefault">
                <interceptor-ref name="defaultStack" />
                <interceptor-ref name="dictData" />
            </interceptor-stack>
        </interceptors>
        <!-- 定义默认拦截器 -->
        <default-interceptor-ref name="mydefault" />
        ...................     
   </package>

```

初次调用时候，字典被加载。![](http://img.tongji.cn.yahoo.com/1083199/ystat.gif)