struts2 自定义拦截器实现日志保存到数据库的功能

springmvc 可以通过拦截器实现日志的保存到数据库或者文件中,struts2也可以通过自定义拦截器来实现

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
	<include file="struts-default.xml" />
	<package name="cywsjdzf" extends="struts-default">
		<interceptors>
			<interceptor name="bussinessInterceptor"
				class="com.cao.common.interceptor.BussinessLogInterceptor" />

			<interceptor-stack name="storeMessage">
				<interceptor-ref name="paramsPrepareParamsStack" />
				<interceptor-ref name="store">
					<param name="operationMode">AUTOMATIC</param>
				</interceptor-ref>
				<!-- 默认拦截器 -->
				<interceptor-ref name="defaultStack" />
				<!-- 自定义拦截器 -->
				<interceptor-ref name="bussinessInterceptor" />
			</interceptor-stack>
		</interceptors> <!--配置到全局 ,拦截所有的Action的请求,其中包含了自定义日志的拦截器 -->
		<default-interceptor-ref name="storeMessage" />
		<global-results>
			<result name="exception">/errorException.jsp</result>
		</global-results>
		<global-exception-mappings>
			<exception-mapping result="exception" exception="java.lang.Exception"></exception-mapping>
		</global-exception-mappings>
	</package>
	
	<constant name="struts.enable.DynamicMethodInvocation" value="true" />
	<constant name="struts.action.extension" value="do"></constant>
	<!-- 不需要重新启动 加载 -->
	<!-- 把它设置为开发模式,发布时要设置为false -->
	<constant name="struts.devMode" value="false" />
	<!-- 设置在class被修改时是否热加载,发布时要设置为false -->
	<constant name="struts.convention.classes.reload" value="false" />
	<constant name="struts.multipart.maxSize" value="52428800" />
	<constant name="struts.i18n.encoding" value="UTF-8"></constant>
	<!-- struts2标签 不换行 -->
	<constant name="struts.ui.theme" value="simple" />
	<constant name="struts.convention.default.parent.package"
		value="cywsjdzf" />
	<!-- 获取静态方法或变量 -->
	<constant name="struts.ognl.allowStaticMethodAccess" value="true" />
	<!-- J2EE服务器为WEBLOGIC,请求参数值设置 -->
	<constant name="struts.dispatcher.parametersWorkaround" value="true" />
</struts>  

上面是struts2 的全局struts.xml

BussinessLogInterceptor.java继承于 AbstractInterceptor

package com.cao.common.interceptor;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import cn.cao.common.util.DateUtil;

