/* 是拦截所有的文件夹,不包含子文件夹
/** 是拦截所有的文件夹及里面的子文件夹
package com.gyt.screen.filter; import com.gyt.screen.domain.Admin; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class AdminInterceptor implements HandlerInterceptor { /** * 在请求处理之前进行调用(Controller方法调用之前) */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { // System.out.println("执行了TestInterceptor的preHandle方法"+request.getRequestURI()); //if (request.getRequestURI().contains("favicon.ico")) { // return true; // //拦截代码...... // } try { //统一拦截(查询当前session是否存在user)(这里user会在每次登陆成功后,写入session) Admin user=(Admin)request.getSession().getAttribute("user"); if(user!=null){ return true; } response.sendRedirect(request.getContextPath()+"/login"); } catch (IOException e) { e.printStackTrace(); } return false;//如果设置为false时,被请求时,拦截器执行到此处将不会继续操作 //如果设置为true时,请求将会继续执行后面的操作 } /** * 请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后) */ @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) { System.out.println("执行了TestInterceptor的postHandle方法"); } /** * 在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行(主要是用于进行资源清理工作) */ @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { System.out.println("执行了TestInterceptor的afterCompletion方法"); } }
2.创建过滤器配置类
package com.gyt.screen.config; import com.gyt.screen.filter.AdminInterceptor; import org.springframework.context.annotation.Bean; 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.WebMvcConfigurationSupport; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class LoginConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { // 注册拦截器 AdminInterceptor loginInterceptor = new AdminInterceptor(); InterceptorRegistration loginRegistry = registry.addInterceptor(loginInterceptor); // 拦截路径 loginRegistry.addPathPatterns("/**");//.excludePathPatterns("/view/toLogin","/login","/view/toReg","/loginout"); // 排除路径 loginRegistry.excludePathPatterns("/login"); loginRegistry.excludePathPatterns("/doLogin"); loginRegistry.excludePathPatterns("/loginout"); loginRegistry.excludePathPatterns("/static/**");//此处是新建webapp下静态资源的路径(与默认resources下的static的静态资源路径一样)
} }