SpringMvc例外ハンドラ

簡単な紹介

  要求の処理にSpringMvc異常情報が例外ハンドラによって処理され、例外ハンドラはシステムのカスタム例外処理ロジックを実装することができます。

異常が理解します

  例外が含まコンパイル例外異常動作コンパイル時にも、例外と呼ばれる、異常な期待を異常が唯一のランタイムを実行するプロジェクトの場合に発見される、コンパイル時には、心配する必要はありません。

  なランタイムなどの例外、:nullポインタ例外、配列境界例外などの例外については、唯一の経験のプログラマーやテスター常に解決するための厳格なテストの富を通じて解決することができます。

  コンパイル時の異常:など、データベースの例外、ファイルの読み込み例外、カスタム例外のように。この例外のために、あなたがしなければならないキャッチしようとしブロックするか、スローハンドル例外にキーワードを。

例外処理のアイデア

  :システム異常は、2つのカテゴリ含む予想例外例外のRuntimeException(異常コンパイル時間)と実行時、テストおよび実行時例外を低減する他の手段、主に標準化されたコードの開発を通して起こる例外情報を捕捉することによって、例外を得るために、前者を。

  DAOシステムは、サービスは、コントローラは以下のように例外発生は、コントローラのフロントエンドにより、最終的に例外ハンドラSpringMvc例外処理までスローされるスロー。

 

 唯一のグローバルスコープの例外ハンドラ。

カスタム例外クラス

最初のステップ:CustomException.java

パッケージcom.cyb.ssm.exception。

/ **
 *カスタムコンパイル時の異常
 * 
 * @author apple
 *
 */
public class CustomException extends Exception {
    private String msg;

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public CustomException(String msg) {
        super();
        this.msg = msg;
    }
}

第二步:CustomExceptionResolver.java(重点)

package com.cyb.ssm.resolver;

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

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

import com.cyb.ssm.exception.CustomException;

public class CustomExceptionResolver implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
            Exception ex) {
        String message="";
        // 异常处理逻辑
        if (ex instanceof CustomException) {
            message = ((CustomException) ex).getMsg();
        } else {
            message="未知错误";
        }
        ModelAndView mv=new ModelAndView();
        mv.setViewName("error");
        mv.addObject("message", message);
        return mv;
    }
}

第三步:在springmvc.xml中加入bean

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!-- 处理器类的扫描 -->
    <context:component-scan
        base-package="com.cyb.ssm.controller"></context:component-scan>
    <mvc:annotation-driven conversion-service="conversionService"/>
    <!-- 显示配置视图解析器 -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    <!-- 配置自定义的转换服务 -->
    <bean id="conversionService"
        class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <!-- 自定义日期类型转换器 -->
                <bean class="com.cyb.ssm.controller.converter.DateConverter"></bean>
            </set>
        </property>
    </bean>
    <!-- 配置异常处理器 -->
    <bean class="com.cyb.ssm.resolver.CustomExceptionResolver"></bean>
</beans>

第四步:jsp错误页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>错误页面</title>
</head>
<body>
    ${message }
</body>
</html>

第五步:测试类

    @RequestMapping("queryItem")
    public ModelAndView queryItem() throws CustomException {
        //查询数据库,用静态数据模拟
        List<Item> itemList = Service.queryItemList();
        ModelAndView mvAndView = new ModelAndView();
        mvAndView.addObject("itemList", itemList);
        //设置视图(逻辑路径)
        mvAndView.setViewName("item/item-list");
        if (true) {
            throw new CustomException("我是自定义异常类");
        }
        return mvAndView;
    }

实现

 

源码 

完整代码:直接下载

おすすめ

転載: www.cnblogs.com/chenyanbin/p/12022180.html