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

Теперь добавим в конфигурацию контекста сервлета еще один обработчик исключений - класс 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 и обработка исключений

Напишите первое сообщение!

Вы должны войти под своим аккаунтом чтобы оставлять комментарии