springmvc的初始化参数绑定
生活随笔
收集整理的這篇文章主要介紹了
springmvc的初始化参数绑定
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?一、springmvc的初始化參數綁定
此種和我們之前說的類型轉換非常相似,可以看作是一種類型轉換
在初始化參數綁定時? 重要的是參數類型
-------------------單日期的綁定
?二、 配置步驟:
? 步驟一:在applicationcontext.xml中只需要配置一個包掃描器即可
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:p="http://www.springframework.org/schema/p"xmlns:mvc="http://www.springframework.org/schema/mvc"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation=" http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc.xsd "><!--讓spring掃描包下所有的類,讓標注spring注解的類生效 --><context:component-scan base-package="cn.yxj.controller"/></beans>步驟二:在處理器類中配置綁定方法? 使用@InitBinder注解
在這里首先注冊一個用戶編輯器?參數一為目標類型?? propertyEditor為屬性編輯器,此處我們選用?CustomDateEditor屬性編輯器,
參數一為想轉換的日期格式,參數二表示是否允許為空
@InitBinderpublic void databinder(WebDataBinder binder){System.out.println("11111");DateFormat df=new SimpleDateFormat("yyyy-MM-dd");binder.registerCustomEditor(Date.class,new CustomDateEditor(df, true) );}單個日期的參數綁定配置完畢
?
-------------------多日期的綁定
配置步驟:
1.屬性編輯器
此時我們需要考慮使用哪個屬性編輯器,需要定義自己的屬性編輯器
大致的配置方式如單日期相似,只需要更換屬性編輯即可
自定義的屬性編輯器,需要我們繼承PropertiesEditor,重寫里面的setAsText方法,使用setValue方法賦值
package cn.yxj.propertyEdit;import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.regex.Pattern;import org.springframework.beans.propertyeditors.PropertiesEditor;public class MyDataEdit extends PropertiesEditor{@Overridepublic void setAsText(String text) throws IllegalArgumentException {SimpleDateFormat sdf=getDateFormat(text);try {Date date = sdf.parse(text);setValue(date);} catch (ParseException e) {e.printStackTrace();}}private SimpleDateFormat getDateFormat(String text) {if(Pattern.matches("^\\d{4}-\\d{2}-\\d{2}$", text)){return new SimpleDateFormat("yyyy-MM-dd");}else if(Pattern.matches("^\\d{4}/\\d{2}/\\d{2}$", text)){return new SimpleDateFormat("yyyy/MM/dd");}else if(Pattern.matches("^\\d{4}\\d{2}\\d{2}$", text)){return new SimpleDateFormat("yyyyMMdd");}else if(Pattern.matches("^\\d{4}年\\d{2}月\\d{2}日$", text)){return new SimpleDateFormat("yyyy年MM月dd日");}return null;}}步驟二:在處理器類中使用我們自定的屬性編輯器
@InitBinderpublic void databinder(WebDataBinder binder){System.out.println("11111");DateFormat df=new SimpleDateFormat("yyyy-MM-dd");binder.registerCustomEditor(Date.class,new MyDataEdit() );}?
轉載于:https://www.cnblogs.com/yejiaojiao/p/6163647.html
總結
以上是生活随笔為你收集整理的springmvc的初始化参数绑定的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: PHP函数整理(一)
- 下一篇: 合肥滨湖欣园停车位