Spring MVC例外処理の例
J2EE/サーブレットWebアプリケーションでは、エラーページをマップして次のような例外を指定できます。
web.xml
<error-page>
<error-code>404</error-code>
<location>/WEB-INF/pages/404.jsp</location>
</error-page>
<error-page>
<exception-type>com.mkyong.web.exception.CustomException</exception-type>
<location>/WEB-INF/pages/error/custom__error.jsp</location>
</error-page>
<error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/WEB-INF/pages/generic__error.jsp</location>
</error-page>
上記のコードは自己探検であるべきです。例外処理関数がサーブレットコンテナに存在する場合、例外を処理するためにSpringを使用する必要があるのはなぜですか?
一般に、2つの理由があります。
-
カスタマイズ・エラー・ページ
– サーブレット・コンテナはエラーをレンダリングします
直接ページ。 Springではモデルやデータをエラーページに埋め込むことができるので、より使いやすいエラーページをカスタマイズできます。
-
ビジネスロジック
– Springでは余分なビジネスロジックを適用できます
エラーページを表示する前に、ロギング、監査など
このチュートリアルでは、Springで例外を処理する2つの例を示します。
-
Spring 2.xでは、XMLで `SimpleMappingExceptionResolver`を使います
ファイル。
-
Spring 3.xでは、XML設定を単純化することができます.
@ ExceptionHandlerアノテーション。
1. SimpleMappingExceptionResolverの例
ディレクトリ構造を確認します。

カスタム例外。
CustomGenericException.java
package com.mkyong.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.mkyong.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.mkyong.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
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.mkyong"/>
<bean
class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
<!-- Register the bean -->
<bean class="com.mkyong.web.controller.CustomerController"/>
<bean
class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="com.mkyong.wb.exception.CustomGenericException">
error/generic__error
</prop>
<prop key="java.lang.Exception">error/exception__error</prop>
</props>
</property>
</bean>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<mvc:annotation-driven/>
</beans>
上記において、
-
CustomGenericExceptionがスローされ、ビュー名にマップされます.
“error/generic__error”
-
他の例外がスローされ、ビュー名にマップされます
“error/exception__error”。
JSPページでは、 `$ {exception}`を介して例外インスタンスにアクセスできます。
pages/error/generic__error.jsp.jsp
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<body>
<c:if test="${not empty exception.errCode}">
<h1>${exception.errCode} : System Errors</h1>
</c:if>
<c:if test="${empty exception.errCode}">
<h1>System Errors</h1>
</c:if>
<c:if test="${not empty exception.errMsg}">
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<ins class="adsbygoogle"
style="display:block; text-align:center;"
data-ad-format="fluid"
data-ad-layout="in-article"
data-ad-client="ca-pub-2836379775501347"
data-ad-slot="6894224149"></ins>
<script>
(adsbygoogle = window.adsbygoogle ||[]).push({});
</script><h2>${exception.errMsg}</h2>
</c:if>
</body>
</html>

ダウンロードする –
SpringMvc-SimpleMappingExceptionResolver-Example.zip
(13KB)
2 @ExceptionHandlerの例
Spring 3.0以降、XML設定を単純化するための新しい注釈「@ExceptionHandler」があります。以下は `@ ExceptionHandler`を使った同等のバージョンです。
CustomerController.java
package com.mkyong.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.mkyong.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
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.mkyong"/>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<mvc:annotation-driven/>
</beans>
ダウンロードする –
SpringMvc-ExceptionHandler-Example.zip
(15KB)
リファレンス
JavaDoc]。
http://docs.spring.io/spring/docs/3.0.x/javadoc-api/org/springframework/web/bind/annotation/ExceptionHandler.html
[@ExceptionHandler
JavaDoc]。リンク://spring-mvc/spring-mvc-exceptionhandler-example/[Spring MVC
@ExceptionHandlerの例]
リンク://タグ/例外ハンドラ/[例外ハンドラ]
spring mvc