SpringBoot中的拦截器是常用的技能,接下来将参照一个小小的demo讲解SpringBoot中拦截器的配置和使用.
1、SpringBoot中拦截器的使用场景.
日志、登陆验证、权限等都会用到拦截器.
2、demo源码.
在SpringBoot中使用拦截器非常的简单,相关的依赖SpringBoot已经自动为我们导入了,因此不必进行额外的导入,相关的参考代码如下:
package com.spring.boot.gp4zj.webconfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
/**
* 添加了一个拦截器,用于登陆验证和数据加密;
*
* @author:JunZhou
* @Company:LongZheng
* @Email:1769676159@qq.com
* @2018年1月19日@下午2:24:42
*/
public class SessionInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
// 登录不做拦截
if (request.getRequestURI().equals("/mongo/attencedetail/selectAll")
|| request.getRequestURI().equals("/user/login_view")) {
System.out.println("You get a http request");
}
return true;
}
/**
* 该方法将在Controller执行之后,返回视图之前执行,modelAndView表示请求Controller处理之后返回的Model和View对象,所以可以在
* 这个方法中修改modelAndView的属性,从而达到改变返回的模型和视图的效果。
*/
@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 {
}
public String getRemortIP(HttpServletRequest request) {
if (request.getHeader("x-forwarded-for") == null) {
return request.getRemoteAddr();
}
return request.getHeader("x-forwarded-for");
}
}
3、参考文章