spingBoot 拦截器实现每次请求打印日志
拦截器配置
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
@AllArgsConstructor
public class InterceptorConfig extends WebMvcConfigurerAdapter{
private LoginInterceptor loginInterceptor;
private LoginInterceptor2 loginInterceptor2;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(loginInterceptor).addPathPatterns("/**");//日志拦截
registry.addInterceptor(loginInterceptor2).addPathPatterns("/**");//登录拦截
}
}
拦截所有请求打印日志
import com.google.gson.Gson;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
@Aspect
@Component
public class LoginInterceptor implements HandlerInterceptor {
private final static Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);
/** 以 controller 包下定义的所有请求为切入点 */
@Pointcut(value = "execution(public * com.lanyou.*.controller..*.*(..))")
public void webLog() {}
/**
* 在切点之前织入
* @param joinPoint
* @throws Throwable
*/
@Before("webLog()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
// 开始打印请求日志
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
// 打印请求相关参数
logger.info("========================================== Start ==========================================");
// 打印请求 url
logger.info("URL : {}", request.getRequestURL().toString());
// 打印 Http method
logger.info("HTTP Method : {}", request.getMethod());
// 打印调用 controller 的全路径以及执行方法
logger.info("Class Method : {}.{}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
// 打印请求的 IP
logger.info("IP : {}", request.getRemoteAddr());
// 打印请求入参
logger.info("Request Args : {}", new Gson().toJson(joinPoint.getArgs()));
}
/**
* 在切点之后织入
* @throws Throwable
*/
@After("webLog()")
public void doAfter() throws Throwable {
logger.info("=========================================== End ===========================================");
// 每个请求之间空一行
logger.info("");
}
/**
* 环绕
* @param proceedingJoinPoint
* @return
* @throws Throwable
*/
@Around("webLog()")
public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
long startTime = System.currentTimeMillis();
Object result = proceedingJoinPoint.proceed();
// 打印出参
logger.info("Response Args : {}", new Gson().toJson(result));
// 执行耗时
logger.info("Time-Consuming : {} ms", System.currentTimeMillis() - startTime);
return result;
}
}
未登录ajax超时拦截返回登录
import com.lanyou.personnel.entity.Admin;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashSet;
import java.util.Set;
@Controller
@Component
public class LoginInterceptor2 implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
String basePath = request.getContextPath();
String path = request.getRequestURI();
//是否进行登陆拦截
if(!doLoginInterceptor(path, basePath) ){
return true;
}
//如果登录了,会把用户信息存进session
HttpSession session = request.getSession();
Admin admin = (Admin) session.getAttribute("admin");
if(admin==null){
String requestType = request.getHeader("X-Requested-With");
// Ajax 请求
if(requestType!=null && "XMLHttpRequest".equals(requestType)){
//登录超时
response.setHeader("sessionstatus","timeout");
response.getWriter().print("/LoginTimeout");
return false;
} else {
response.sendRedirect(request.getContextPath()+"/login");
}
return false;
}else{
//存入session
session.setAttribute("admin",admin);
}
// log.info("用户已登录,userName:"+userInfo.getSysUser().getUserName());
return true;
}
/**
* 是否进行登陆过滤
* @param path
* @param basePath
* @return
*/
private boolean doLoginInterceptor(String path,String basePath){
path = path.substring(basePath.length());
Set<String> notLoginPaths = new HashSet<>();
//设置不进行登录拦截的路径:登录注册和验证码
notLoginPaths.add("/login");
notLoginPaths.add("/error");
notLoginPaths.add("/admin/login");
notLoginPaths.add("/LoginTimeout");//超时页面
notLoginPaths.add("/defaultKaptcha");//生产验证码
notLoginPaths.add("/js/**");
notLoginPaths.add("/layui/**");
notLoginPaths.add("/jquery-3.2.1/**");
if(notLoginPaths.contains(path)) {
return false;
}
return true;
}
}