自定义拦截器:
1 package com.yas.interceptor; 2 3 import org.springframework.web.servlet.HandlerInterceptor; 4 import org.springframework.web.servlet.ModelAndView; 5 6 import javax.servlet.http.HttpServletRequest; 7 import javax.servlet.http.HttpServletResponse; 8 import javax.servlet.http.HttpSession; 9 10 public class MyInterceptor implements HandlerInterceptor { 11 //在handler之前执行 12 @Override 13 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { 14 // System.out.println("preHandle"); 15 HttpSession session = request.getSession(); 16 if(session.getAttribute("state")!=null){ 17 return true; 18 } 19 response.sendRedirect("/login.jsp"); 20 return false; 21 } 22 23 //在handler之后,响应之前执行 24 //改动请求中的数据 25 @Override 26 public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { 27 // System.out.println("postHandle"); 28 } 29 30 //在视图渲染完毕之后执行 31 //资源回收 32 @Override 33 public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { 34 // System.out.println("afterCompletion"); 35 } 36 }
定义Controller:
1 package com.yas.controller; 2 3 import org.springframework.stereotype.Controller; 4 import org.springframework.ui.Model; 5 import org.springframework.web.bind.annotation.RequestMapping; 6 import org.springframework.web.bind.annotation.SessionAttributes; 7 8 @Controller 9 @RequestMapping("/inter") 10 @SessionAttributes("state") 11 public class InterceptorController { 12 13 @RequestMapping("/login") 14 public String login(Model model){ 15 model.addAttribute("state","ok"); 16 return "main"; 17 } 18 19 @RequestMapping("/test1") 20 public String test1(){ 21 return "main"; 22 } 23 24 @RequestMapping("/test2") 25 public String test2(){ 26 return "main"; 27 } 28 }
在mvc.xml进行配置:
<mvc:interceptors> <mvc:interceptor> <!-- <mvc:mapping path="/inter/test1"/>--> <!-- <mvc:mapping path="/inter/test2"/>--> <mvc:mapping path="/inter/**"/> <mvc:exclude-mapping path="/inter/login"/> <bean class="com.yas.interceptor.MyInterceptor"></bean> </mvc:interceptor> </mvc:interceptors>