首先在springmvc.xml中配置拦截器的监听
1 <mvc:interceptors> 2 <mvc:interceptor> 3 <mvc:mapping path="/**"/><!-- 拦截所有controller --> 4 <!-- <mvc:exclude-mapping path=""/> --><!-- 不拦截的controller --> 5 <bean id="loginInterceptor" class="com.llh.interceptor.LoginInterceptor"></bean> 6 </mvc:interceptor> 7 </mvc:interceptors>
然后创建一个实现了HandlerInterceptor接口的类
1 package com.llh.interceptor; 2 3 import javax.servlet.http.HttpServletRequest; 4 import javax.servlet.http.HttpServletResponse; 5 6 import org.springframework.web.servlet.HandlerInterceptor; 7 import org.springframework.web.servlet.ModelAndView; 8 9 import com.llh.entity.Student; 10 11 public class LoginInterceptor implements HandlerInterceptor{ 12 13 @Override 14 public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) 15 throws Exception { 16 // TODO Auto-generated method stub 17 18 } 19 20 @Override 21 public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) 22 throws Exception { 23 // TODO Auto-generated method stub 24 25 } 26 27 @Override 28 public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object arg2) throws Exception { 29 // TODO Auto-generated method stub 30 Student s = (Student) req.getSession().getAttribute("s"); 31 System.out.println("拦截器拦截"); 32 String context = req.getContextPath(); 33 System.out.println(context); 34 if(s==null){ 35 res.sendRedirect(context+"/login.jsp"); 36 return false; 37 } 38 return true; 39 } 40 41 }