SpringMVC配置簡單的異常處理器

一、配置前端控制器及過濾器

<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">

    <!--配置中文亂碼過濾器-->
    <filter>
        <filter-name>characterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <!--指定編碼方式-->
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <!--解決請求和響應亂碼setCharacterEncoding-->
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!--配置前端控制器-->
    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <!--加載類路徑下的配置文件-->
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

二、自定義異常類

/**
 * 自定義異常類
 * @author Summerday
 */
public class MyException extends Exception{
    public MyException(String message) {
        super(message);
    }
}

三、自定義異常處理器

/**
 * 自定義異常處理器
 * @author Summerday
 */
public class MyExceptionResolver implements HandlerExceptionResolver {
    /**
     * 處理異常業務邏輯
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @return
     */
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        //獲取異常對象
        MyException e = null;
        if(ex instanceof MyException){
            e = (MyException) ex;
        }else{
            e = new MyException("系統正在維護!");
        }
        ModelAndView mv = new ModelAndView();
        mv.addObject("errorMsg",e.getMessage());
        //設置友好頁面
        mv.setViewName("error");
        return mv;
    }
}

四、配置Springmvc.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 開啓註解掃描 -->
    <context:component-scan base-package="com.smday"/>

    <!-- 視圖解析器對象 -->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    <!-- 開啓SpringMVC框架註解的支持 -->
    <mvc:annotation-driven/>
    <!-- 配置異常處理器 -->
    <bean id="myExceptionResolver" class="com.smday.exception.MyExceptionResolver"/>
    <!--放行靜態資源-->
    <mvc:default-servlet-handler/>

</beans>

五、定義Controller

/**
 * @author Summerday
 */

@Controller
@RequestMapping("/user")
public class UserController {
    @RequestMapping("/testException")
    public String testException() throws Exception{
        System.out.println("UserController.testException");
        //模擬異常
        try {
            int a = 10/0;
        } catch (Exception e) {
            e.printStackTrace();
            //拋出自定義異常信息
            throw new MyException("查詢所有用戶出現錯誤!");
        }
        return "success";
    }
}

六、定義友好提示頁面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
    <head>
        <title>Title</title>
    </head>
    <body>
        ${errorMsg}
    </body>
</html>

七、前端超鏈接測試

 <a href="${pageContext.request.contextPath}/user/testException">異常處理</a>

將會發現後端拋出異常,前端跳轉到/WEB-INF/pages/error.jsp用戶友好提示頁面。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章