Springmvc异常处理器及拦截器实现代码

一、异常处理器

1、实现HandlerExceptionResolver接口

package com.wuxi.exceptions;

import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class RequestExceptionResolver implements HandlerExceptionResolver {
  @Override
  public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
    ModelAndView mv = new ModelAndView();
    mv.addObject("errorMsg", e.getMessage());//错误信息
    mv.setViewName("error");//请求转发的页面
    return mv;
  }
}

2、springmvc的xml配置文件



  
  
  
  
    
    
  
  
  
    
      
        
      
    
  
  
  
  
  
  
  
    
  
  
  
  
  

二、拦截器

1、实现HandlerInterceptor接口

package com.wuxi.interceptors;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ControllerInterceptor implements HandlerInterceptor {
  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    System.out.println("controller的方法执行之前执行");
    return true;//true:放行;false:拦截
  }

  @Override
  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    System.out.println("controller的方法执行之后执行");
  }

  @Override
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    System.out.println("jsp执行之后执行");
  }
}

2、springmvc的xml配置文件



  
  
  
  
    
    
  
  
  
    
      
        
      
    
  
  
  
  
  
  
  
    
  
  
  
  
  
    
    
      
      
      
      
      
    
  
  
  

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

你可能感兴趣的:(Springmvc异常处理器及拦截器实现代码)