SpringBoot integration interceptor

SpringMVC configuration

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;

/**
 * Interceptor configuration
 * @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 In order to register the interceptor, otherwise the Service cannot be called.


The following is the log management interceptor
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;


/**
 * Log interceptor
 * @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);

			// Determine if the request is configured for logging
			if (annotation != null) {
				Map<String, Object> param = new HashMap<String, Object>();
				//get user information
				User user = (User) SecurityUtils.getSubject().getPrincipal();
		    	int userId = user.getId();
				String userName = user.getName();

				//Get the operation object
				String operObj = annotation.operObj();
				//get the operation type
				String operType = annotation.operType();
				
				//get user ip address
				String ipAdress = getRequestIp(request);
				
				//Get the operation description
				String operDesc = annotation.operDesc();
				if(!StringUtils.isBlank(operDesc))
					param.put("operDesc", operDesc);
				
				//status code
				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);
				
			}	
		}
	}
	
	/***
     * Get the IP address of the currently logged in user
     * @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)) {
			// After multiple reverse proxies, there will be multiple IP values, the first one is the real 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();
		}
    }
}


Where AuditLog is a custom annotation
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 {

	/**
	 * Operation object
	 *
	 * @return
	 */
	String operObj();

	/**
	 * Operation type
	 *
	 * @return
	 */
	String operType();

	/**
	 * Operation description
	 *
	 * @return
	 */
	String operDesc() default "";

}


Add annotations to the necessary methods and pass in the necessary parameters

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326146492&siteId=291194637