int.text SpringMVC的拦截器主要是通过实现HandlerInterceptor接口来实现,并实现接口中的三个方法,分别是boolean preHandle(HttpServletRequest request,HttpServletResponse response,Object handle)上述方法主要是在
SpringMVC的拦截器主要是通过实现HandlerInterceptor接口来实现,并实现接口中的三个方法,分别是 boolean preHandle(HttpServletRequest request,HttpServletResponse response,Object handle) 上述方法主要是在请求处理之前被调用,返回为false时表示结束后续方法都不执行,为true时会调用当前请求的controller方法。 void postHandle(HttpServletRequest request,HttpServletResponse response,Object handler,ModelAndView mv) 上述方法只能在preHandle返回为true时才能执行,该方法在控制器方法执行后执行,但是它会在视图渲染前执行。 void afterCompletion(HttpServletRequest request,HttpServletResponse response,Object handler,Exception exception) 上述方法在preHandle为true时才能执行,只要是在整个请求结束后即视图渲染结束后进行资源清理。 例子: 拦截器实现HandlderInterceptor接口 public class AuthorizationInterceptor implements HandlerInterceptor { private static final String[] IGNORE_URL={"/child/login","/childlogin"}; public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception { // TODO Auto-generated method stub System.out.println("AuthorizationInterceptor afterCompletion"); } public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception { // TODO Auto-generated method stub System.out.println("AuthorizationInterceptor postHandle"); } public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // TODO Auto-generated method stub System.out.println("AuthorizationInterceptor preHandle"); boolean flag=false; //获取servlet的路径 String path=request.getServletPath(); System.out.println(path); //路径进行比对,是否需要拦截 for(String s:IGNORE_URL){ if(path.contains(s)){ flag=true; break; } } //拦截请求操作 if(!flag){ Child child=(Child) request.getSession().getAttribute("child"); if(child==null){ System.out.println("AuthorizationInterceptor拦截请求"); request.setAttribute("message","请先登录再访问"); //../表示当前目录的前一级目录 request.getRequestDispatcher("../childlogin.jsp").forward(request, response); }else{ System.out.println("AuthorizationInterceptor放行通过"); flag=true; } } return flag; } } MVC中的配置文件进行bean的配置 注意:mapping对应的path使用/**表示拦截所有路径包括二级路径等等,如果只用/*只能拦截单级目录