SimpleMappingExceptionResolver і модель (ModelAndView)

травня
09
2012

Зміст

Як вже було сказано раніше, головним недоліком використання SimpleMappingExceptionResolver при вилові винятків - це відсутність можливості додати дані в модель. У цій статті розглянемо спосіб обійти це обмеження, створивши клас, успадкований від SimpleMappingExceptionResolver.

Отже, для початку нам знадобиться клас CustomExceptionResolver. Зверніть увагу, що він успадкований від SimpleMappingExceptionResolver:


package com.seostella.spring.exception.resolver;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

public class CustomExceptionResolver extends SimpleMappingExceptionResolver {

	@Override
	protected ModelAndView getModelAndView(String viewName, Exception ex) {
		return getCustomModelAndView(viewName, ex, null);
	}
	
	@Override
	protected ModelAndView getModelAndView(String viewName, Exception ex,
			HttpServletRequest request) {
		return getCustomModelAndView(viewName, ex, request);
	}
	
	private ModelAndView getCustomModelAndView(String viewName, Exception ex,
			HttpServletRequest request){
		ModelAndView mv = super.getModelAndView(viewName, ex);
		
		mv.addObject("funnyMessage", "view: " + viewName 
				+ " exceptionMessage: " + ex.getMessage() 
				+ " queryString: " + request.getQueryString() );
		
		return mv;
	}
}

Як видно з прикладу, є можливість перевантажити два методи для роботи з моделлю: один з об'єктом HttpServletRequest, а другий - без нього. Також в класі SimpleMappingExceptionResolver є ще кілька корисних методів. Отримати детальну інформацію по ним Ви можете скориставшись наступним посиланням - SimpleMappingExceptionResolver API

Тепер додамо в конфігурацію контексту сервлетe ще один обробник виключень - клас CustomExceptionResolver:


<beans:bean
	class="com.seostella.spring.exception.resolver.CustomExceptionResolver">
	<beans:property name="exceptionMappings">
		<beans:map>
			<beans:entry key="com.seostella.spring.exception.FunnyException" value="/exception/funnyException" />
		</beans:map>
	</beans:property>
</beans:bean>

Врахуйте, що цей CustomExceptionResolver потрібно розташувати до resolver'а, який обробляє помилки за замовчуванням, інакше останній їх буде перехоплювати.

Весь файл конфігурації контексту сервлета виглядає так:

servlet-context.xml

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

	<!-- DispatcherServlet Context: defines this servlet's request-processing 
		infrastructure -->

	<!-- Enables the Spring MVC @Controller programming model -->
	<annotation-driven />

	<!-- Handles HTTP GET requests for /resources/** by efficiently serving 
		up static resources in the ${webappRoot}/resources directory -->
	<resources mapping="/resources/**" location="/resources/" />

	<!-- Resolves views selected for rendering by @Controllers to .jsp resources 
		in the /WEB-INF/views directory -->
	<beans:bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/WEB-INF/views/" />
		<beans:property name="suffix" value=".jsp" />
	</beans:bean>

	<context:component-scan base-package="com.seostella.spring" />

	<beans:bean
		class="com.seostella.spring.exception.resolver.CustomExceptionResolver">
		<beans:property name="exceptionMappings">
			<beans:map>
				<beans:entry key="com.seostella.spring.exception.FunnyException" value="/exception/funnyException" />
			</beans:map>
		</beans:property>
	</beans:bean>

	<beans:bean
		class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
		<beans:property name="exceptionMappings">
			<beans:map>
				<beans:entry key="com.seostella.spring.exception.CustomException" value="/exception/customException" />
				<beans:entry key="com.seostella.spring.exception.SecondCustomException" value="/exception/secondCustomException" />
			</beans:map>
		</beans:property>
		<beans:property name="defaultErrorView" value="/exception/defaultException" />
	</beans:bean>
	
</beans:beans>

Клас FunnyException виглядає наступним чином:


package com.seostella.spring.exception;

@SuppressWarnings("serial")
public class FunnyException extends Exception {

	public FunnyException(String message) {
		super(message);
	}

}

На цій ноті закінчимо роботу з обробкою виключень. В наступній частині розглядається обробка HTTP-помилок в Spring MVC і буде наведено код проекту, в якому також використовується CustomExceptionResolver.

< SimpleMappingExceptionResolver в Spring і обробка виключень

Напишіть перше повідомлення!

Ви повинні увійти під своїм аккаунтом щоб залишати коментарі