SpringBoot整合拦截器

MayMatrix 2017-08-16

SpringMVC配置

package com.bjdjjs.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import com.bjdjjs.interceptor.LogInterceptor;

/**
 * 拦截器配置
 * @author Administrator
 *
 */
@Configuration
public class MyWebMvcConfigurer 
        extends WebMvcConfigurerAdapter {
 
    @Bean
    public LogInterceptor getMyInterceptor(){
        return new LogInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(getMyInterceptor());
        super.addInterceptors(registry);
    }
}

@bean为了注册拦截器,不然调用不了Service

以下为日志管理拦截器

package com.bjdjjs.interceptor;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

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

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.bjdjjs.domain.AuditLog;
import com.bjdjjs.domain.User;
import com.bjdjjs.enumeration.DelStatusEnum;
import com.bjdjjs.service.log.LogService;


/**
 * 日志拦截器
 * @author Administrator
 *
 */
public class LogInterceptor implements HandlerInterceptor {

	protected static Logger logger = Logger.getLogger(LogInterceptor.class);
	
	@Autowired
	private LogService logService;
	
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		if (handler instanceof HandlerMethod) {
			HandlerMethod handlerMethod = (HandlerMethod) handler;
			Method method = handlerMethod.getMethod();
			AuditLog annotation = method.getAnnotation(AuditLog.class);

			// 判断请求是否配置为进行日志记录
			if (annotation != null) {
				Map<String, Object> param = new HashMap<String, Object>();
				//获取用户信息
				User user = (User) SecurityUtils.getSubject().getPrincipal();
		    	int userId = user.getId();
				String userName = user.getName();

				//获取操作对象
				String operObj = annotation.operObj();
				//获取操作类型
				String operType = annotation.operType();
				
				//获取用户ip地址
				String ipAdress = getRequestIp(request);
				
				//获取操作描述
				String operDesc = annotation.operDesc();
				if(!StringUtils.isBlank(operDesc))
					param.put("operDesc", operDesc);
				
				//状态码
				param.put("status", response.getStatus());
				
				param.put("userId", userId);
				param.put("userName", userName);
				param.put("ipAdress", ipAdress);
				param.put("operObj", operObj);
				param.put("operType", operType);
				
				param.put("isDel", DelStatusEnum.DEFAULT.getValue());
				
				logService.save(param);
				
			}	
		}
	}
	
	/***
     * 获取当前登录用户的IP地址
     * @param request
     */
    private String  getRequestIp(HttpServletRequest request ){
    
    	String ip = request.getHeader("X-Real-IP");
    	if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
    		System.out.println("*******************************X-Real-IP"+ip+"*******************************");
			return ip;
		}
    	
    	ip = request.getHeader("X-Forwarded-For");
		if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
			// 多次反向代理后会有多个IP值,第一个为真实IP。
			System.out.println("*******************************X-Forwarded-For"+ip+"*******************************");
			int index = ip.indexOf(',');
			if (index != -1) {
				return ip.substring(0, index);
			} else {
				return ip;
			}
		} else {
			System.out.println("*******************************getRemoteAddr"+request.getRemoteAddr()+"*******************************");
			return request.getRemoteAddr();
		}
    }
}

其中AuditLog为自定义注解

package com.bjdjjs.domain;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AuditLog {

	/**
	 * 操作对象
	 * 
	 * @return
	 */
	String operObj();

	/**
	 * 操作类型
	 * 
	 * @return
	 */
	String operType();

	/**
	 * 操作描述
	 * 
	 * @return
	 */
	String operDesc() default "";

}

将注解添加到必要的方法上,传入必要的参数即可

相关推荐