天天看點

SpringMVC架構(1)之(1.3 自定義參數綁定)

一、自定義參數綁定-屬性編輯器(不推薦)

問題:① 4.1 itemsList.jsp 中增加顯示 “訂購日期” 屬性;② JSP頁面中日期拿到的是字元串,而送出到Controller中POJO類ItemsCustom 屬性對象的日期字段要變成Date類型,即字元串轉換成日期類型,無法自動轉換,編輯器在做類型轉換時出錯,此時若直接運作會報錯。

SpringMVC沒有提供對日期類型進行自動綁定,要自定義日期類型綁定;

法一:在 Controller類中使用 WebDataBinder(隻可用于一個Controller中;eg:下方 3.1 ItemsController.java中添加自定義屬性編輯器;方法中 true表示是否允許空)

//自定義屬性編輯器
	@InitBinder
	public void initBinder(WebDataBinder binder)throws Exception{
		binder.registerCustomEditor(Date.class,new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),true));
	}
           

法二: 多個 Controller共用時:WebBindingInitializer

步驟:

1.建立CustomPropertyEditor類實作接口 PropertyEditorRegister;

2.springmvc.xml配置檔案中配置屬性編輯器(① 注冊屬性編輯器即生成 bean對象; ② 自定義WebBinder; ③ 在擴充卡中引用; 此時 1.在 Controller類中使用 WebDataBinder可省略;);

二、自定義參數綁定-使用轉換器

兩個參數<資料源類型,目标類型>,将字元串轉換成日期類型,若字元串前後有空格,要去除空格;

第一步:實作Converter接口;

第二步:配置轉換器:

方式一:1.建立轉換器的 bean(conversionService);

               2.< mvc:annotation-driven/>

方式二:1.建立轉換器的 bean(conversionService);

               2.建立自定義 WebBinder的 bean(customBinder), 引用轉換器: ref=“conversionService”;

               3.擴充卡中引用自定義 WebBinder:ref=“customBinder”;

即(1.定義轉換器; 2.使用轉換器; 3.設定自定義轉換器; 4.自定義轉換器注入到擴充卡;)

(① 建立CustomDateConverter.java類實作Converter接口,接口兩個參數<資料源類型,目标類型>,将字元串轉換成日期類型,若字元串前後有空格,要去除空格:建立;)

一、自定義參數綁定-屬性編輯器(不推薦)

自定義參數綁定-屬性編輯器:法一:在 Controller類中使用 WebDataBinder

4.1 itemsList.jsp

(日期要格式化,先添加一行即引入 jstl标簽庫,再進行格式化;$ {item.price} 變為 < fmt:formatDate value="$ {item.createtime}" pattern=“yyyy-MM-dd”/>)

<%@taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
           
<body>
    <table width="100%" >
       <tr><td>商品名稱</td><td>商品價格</td><td>訂購日期</td><td>商品描述</td><td>操作</td></tr>
       <c:forEach items="${items}" var="item">
          <tr><td>${item.name}</td>
              <td>${item.price}</td>
              <td><fmt:formatDate value="${item.createtime}" pattern="yyyy-MM-dd"/></td>
              <td>${item.detail}</td>
              <td>
                <a href="${pageContext.request.contextPath}/items/editItems.action?id=${item.id}" target="_blank" rel="external nofollow" >修改</a>
              </td>
          </tr>
       </c:forEach>
    </table>
</body>
           

4.2 editItems.jsp

<%@taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
           
<body>
  <form action="${pageContext.request.contextPath}/items/editItemsSubmit.action" method="post">
  <input type="hidden" name="id" value="${item.id}"/>
  <table>
     <tr><td>商品名稱:</td>
         <td><input type="text" name="name" value="${item.name}"></td></tr>
     <tr><td>商品價格:</td>
         <td><input type="text" name="price" value="${item.price}"></td></tr>
     <tr><td>訂購日期:</td>
         <td><input type="text" name="price" value="<fmt:formatDate value='${item.createtime}' pattern="yyyy-MM-dd"/>"></td></tr>
     <tr><td>商品描述:</td>
         <td><input type="text" name="detail" value="${item.detail}"></td></tr>
     <tr><td colspan="2" align="center"><input type="submit" value="送出"/></td></tr>
  </table>
  </form>
