一.spring中@InitBinder和WebBindingInitializer的使用

spring中@InitBinder和WebBindingInitializer的使用

前言:

SpringMVC注解@initbinder解决类型转换问题

         在使用SpringMVC的时候,经常会遇到表单中的日期字符串和JavaBean的Date类型的转换,而SpringMVC默认不支持这个格式的转换,所以需要手动配置,自定义数据的绑定才能解决这个问题。在需要日期转换的Controller中使用SpringMVC的注解@initbinder和Spring自带的WebDateBinder类来操作。
WebDataBinder是用来绑定请求参数到指定的属性编辑器.由于前台传到controller里的值是String类型的,当往Model里Set这个值的时候,如果set的这个属性是个对象,Spring就会去找到对应的editor进行转换,然后再SET进去。

详解

@InitBinder用于在@Controller中标注于方法,表示为当前控制器注册一个属性编辑器或者其他,只对当前的Controller有效
WebBindingInitializer:实现WebBindingInitializer,重写initBinder注册的属性编辑器是全局的属性编辑器,对所有的Controller都有效
自定义springMVC的属性编辑器主要有两种方式,一种是使用@InitBinder标签在运行期注册一个属性编辑器,这种编辑器只在当前Controller里面有效;还有一种是实现自己的 WebBindingInitializer,然后定义一个AnnotationMethodHandlerAdapter的bean,在此bean里面进行注册 ,这种属性编辑器是全局的。

第一种方式:

package mytest;
import java.beans.PropertyEditorSupport;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletResponse;  
@RequestMapping("/globalController")
@Controller
public class GlobalController {
@RequestMapping("test/{date}")  
    public void test(@PathVariable Date date, HttpServletResponse response) throws IOException{
        response.getWriter().write(date.toString());  
    }  
    @InitBinder//必须有一个参数WebDataBinder  
    public void initBinder(WebDataBinder binder) {  
        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), false));  
                binder.registerCustomEditor(int.class, new PropertyEditorSupport() {  
            @Override  
            public String getAsText() {  
                // TODO Auto-generated method stub  
                return getValue().toString();  
            }  
              @Override  
            public void setAsText(String text) throws IllegalArgumentException {  
                // TODO Auto-generated method stub  
                System.out.println(text + "...........................................");  
                setValue(Integer.parseInt(text));  
            }  
              
        });  

或者:
 @InitBinder  
    public void initBinder(WebDataBinder binder) {  
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");  
        dateFormat.setLenient(false);  
df.setLeninet(false)这个方法有以下功能:
①这个的功能是不把1996-13-3转换为1997-1-3。
②这样输入1996-2-31这样的数据也会验证出来错误的。

        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));  
//true:允许输入空值,false:不能为空值

    }

    }  
}

配置文件:

<!-- 解析器注册 -->
<bean
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="stringHttpMessageConverter" />
</list>
</property>
</bean>
<!-- String类型解析器,允许直接返回String类型的消息 -->
<bean id="stringHttpMessageConverter"
class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
<!-- 换种写法 -->
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8" />
</bean>
</mvc:message-converters>
</mvc:annotation-driven>

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

请求:

http://localhost:8080/mytest/globalController/test/2013-12-23

返回:

Mon Dec 23 00:00:00 CST 2013
 
 

第二种方式:

package mytest;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.support.WebBindingInitializer;
import org.springframework.web.context.request.WebRequest;
public class MyWebBindingInitializer implements WebBindingInitializer {   
    @Override  
    public void initBinder(WebDataBinder binder, WebRequest request) {  
        // TODO Auto-generated method stub  
        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), false));  
    }  
  
}  
在springMVC的配置文件里面定义一个AnnotationMethodHandlerAdapter,并设置其WebBindingInitializer属性为我们自己定义的WebBindingInitializer对象
	<bean
		class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
		<property name="messageConverters">
			<list>
				<ref bean="stringHttpMessageConverter" />
			</list>
		</property>
		<property name="cacheSeconds" value="0" />
		<property name="webBindingInitializer">
			<bean class="mytest.MyWebBindingInitializer" />
		</property>
	</bean>
	<bean id="stringHttpMessageConverter"
		class="org.springframework.http.converter.StringHttpMessageConverter">
		<property name="supportedMediaTypes">
			<list>
				<value>text/html;charset=UTF-8</value>
			</list>
		</property>
	</bean>
	<mvc:annotation-driven />
 第二种方式经过上面两步就可以定义一个全局的属性编辑器了。
注意:当使用了<mvc:annotation-driven />的时候,它 会自动注册DefaultAnnotationHandlerMapping与AnnotationMethodHandlerAdapter 两个bean。这时候第二种方式指定的全局属性编辑器就不会起作用了,解决办法就是手动的添加上述bean,并把它们加在<mvc:annotation-driven/>的前面。如果不生效,则将手动注册AnnotationMethodHandlerAdapter改为手动注册RequestMappingHandlerAdapter。
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值