spring boot登录拦截器的实现
创建时间:2018年6月28日(星期四) 上午10:31
package
com.otc.demo.filter;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class MyInterceptorimplements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o)throws Exception {
HttpSession session = httpServletRequest.getSession();
String token = (String) session.getAttribute("token");//获取登录的session信息
if(token!=null){
return true;
}
else{
System.out.print("下面执行跳转到登录界面");
//httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/login/index"); //未登录自动跳转界面
return false;
}
}
//请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView)throws Exception {
System.out.println("postHandle被调用\n");
}
//在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行(主要是用于进行资源清理工作)
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e)throws Exception {
System.out.println("afterCompletion被调用\n");
}
}
拦截和排除
package com.otc.demo.filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebMvcConfigimplements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
//addPathPattern后跟拦截地址,excludePathPatterns后跟排除拦截地址
InterceptorRegistration interceptorRegistration = registry.addInterceptor(new MyInterceptor());
//不拦截的路径
interceptorRegistration.excludePathPatterns("/user/login");
System.out.println("执行到此");
interceptorRegistration.excludePathPatterns("/user/register");
//拦截的路径
interceptorRegistration.addPathPatterns("/**");
}
}