Spring MVC例外処理の例

Spring MVC例外処理の例

J2EE /サーブレットWebアプリケーションでは、エラーページをマッピングして、次のように例外を指定できます。

web.xml

  
    404
    /WEB-INF/pages/404.jsp
  

  
    com.example.web.exception.CustomException
    /WEB-INF/pages/error/custom_error.jsp
  

  
    java.lang.Exception
    /WEB-INF/pages/generic_error.jsp
  

上記のコードは自己探求的なものでなければなりません。 例外処理関数がサーブレットコンテナに存在する場合、Springを使用して例外を処理する必要があるのはなぜですか?

一般的に、2つの理由があります:

  1. Customize Error Page –サーブレットコンテナはエラーページを直接レンダリングします。 Springではモデルまたはデータをエラーページに入力できるため、よりユーザーフレンドリーなエラーページをカスタマイズできます。

  2. Business logic – Springを使用すると、ログ記録、監査など、エラーページをレンダリングする前に追加のビジネスロジックを適用できます。

このチュートリアルでは、Springで例外を処理する2つの例を示します。

  1. Spring 2.xの場合、XMLファイルでSimpleMappingExceptionResolverを使用します。

  2. Spring 3.xの場合、@ExceptionHandlerアノテーションを使用してXML構成を簡略化できます。

1. SimpleMappingExceptionResolverの例

ディレクトリ構造を確認します。

spring-mvc-exception-example-directory

カスタム例外。

CustomGenericException.java

package com.example.web.exception;

public class CustomGenericException extends RuntimeException {

    private static final long serialVersionUID = 1L;

    private String errCode;
    private String errMsg;

    //getter and setter methods

    public CustomGenericException(String errCode, String errMsg) {
        this.errCode = errCode;
        this.errMsg = errMsg;
    }

}

このコントローラークラスは、カスタムエラーコードとエラーの説明を含むCustomGenericExceptionをスローするだけです。

CustomerController.java

package com.example.web.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
import com.example.web.exception.CustomGenericException;

public class CustomerController extends AbstractController {

  @Override
  protected ModelAndView handleRequestInternal(HttpServletRequest request,
    HttpServletResponse response) throws Exception {

    throw new CustomGenericException("E888", "This is custom message - ABC");

  }

}

以下のSimpleMappingExceptionResolverを確認してください。

mvc-dispatcher-servlet.xml



    

    

    
    

    
      
        
            
                error/generic_error
            
            error/exception_error
        
      
    

    
        
            /WEB-INF/pages/
        
        
            .jsp
        
    

    

上記で、

  1. CustomGenericExceptionがスローされ、ビュー名「error / generic_error」にマッピングされます。

  2. その他の例外はスローされ、ビュー名「error / exception_error」にマップされます。

JSPページでは、${exception}を介して例外インスタンスにアクセスできます。

pages/error/generic_error.jsp.jsp

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>



    
        

${exception.errCode} : System Errors

System Errors

${exception.errMsg}

spring-mvc-exception-handle-1

2. @ExceptionHandlerの例

Spring 3.0以降、XML構成を簡素化するための新しい注釈@ExceptionHandlerがあります。 以下は、@ExceptionHandlerを使用した同等のバージョンです。

CustomerController.java

package com.example.web.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.example.web.exception.CustomGenericException;

@Controller
public class CustomerController {

    @RequestMapping(value = "/customer", method = RequestMethod.GET)
    public ModelAndView getPages() throws Exception {

        throw new CustomGenericException("E888", "This is custom message X");

    }

    @ExceptionHandler(CustomGenericException.class)
    public ModelAndView handleCustomException(CustomGenericException ex) {

        ModelAndView model = new ModelAndView("error/generic_error");
        model.addObject("exception", ex);
        return model;

    }

    @ExceptionHandler(Exception.class)
    public ModelAndView handleAllException(Exception ex) {

        ModelAndView model = new ModelAndView("error/exception_error");
        return model;

    }

}

Spring XMLファイルで宣言するものはありません。

mvc-dispatcher-servlet.xml



    

    
        
            /WEB-INF/pages/
        
        
            .jsp
        
    

    

ダウンロード–SpringMvc-ExceptionHandler-Example.zip(15KB)

Note
このSpring MVC @ExceptionHandler Exampleに興味があるかもしれません