1.创建拦截类实现HandlerInterceptor
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import com.pengsheng.bugcollect.po.PersonInfo; public class loginFilter implements HandlerInterceptor{ @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object obj, Exception err) throws Exception { } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object obj, ModelAndView mav) throws Exception { } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception { //获取session里的登录状态值 PersonInfo str = (PersonInfo) request.getSession().getAttribute("personInfo"); //如果登录状态不为空则返回true,返回true则会执行相应controller的方法 if (str != null) { return true; } //如果登录状态为空则重定向到登录页面,并返回false,不执行原来controller的方法 response.sendRedirect("/initLogin.action"); return false; } }
2.编写InterceptorConfigurerAdapter类继承WebMvcConfigurerAdapter
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration public class InterceptorConfigurerAdapter extends WebMvcConfigurerAdapter { /** * 该方法用于注册拦截器 * 可注册多个拦截器,多个拦截器组成一个拦截器链 */ @Override public void addInterceptors(InterceptorRegistry registry) { // addPathPatterns 添加路径 // excludePathPatterns 排除路径 registry.addInterceptor(new loginFilter()).addPathPatterns("/*.*").excludePathPatterns("/initLogin.action", "/jsp/login.jsp","/login.action"); super.addInterceptors(registry); } }