SpringMVC 自定义全局PropertyEditor

<mvc:annotation-driven></mvc:annotation-driven>注入了@Controller与@RequestMapping需要的注解类

    <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>

    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
 

当需要自定义全局属性转换器(JodaTime)属性转换器,可用注解实现。但是实际的项目管理中,使用注解开发,管理不好对于后期维护可是大坑啊,所以个人觉得还是使用配置文件进行开发更利于项目的维护。

1、首先,在Spring最新版本(4.1.6.RELEASE)版本中上述的两个注解类已经不推荐使用了,取而代之的是

org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping

所以不适用<mvc:annotation-driven>而是自己来维护

2、配置文件如下

<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="messageConverters">
			<list>
				<ref bean="mappingJacksonHttpMessageConverter" />
			</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>


3、配置文件中webBindingInitializer我们可以注入全局的PropertyEditor,详细代码:

package com.cml.mvc.base;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.joda.time.DateTime;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.support.WebBindingInitializer;
import org.springframework.web.context.request.WebRequest;

import com.cml.mvc.property.editor.JodaTimePropertyEditor;

public class BaseWebBindingInital implements WebBindingInitializer {
	private static final Log LOG = LogFactory
			.getLog(BaseWebBindingInital.class);
	
	private String timeFormatter;

	@Override
	public void initBinder(WebDataBinder binder, WebRequest request) {
		binder.registerCustomEditor(DateTime.class, new JodaTimePropertyEditor(
				timeFormatter));
		LOG.debug("BaseWebBindingInital->initBinder=====>sessionId:"
				+ Thread.currentThread().getId());
	}

	public String getTimeFormatter() {
		return timeFormatter;
	}

	public void setTimeFormatter(String timeFormatter) {
		this.timeFormatter = timeFormatter;
	}

}


4、JodaTimePropertyEditor是自定义的JodaTime的PropertyEditor

package com.cml.mvc.property.editor;

import java.beans.PropertyEditorSupport;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.util.StringUtils;

/**
 * jodaTime日期格式转换
 * 
 
 *         2015年4月22日
 */
public class JodaTimePropertyEditor extends PropertyEditorSupport {

	private static final Log LOG = LogFactory
			.getLog(JodaTimePropertyEditor.class);

	private String formatter = "yyyyMMdd HHmmss";
	private DateTimeFormatter format;

	public JodaTimePropertyEditor(String formatter) {
		if (null != formatter) {
			this.formatter = formatter;
		}
		format = DateTimeFormat.forPattern(formatter);
	}

	@Override
	public String getAsText() {

		LOG.debug("===>getAsText:" + getValue());

		Object obj = getValue();
		if (null != obj) {
			return ((DateTime) obj).toString(formatter);
		}

		return "";
	}

	@Override
	public void setAsText(String text) throws IllegalArgumentException {

		LOG.debug("datetime setAsText:" + text);

		if (StringUtils.isEmpty(text)) {
			setValue(null);
		} else {

			try {
				setValue(format.parseDateTime(text));
			} catch (Exception e) {
				LOG.debug("format datetime error:" + e.getMessage() + ",value:"
						+ text);
			}

		}

	}

	public String getFormatter() {
		return formatter;
	}

	public void setFormatter(String formatter) {
		this.formatter = formatter;
	}

}






郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。