1. 程式人生 > >SpringMVC 攔截返回值,並自定義

SpringMVC 攔截返回值,並自定義

有關取代mvc:annotation-driven使用自定義配置請看:

1、在專案開發中,自定義全域性返回值攔截是非常實用的,就如在Struts2的攔截器中,可以根據Action的返回值自定義返回資訊,如果返回SUCCESS就統一返回一個成功的json物件,如果FAIL就返回全域性的定義資訊

2、配置xml:

<context:component-scan base-package="com.cml.mvc.*" />

	<!-- 取代mvc:annotation-driven> -->
	<bean
		class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">
	</bean>

	<!-- 採用SpringMVC自帶的JSON轉換工具,支援@ResponseBody註解 -->
	<bean
		class=" org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
		<!-- 自定義返回值攔截 -->
		<property name="responseBodyAdvice">
			<list>
				<bean class="com.cml.mvc.base.MyResponseBodyAdvice"></bean>
			</list>
		</property>
		<!-- 自定義返回值校驗 -->
		<property name="customReturnValueHandlers">
			<list>
				<bean class="com.cml.mvc.base.MyReturnValues"></bean>
			</list>
		</property>
		
		<!-- 注入全域性的propertiesEditor -->
		<property name="webBindingInitializer">
			<bean class="com.cml.mvc.base.BaseWebBindingInital">
				<property name="timeFormatter" value="yyyy-MM-dd HH:mm:ss"></property>
			</bean>
		</property>
		<property name="contentNegotiationManager" ref="contentNegotiationManager"></property>
	</bean>
	<!-- 避免IE執行AJAX時,返回JSON出現下載檔案 -->
	<bean id="mappingJacksonHttpMessageConverter"
		class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
		<property name="supportedMediaTypes">
			<list>
				<value>text/html;charset=UTF-8</value>
			</list>
		</property>
	</bean>
	<bean id="contentNegotiationManager"
		class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
		<property name="favorPathExtension" value="false" />
		<property name="favorParameter" value="true" />
		<property name="mediaTypes">
			<value>
				json=application/json
				xml=application/xml
			</value>
		</property>
	</bean>

	<!-- 取代mvc:annotation-driven> end -->

2、自定義返回值攔截類,只要實現 org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice介面即可
package com.cml.mvc.base;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import com.cml.mvc.beans.Result;

public class MyResponseBodyAdvice implements ResponseBodyAdvice<Result> {

	private static Log log = LogFactory.getLog(MyResponseBodyAdvice.class);

	@Override
	public boolean supports(MethodParameter returnType,
			Class<? extends HttpMessageConverter<?>> converterType) {
		log.debug("MyResponseBodyAdvice==>supports:" + converterType);
		log.debug("MyResponseBodyAdvice==>supports:" + returnType.getClass());
		log.debug("MyResponseBodyAdvice==>supports:"
				+ MappingJackson2HttpMessageConverter.class
						.isAssignableFrom(converterType));
		return MappingJackson2HttpMessageConverter.class
				.isAssignableFrom(converterType);
	}

	@Override
	public Result beforeBodyWrite(Result body, MethodParameter returnType,
			MediaType selectedContentType,
			Class<? extends HttpMessageConverter<?>> selectedConverterType,
			ServerHttpRequest request, ServerHttpResponse response) {

		log.debug("MyResponseBodyAdvice==>beforeBodyWrite:" + returnType + ","
				+ body);
		body.setB("我是後面設定的");
		return body;
	}

}

3、controller中只要返回自定義的Result物件,就可以攔截到轉換資訊,controller程式碼
       @RequestMapping("/times")
	@ResponseBody
	public Result getTime( Integer id) {
		
		log.debug("==========>getTime,id:" + id);
		Result result=new Result();
		result.setA(1);
		return result;
	}
action中設定了A的值為1,在頁面上返回結果:


成功實現自定義返回資訊。