定义
public class SessionInterceptor implements HandlerInterceptor
{
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
System.out.println(request.getRequestURI());
//登录不做拦截
if(request.getRequestURI().equals("/user/login") || request.getRequestURI().equals("/user/login_view"))
{
return true;
}
//验证session是否存在
Object obj = request.getSession().getAttribute("_session_user");
if(obj == null)
{
response.sendRedirect("/user/login_view");
return false;
}
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 {
}
}
注册
@Configuration
public class SessionConfiguration extends WebMvcConfigurerAdapter
{
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new SessionInterceptor()).addPathPatterns("/**");
}
}
扩展
请求日志拦截
数据结构
DROP TABLE IF EXISTS `t_logger_infos`;
CREATE TABLE `t_logger_infos` (
`ali_id` int(11) NOT NULL AUTO_INCREMENT,
`ali_client_ip` varchar(30) DEFAULT NULL COMMENT '客户端请求IP地址',
`ali_uri` varchar(100) DEFAULT NULL COMMENT '日志请求地址',
`ali_type` varchar(50) DEFAULT NULL COMMENT '终端请求方式,普通请求,ajax请求',
`ali_method` varchar(10) DEFAULT NULL COMMENT '请求方式method,post,get等',
`ali_param_data` longtext COMMENT '请求参数内容,json',
`ali_session_id` varchar(100) DEFAULT NULL COMMENT '请求接口唯一session标识',
`ali_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '请求时间',
`ali_returm_time` varchar(50) DEFAULT NULL COMMENT '接口返回时间',
`ali_return_data` longtext COMMENT '接口返回数据json',
`ali_http_status_code` varchar(10) DEFAULT NULL COMMENT '请求时httpStatusCode代码,如:200,400,404等',
`ali_time_consuming` int(8) DEFAULT '0' COMMENT '请求耗时(毫秒单位)',
PRIMARY KEY (`ali_id`)
) ENGINE=InnoDB AUTO_INCREMENT=106119 DEFAULT CHARSET=utf8 COMMENT='请求日志信息表';
数据Model
@Entity
@Table(name = "t_logger_infos")
public class LoggerEntity implements Serializable
{
//编号
@Id
@GeneratedValue
@Column(name = "ali_id")
private Long id;
//客户端请求ip
@Column(name = "ali_client_ip")
private String clientIp;
//客户端请求路径
@Column(name = "ali_uri")
private String uri;
//终端请求方式,普通请求,ajax请求
@Column(name = "ali_type")
private String type;
//请求方式method,post,get等
@Column(name = "ali_method")
private String method;
//请求参数内容,json
@Column(name = "ali_param_data")
private String paramData;
//请求接口唯一session标识
@Column(name = "ali_session_id")
private String sessionId;
//请求时间
@Column(name = "ali_time",insertable = false)
private Timestamp time;
//接口返回时间
@Column(name = "ali_returm_time")
private String returnTime;
//接口返回数据json
@Column(name = "ali_return_data")
private String returnData;
//请求时httpStatusCode代码,如:200,400,404等
@Column(name = "ali_http_status_code")
private String httpStatusCode;
//请求耗时秒单位
@Column(name = "ali_time_consuming")
private int timeConsuming;
// Get Set ......
}
对于Model增删改查省略。。。。。
日志拦截器
public class LoggerInterceptor implements HandlerInterceptor
{
//请求开始时间标识
private static final String LOGGER_SEND_TIME = "_send_time";
//请求日志实体标识
private static final String LOGGER_ENTITY = "_logger_entity";
/**
* 进入SpringMVC的Controller之前开始记录日志实体
* @param request 请求对象
* @param response 响应对象
* @param o
* @return
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
//创建日志实体
LoggerEntity logger = new LoggerEntity();
//获取请求sessionId
String sessionId = request.getRequestedSessionId();
//请求路径
String url = request.getRequestURI();
//获取请求参数信息
String paramData = JSON.toJSONString(request.getParameterMap(),
SerializerFeature.DisableCircularReferenceDetect,
SerializerFeature.WriteMapNullValue);
//设置客户端ip
logger.setClientIp(LoggerUtils.getCliectIp(request));
//设置请求方法
logger.setMethod(request.getMethod());
//设置请求类型(json|普通请求)
logger.setType(LoggerUtils.getRequestType(request));
//设置请求参数内容json字符串
logger.setParamData(paramData);
//设置请求地址
logger.setUri(url);
//设置sessionId
logger.setSessionId(sessionId);
//设置请求开始时间
request.setAttribute(LOGGER_SEND_TIME,System.currentTimeMillis());
//设置请求实体到request内,方面afterCompletion方法调用
request.setAttribute(LOGGER_ENTITY,logger);
return true;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) throws Exception {
//获取请求错误码
int status = response.getStatus();
//当前时间
long currentTime = System.currentTimeMillis();
//请求开始时间
long time = Long.valueOf(request.getAttribute(LOGGER_SEND_TIME).toString());
//获取本次请求日志实体
LoggerEntity loggerEntity = (LoggerEntity) request.getAttribute(LOGGER_ENTITY);
//设置请求时间差
loggerEntity.setTimeConsuming(Integer.valueOf((currentTime - time)+""));
//设置返回时间
loggerEntity.setReturnTime(currentTime + "");
//设置返回错误码
loggerEntity.setHttpStatusCode(status+"");
//设置返回值
loggerEntity.setReturnData(JSON.toJSONString(request.getAttribute(LoggerUtils.LOGGER_RETURN),
SerializerFeature.DisableCircularReferenceDetect,
SerializerFeature.WriteMapNullValue));
//执行将日志写入数据库
LoggerJPA loggerDAO = getDAO(LoggerJPA.class,request);
loggerDAO.save(loggerEntity);
}
/**
* 根据传入的类型获取spring管理的对应dao
* @param clazz 类型
* @param request 请求对象
* @param <T>
* @return
*/
private <T> T getDAO(Class<T> clazz,HttpServletRequest request)
{
BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
return factory.getBean(clazz);
}
}
注册日志拦截器省略。。。。