SpringMVC之拦截器的的配置和使用
拦截器与过滤器的区别:拦截器只能拦截controller的请求,过滤器可以过滤所有请求
(1)实现HandlerInterceptor接口
在执行控制器中的方法之前执行preHandle()中的方法
1 package com.eu.weh.web; 2 3 import javax.servlet.http.HttpServletRequest; 4 import javax.servlet.http.HttpServletResponse; 5 import javax.servlet.http.HttpSession; 6 7 import org.springframework.web.servlet.HandlerInterceptor; 8 import org.springframework.web.servlet.ModelAndView; 9 10 import com.eu.weh.bean.User; 11 12 /** 13 * 14 * @ClassName: LoginInterceptor 15 * @Description: 登录拦截器 16 * @author Administrator 17 * @date 2019年4月29日 上午10:31:25 18 * 19 */ 20 public class LoginInterceptor implements HandlerInterceptor { 21 22 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) 23 throws Exception { 24 25 //判断当前用户是否已经登录 26 HttpSession session = request.getSession(); 27 User loginUser = (User) session.getAttribute("dbUser"); 28 if (loginUser == null) { 29 String path = session.getServletContext().getContextPath(); 30 response.sendRedirect(path+"/login"); 31 return false; 32 }else { 33 return true; 34 } 35 } 36 37 public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, 38 ModelAndView modelAndView) throws Exception { 39 40 } 41 42 public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) 43 throws Exception { 44 45 } 46 47 }
(2)SpringMVC配置文件
1 <mvc:interceptors> 2 <mvc:interceptor> 3 <mvc:mapping path="/**" /> 4 <mvc:exclude-mapping path="/login" /> 5 <mvc:exclude-mapping path="/doAJAXlogin" /> 6 <mvc:exclude-mapping path="/bootstrap/**" /> 7 <mvc:exclude-mapping path="/css/**" /> 8 <mvc:exclude-mapping path="/fonts/**" /> 9 <mvc:exclude-mapping path="/img/**" /> 10 <mvc:exclude-mapping path="/jquery/**" /> 11 <mvc:exclude-mapping path="/layer/**" /> 12 <mvc:exclude-mapping path="/script/**" /> 13 <mvc:exclude-mapping path="/ztree/**" /> 14 <bean class="com.eu.weh.web.LoginInterceptor"></bean> 15 </mvc:interceptor> 16 </mvc:interceptors>