SpringMVC之拦截器(interceptor)和异常处理

对DIspatcherServlet所处理的所有请求进行拦截

    


        

    
    
    

    

Controller需要过滤的内容

@Controller
public class TestController {
    @RequestMapping("/**/testInterceptor")
    public  String testInterceptor(){
        return "success";
    }
}

重写过滤器方法

@Component
public class FirsInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//    preHandle:器方法执行之前执行preHandle(),其中boolean类型返回值表示是否拦截或方向
//        返回true表示放行,及调用控制器方法,返回false表示拦截
//        即不调用控制器方法
        System.out.println("FirstInterceptor-->preHandle");
        return true;
    }

//    @Override
//    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
      控制器方法执行后执行postHandle
//    }
//
//    @Override
//    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
      处理完视图和模型数据,渲染完视图完毕后执行afterCompletion()
//    }
}

全局异常处理

1.截取编号类型跳转页面




2.截取全局异常并跳转页面

1.Controller类

@Controller
public class MyExceptionController  extends Exception{
    @RequestMapping("/e1")
    public String e1() throws SysException {

        String str=null;
        try {
            str.length();
        } catch (Exception e) {
           e.printStackTrace();
           throw new SysException("查询异常");
        }
        return "index";

    }
}

2.异常方法

package com.dltt.exception;

public class SysException extends Exception{
    //存储信息
    private String message;

    @Override
    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    /**
     * Constructs a new exception with {@code null} as its detail message.
     * The cause is not initialized, and may subsequently be initialized by a
     * call to {@link #initCause}.
     */
    public SysException(String message) {
        this.message = message;
    }
}

3.截取异常界面并跳转

//public class SysExceptionResolver implements HandlerExceptionResolver {
//    @Override
//    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
//      //获取到异常对象
//        SysException e=null;
//        if(ex instanceof SysException){
//            e=(SysException) ex;
//        }
//        //创建ModelAndVeiw对象
//        ModelAndView mv=new ModelAndView();
//        mv.addObject("errorMsg",e.getMessage());
//        mv.setViewName("error.html");
//        return mv;
//    }
//}

3.处理前后端分离异常处理问题

@ControllerAdvice

public class MyException {
    @ExceptionHandler(value = SysException.class)
    public String myException(){
        System.out.println("输出异常");
        return "error";
    }
}

你可能感兴趣的:(java,servlet,前端)