import com.cao.common.dictionary.DataDictoryService;
import com.cao.common.util.ValidUtil;
import com.cao.system.logInfo.entity.BusLog;
import com.cao.system.logInfo.entity.OperType;
import com.cao.system.logInfo.service.BussinessLogService;
import com.cao.system.logInfo.service.OperationLogService;
import com.cao.system.user.form.UserForm;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class BussinessLogInterceptor extends AbstractInterceptor {
	//日志保存Service
	private OperationLogService operationLogService ;
	private BussinessLogService bussinessLogService;

	public OperationLogService getOperationLogService() {
		return operationLogService;
	}
	
	public void setOperationLogService(OperationLogService operationLogService) {
		this.operationLogService = operationLogService;
	}



	public BussinessLogService getBussinessLogService() {
		return bussinessLogService;
	}

	public void setBussinessLogService(BussinessLogService bussinessLogService) {
		this.bussinessLogService = bussinessLogService;
	}

	public String intercept(ActionInvocation invocation) throws Exception {

		String result =  invocation.invoke();
		

		// 在拦截器触发之前,需要把Spring中的bean实例取出来,
		// 这样在最后才能把拦截到的数据通过方法保存到数据库中
		ServletContext application = ServletActionContext.getServletContext();
		WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(application);

		// 从ApplicationContext中取得定义在Spring中的bean实例
		this.bussinessLogService = (BussinessLogService) ctx.getBean("bussinessLogService");

		// 获取拦截到的action名称
		ActionContext ctxs = invocation.getInvocationContext();
		String actionName = ctxs.getName().toString();
		
		// 获取拦截到的action参数
		Map<String, String> param = new HashMap<String, String>();
		
		HttpServletRequest request = ServletActionContext.getRequest();
		UserForm userForm = (UserForm) request.getSession().getAttribute("usersession");
		
		//请求的uri
		String requestUrI = request.getRequestURI();
		String contexPath = request.getContextPath();
		//操作的路径
		String busUrl = requestUrI.replace(contexPath, "");//去掉项目路径
		//获取字典表中的操作字典
		Map<String, OperType> operTypeHashMap = DataDictoryService.getHashMapData("OperTypeHashMap");
		Map<String, OperType> operTypeHashMapAll = DataDictoryService.getHashMapData("OperTypeHashMapAll");
		//因为同一个url可能有多个 字典中的操作,是用accessparam进行区分  例如 保存和提交操作
		if(operTypeHashMap==null){
			List<OperType> operTypeList = this.bussinessLogService.getOperTypeList();
			if(operTypeList!=null && operTypeList.size()!=0){
				for (OperType operType : operTypeList) {
					//不带参数的部分字典
					operTypeHashMap.put(operType.getAccUrl(), operType);
					//带参数的完整字典
					operTypeHashMapAll.put(operType.getAccUrl()+(operType.getAccParam()==null?"":operType.getAccParam()), operType);
				}
			}
		}
		
		//字典表设置的操作id
		String opertypeStr = "";
		//操作方式
		String operObjTypeStr = "";
		String objId = "";
		//先获得所有的不带参数的日志操作字典
		OperType op = operTypeHashMap.get(busUrl);
		
		if(op!=null){
		
			//字典相同url的操作用参数进行区分
			String accessParam = op.getAccParam();
			
			if(ValidUtil.isNoEmpty(accessParam)){
				//截取参数等号前的内容
				String paramStr = accessParam.substring(0, accessParam.indexOf("="));
				
				//获得url中参数的值
				String paramValue = request.getParameter(paramStr)==null?"":request.getParameter(paramStr);
				String busUrl_ = busUrl+paramStr+"="+paramValue;
				
				//真正的日志字典实体
				OperType opAll = operTypeHashMapAll.get(busUrl_);
				opertypeStr = opAll.getId();
				operObjTypeStr = opAll.getHandleType();
			}
			
		}
		
		
		//只有在字典表中存在日志字典时才需要存入日志
		if(ValidUtil.isNoEmpty(opertypeStr)){
			
			Map parameterMap = request.getParameterMap();
			Set keySet = parameterMap.keySet();
			Iterator iterator = keySet.iterator();
			while(iterator.hasNext()){
				String keyObj = (String) iterator.next();
				//获取参数中的id值
				if("id".equals(keyObj)){
					objId = parameterMap.get("id").toString() ;
				}else if(keyObj.indexOf(".id")!=-1||keyObj.indexOf(".ID")!=-1||keyObj.indexOf(".Id")!=-1){
					objId = parameterMap.get(keyObj).toString() ;
				}
			}
			
			try {
				Object object = new Object();
				// 把拦截到的数据保存到数据库中
				
				
					
			this.bussinessLogService.saveOperationSysLog(objId, opertypeStr, opertypeStr);
				
			}
			catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
		
		return result;
	}

}
BussinessLogService.java


package com.mtm .system.logInfo.service;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cao.common.domain.HibernatePage;
import com.cao.common.pers.hibernate.HibernateDao;
import com.cao.common.util.DateUtil;
import com.cao.common.util.ValidUtil;
import com.cao.system.logInfo.entity.BusLog;
import com.cao.system.logInfo.entity.ExportLog;
import com.cao.system.logInfo.entity.OperType;
import com.cao.system.logInfo.entity.SysLog;
import com.cao.system.user.form.UserForm;


/**功能:
 * @author caoheshan
 * 
 * 2018-1-10上午10:46:32
 */
@Service
@Transactional
public class BussinessLogService {

	@Autowired
	private HibernateDao dao;
	
	/**
	 * 业务操作日志
	 */
	public void saveOperationBusLog(String operObjId, String operType, String operObjType) throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		UserForm user = (UserForm) request.getSession().getAttribute("usersession");
		
		String createTime = DateUtil.getCurrentDatetime();
		
		BusLog busLog = new BusLog();
		
		busLog.setUserId(String.valueOf(user.getUserId()));
		busLog.setUserName(user.getUserName());
		busLog.setOrgCode("010501");
		busLog.setOrgName("朝阳");
		busLog.setDeptId(user.getDeptId());
		busLog.setDeptName(user.getDeptName());
		
		busLog.setOperType(operType);
		busLog.setOperDate(createTime);
		busLog.setOperObjType(operObjType);
		
		busLog.setBusType(operType.substring(0, 4));
		
		busLog.setOperObjId(operObjId);
		
		dao.saveOrUpdate(busLog);
	}


	
	public OperType getOperTypeById(String operId) throws Exception {
		return (OperType)dao.get(OperType.class,operId);
	}
	
/**
 * 功能:获得所有的
 *@author caoheshan
 *2018-1-10下午1:58:09
 *returnType List<OperType>
 *return:
 */
	public List<OperType> getOperTypeList(){
		String sql = " select o from OperType o ";
		return dao.list(sql, new Object[]{});
	}
}



相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页