自定義springMVC的屬性編輯器主要有兩種方式,1種是使用@InitBinder標簽在運行期注冊1個屬性編輯器,這類編輯器只在當前Controller里面有效;還有1種是實現自己的 WebBindingInitializer,然后定義1個
AnnotationMethodHandlerAdapter的bean,在此bean里面進行注冊
,這類屬性編輯器是全局的。
第1種方式:
- import java.beans.PropertyEditorSupport;
- import java.io.IOException;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- import javax.servlet.http.HttpServletResponse;
- 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;
- @Controller
- public class GlobalController {
- @RequestMapping("test/{date}")
- public void test(@PathVariable Date date, HttpServletResponse response) throws IOException
- response.getWriter().write( date);
- }
- @InitBinder//必須有1個參數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));
- }
- });
- }
- }
這類方式這樣寫了就能夠了
第2種:
1.定義自己的WebBindingInitializer
- package com.xxx.blog.util;
- import java.util.Date;
- import java.text.SimpleDateFormat;
- 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));
- }
- }
2.在springMVC的配置文件里面定義1個AnnotationMethodHandlerAdapter,并設置其WebBindingInitializer屬性為我們自己定義的WebBindingInitializer對象
- <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
- <property name="cacheSeconds" value="0"/>
- <property name="webBindingInitializer">
- <bean class="com.xxx.blog.util.MyWebBindingInitializer"/>
- </property>
- </bean>
第2種方式經過上面兩步就能夠定義1個全局的屬性編輯器了。
注意:當使用了<mvc:annotation-driven />的時候,它 會自動注冊DefaultAnnotationHandlerMapping與AnnotationMethodHandlerAdapter 兩個bean。這時候候第2種方式指定的全局屬性編輯器就不會起作用了,解決辦法就是手動的添加上述bean,并把它們加在<mvc:annotation-driven/>的前面。