一、集成
自定义拦截器类实现HandlerInterceptor接口,再把这个拦截器类加载到全文配置中。
(1)自定义拦截器类:
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
@Component
public class ActionHandle implements HandlerInterceptor {
@Autowired
private UserActionLogService userActionLogService;
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
try {
String userId = SpringContextUtil.getCurrentUserId();
String requestUrl = httpServletRequest.getRequestURI();
Map<String, String[]> originRequestMap = httpServletRequest.getParameterMap();
Map<String,String> requestMap = new HashMap<String,String>();
for (String key : originRequestMap.keySet()) {
String[] values = originRequestMap.get(key);
requestMap.put(key,values[0]);
}
String requestParam = JSON.toJSONString(requestMap);
String requestIp = httpServletRequest.getRemoteAddr();
UserActionLog userActionLog = new UserActionLog(userId, requestUrl, requestParam, requestIp, "tableAdmin");
userActionLogService.insert(userActionLog);
} catch (Exception e) {
}
return true;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
}
(2)加载(编程式加载) :
package com.demo.config;
import com.demo.interceptor.MyInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@SpringBootConfiguration
public class MySpringMVCConfig extends WebMvcConfigurerAdapter {
@Autowired
private ActionHandle myInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(myInterceptor).addPathPatterns("/**");
}
}
也可以使用xml式加载。