</body>
           

3.1 ItemsController.java

@Controller
@RequestMapping("/items")
public class ItemsController{
	@Autowired
	private ItemsService itemsService;

	@RequestMapping("/editItemsSubmit")
	public String editItemsSubmit(Integer id,ItemsCustom itemsCustom) throws Exception{
		itemsService.updateItems(id,itemsCustom);
		return "forward:queryItems.action";
	}
	
	//自定義屬性編輯器
	/* @InitBinder
	public void initBinder(WebDataBinder binder)throws Exception{
		//POJO類日期類型屬性createtime
		binder.registerCustomEditor(Date.class,new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),true));
	} */
}
           

自定義參數綁定-屬性編輯器:法二:多個 Controller共用時:WebBindingInitializer

2.1 CustomPropertyEditor.java

public class CustomPropertyEditor implements PropertyEditorRegistrar{
	public void registerCustomEditors(PropertyEditorRegistry binder){
		binder.registerCustomEditor(Date.class,new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),true));
	}
}
           

2.2 springmvc.xml

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> 
	
	<!-- (開啟spring注解掃描)3.注解開發的Handler -->
	<context:component-scan base-package="com.asd"></context:component-scan>
	
	<!-- 5.1 注冊屬性編輯器--> 
	<bean id="customPropertyEditor" name="" class="com.asd.ssm.CustomPropertyEditor"></bean>
	<!-- 5.2 自定義WebBinder--> 
	<bean id="customBinder" name="" class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
        <property name="propertyEditorRegistrars">
            <list>
                <ref bean="customPropertyEditor"/>
            </list>
        </property>
    </bean>
	
	<!-- 1.注解映射器 -->  
	<bean name="" class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingInfoHandlerMapping">
	</bean>

	<!-- 2.注解擴充卡 --> 
	<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <!-- 5.3 注解擴充卡中引用--> 
        <property name="webBindingInitializer" ref="customBinder"></property>
    </bean>

	<!-- 4.視圖解析器 --> 
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/jsp"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>
</beans>
           

二、自定義參數綁定-使用轉換器

1. CustomDateConverter.java

public class CustomDateConverter implements Converter<String,Date>{
	public Date convert(String source){
		try{
			return new SimpleDateFormat("yyyy-MM-dd").parse(source);
		}catch(Exception e){
		}
		return null;
	}
}
           

2. StringTrimConverter.java

public class StringTrimConverter implements Converter<String,String>{
	public String convert(String source){
		try{
			if (source!=null) {
				source=source.trim();
				if (source.equals("")) {
					return null;
				}
			}
		}catch(Exception e){
		}
		return source;
	}
}
           

3. springmvc.xml

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> 
	
	<!-- (開啟spring注解掃描)3.注解開發的Handler -->
	<context:component-scan base-package="com.asd"></context:component-scan>
	
	<!-- 方式一 1:通過annotation-driven可以替代處理器映射和處理器擴充卡-->
	<!-- <mvc:annotation-driven></mvc:annotation-driven> -->
	<!-- 方式一 2、方式二 1:轉換器-->
	<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
		<property name="converts">
			<list>
				<bean class="com.asd.ssm.CustomDateConverter"/>
				<bean class="com.asd.ssm.StringTrimConverter"/>
			</list>
		</property>
	</bean>
	<!-- 方式二 2:自定義WebBinder--> 
	<bean id="customBinder" name="" class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
        <!-- 使用轉換器 --> 
        <property name="conversionService" ref="conversionService"></property>
    </bean>

	<!-- 注解擴充卡 --> 
	<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <!-- 方式二 3:注解擴充卡中引用--> 
        <property name="webBindingInitializer" ref="customBinder"></property>
    </bean>

</beans>
           

繼續閱讀