SpringMVC 3学習(八)--グローバルな例外処理

3190 ワード

SpringMVCのプロファイルでは、次の操作を行います.
<bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    <property name="defaultErrorView">
	    <value>/error</value><!--            exceptionMappings               error   -->
    </property>
    <property name="defaultStatusCode" value="404"/><!--            HttpServletResponse    ,   404-->
    <property name="statusCodes"><!--                     -->
	    <props>
	        <!--      NumberFormatException     number,             number   HttpServletResponse     500 -->
	        <prop key="number">500</prop>
	        <prop key="null">503</prop>
	    </props>
    </property>
    <property name="exceptionMappings">
  	    <props>
	        <prop key="NumberFormatException">number</prop><!--      NumberFormatException        number   -->
	        <prop key="NullPointerException">null</prop>
	    </props>
    </property>
</bean> 

ここで主なクラスはSimpleMappingExceptionResolverクラスと彼の親クラスAbstractHandlerExceptionResolverクラスです.
HandlerExceptionResolverインタフェースを実装し、独自の例外ハンドラを書くこともできます.
SimpleMappingExceptionResolverでは、異なるjspページ(exceptionMappingsプロパティの構成)に異なる例外をマッピングできます.
また、すべての例外に対してデフォルトの例外プロンプトページを指定することもできます(defaultErrorViewプロパティの構成によって).
放出された例外がexceptionMappingsに対応するマッピングがない場合、Springはこのデフォルト構成で例外情報を表示します.
Login.JAvaテストクラス
import java.io.File;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class Login {
	@RequestMapping("/null")
	public void testNullPointerException() {
	     File file = null;
	     //      ,     SpringMVC      null  
	     System.out.println(file.getName());
	}

	@RequestMapping("/number")
	public void testNumberFormatException() {
	     // NumberFormatException,     SpringMVC      number  
	     Integer.parseInt("abc");
	}

	@RequestMapping("/default")
	public void testDefaultException() {
		if (1 == 1)
		  //         SpringMVC          ,         exception  
		  throw new RuntimeException("Error!");
	}
}

エラーのjspページが表示されます(error.jspが例です)
<body>
    <%
        Exception e = (Exception)request.getAttribute("exception");
        out.print(e.getMessage());
    %>
</body>

テストURL:http://localhost:8080/spring_exception/null
            http://localhost:8080/spring_exception/number
            http://localhost:8080/spring_exception/defaultプロジェクトソースダウンロード:http://download.csdn.net/detail/itmyhome/7382465