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%" border="1">
       <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}">修改</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>

猜你喜欢

转载自blog.csdn.net/qq_41029923/article/details/84788444