SpringBoot实现拦截器
下面是示例代码:
LoginInterceptor 类
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
/**
* 登陆验证拦截器
* @author zyl
* @date 2018年11月10日
*/
public class LoginInterceptor implements HandlerInterceptor {
private List<String> url = new ArrayList();
/**
* 开始进入地址请求拦截
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
HttpSession session = request.getSession();
if(session.getAttribute("user") != null){
return true;
}else{
response.sendRedirect("/getLogin"); //未登录,跳转到登录页
return false;
}
}
/**
* 处理请求完成后视图渲染之前的处理操作
*/
@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 {
}
/**
* 定义排除拦截URL
* @return
*/
public List<String> getUrl(){
url.add("/getLogin"); //登录页
url.add("/login"); //登录action URL
url.add("/ws"); //实现socket功能,暂时先不拦
url.add("/redis/*"); //实现redis功能,暂时先不拦
url.add("/hello/*/*"); //实现redis用作mysql缓存功能,暂时先不拦
url.add("/translate"); //测试页面翻译功能,暂时先不拦
url.add("/file/*"); //文件上传下载功能,暂时先不拦
//网站静态资源
url.add("/css/**");
url.add("/js/**");
url.add("/lib/**");
url.add("/fonts/**");
url.add("/images/**");
return url;
}
WebappAdapter类
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* 添加自定义拦截器
* @author zyl
* @date 2018年11月10日
*/
@Configuration
public class WebappAdapter implements WebMvcConfigurer {
/**
* 注册拦截器
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 登陆拦截器
LoginInterceptor loginInterceptor = new LoginInterceptor();
// addPathPatterns 添加拦截url, excludePathPatterns 排除拦截url
registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/**").excludePathPatterns(loginInterceptor.getUrl());
WebMvcConfigurer.super.addInterceptors(registry);
}
}