SpringMVC_Exception Handling and Interceptor_hehe.employment.over.38.3

38.4 Exception Handling in SpringMVC

38.4.1 Ideas for Exception Handling

  • There are two types of exceptions in the system: Expected exception and runtime exception RuntimeExceptionThe former obtains exception information by catching exceptions, while the latter mainly reduces the occurrence of exceptions at runtime by standardizing code development and testing.
  • The dao, service, and controller of the system are all thrown upwards through throws Exception, and finally the springmvc front-end controller is handed over to the exception handler for exception handling, as shown in the following figure:
    Insert picture description here

38.4.2 Exception Handling Code

  • 1. Custom exception class
package com.xww.exception;

/**
 * 自定义异常类
 */
public class SysException extends Exception{
    
    

    // 存储提示信息的
    private String message;

    public String getMessage() {
    
    
        return message;
    }

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

    public SysException(String message) {
    
    
        this.message = message;
    }

}

  • 2. Custom exception handler
package com.xww.exception;

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

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

/**
 * 异常处理器
 */
public class SysExceptionResolver implements HandlerExceptionResolver{
    
    

    /**
     * 处理异常业务逻辑
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @return
     */
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
    
    
        // 获取到异常对象
        SysException e = null;
        if(ex instanceof SysException){
    
    
            e = (SysException)ex;
        }else{
    
    
            e = new SysException("系统正在维护....");
        }
        // 创建ModelAndView对象
        ModelAndView mv = new ModelAndView();
        // 存入错误的提示信息
        mv.addObject("errorMsg",e.getMessage());
        mv.setViewName("error");
        return mv;
    }

}
  • 3. Configure the exception handler
 <!--配置异常处理器-->
    <bean id="sysExceptionResolver" class="com.xww.exception.SysExceptionResolver"/>

38.5 Interceptors in SpringMVC

38.5.1 The role of interceptors

  • The processor interceptor of Spring MVC is similar to the filter in Servlet development, which is used to pre-process and post-process the processor.
  • Users can define some interceptors to achieve specific functions.
  • Speaking of interceptors, I would like to mention one word to everyone-Interceptor Chain. The interceptor chain is to link the interceptors into a chain in a certain order. When accessing the intercepted method or field, the interceptors in the interceptor chain will be called in the order they were previously defined.
  • Having said that, you may have a question in your mind. Isn't this the filter we learned before? Yes, it is somewhat similar to filters, but there are also differences. Next, let's talk about their differences:
    • filterIt is part of the servlet specification and can be used by any java web project.
    • InterceptorIt is owned by the SpringMVC framework and can only be used for projects that use the SpringMVC framework.
    • filterAfter configuring /* in url-pattern, all resources to be accessed can be intercepted.
    • InterceptorIt is a controller method that only intercepts access. If the access is jsp, html, css, image or js, it will not be intercepted.
  • If we want to customize the interceptor, the requirements must be implemented: HandlerInterceptor interface

38.5.2 Getting Started with Interceptors

  • 1. Create a class, implement the HandlerInterceptor interface, and rewrite the required method
package cn.itcast.demo1;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
/**
 * 自定义拦截器1
 */
public class MyInterceptor1 implements HandlerInterceptor{
    
    
    /**
     * controller方法执行前,进行拦截的方法
     * return true放行
     * return false拦截
     * 可以使用转发或者重定向直接跳转到指定的页面。
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler)throws Exception {
    
    
        System.out.println("拦截器执行了...");
        return true;
    }
}
  • 2. Configure the interceptor class in springmvc.xml
    <!--配置拦截器-->
    <mvc:interceptors>
        <!--配置拦截器-->
        <mvc:interceptor>
            <!--要拦截的具体的方法-->
            <mvc:mapping path="/user/*"/>
            <!--不要拦截的方法
            <mvc:exclude-mapping path=""/>
            -->
            <!--配置拦截器对象-->
            <bean class="cn.itcast.interceptor.MyInterceptor1" />
        </mvc:interceptor>

        <!--配置第二个拦截器-->
        <mvc:interceptor>
            <!--要拦截的具体的方法-->
            <mvc:mapping path="/**"/>
            <!--不要拦截的方法
            <mvc:exclude-mapping path=""/>
            -->
            <!--配置拦截器对象-->
            <bean class="cn.itcast.interceptor.MyInterceptor2" />
        </mvc:interceptor>
    </mvc:interceptors>

38.5.3 Methods in the HandlerInterceptor interface

  • The preHandle method is a method that is intercepted before the controller method is executed
    • You can use request or response to jump to the specified page
    • Return true to let it go and execute the next interceptor. If there is no interceptor, execute the method in the controller.
    • Return false is not allowed, and the method in the controller will not be executed.
  • postHandle is a method that is executed after the controller method is executed, before the JSP view is executed.
    • You can use request or response to jump to the specified page
    • If the page to jump to is specified, the page jumped to by the controller method will not be displayed.
  • The postHandle method is executed after the JSP is executed
    • Request or response can no longer jump to the page

38.5.4 Configure multiple interceptors

  • Write another interceptor class
  • Configure 2 interceptors
  • springmvc.xml
    <!--配置拦截器-->
    <mvc:interceptors>
        <!--配置拦截器-->
        <mvc:interceptor>
            <!--要拦截的具体的方法-->
            <mvc:mapping path="/user/*"/>
            <!--不要拦截的方法
            <mvc:exclude-mapping path=""/>
            -->
            <!--配置拦截器对象-->
            <bean class="cn.itcast.interceptor.MyInterceptor1" />
        </mvc:interceptor>

        <!--配置第二个拦截器-->
        <mvc:interceptor>
            <!--要拦截的具体的方法-->
            <mvc:mapping path="/**"/>
            <!--不要拦截的方法
            <mvc:exclude-mapping path=""/>
            -->
            <!--配置拦截器对象-->
            <bean class="cn.itcast.interceptor.MyInterceptor2" />
        </mvc:interceptor>
    </mvc:interceptors>

Guess you like

Origin blog.csdn.net/qq_44686266/article/details/114890385