Spring MVC学习之五:总结(七)
inder 注解实现。
下面先看向整个 Spring MVC 框架注册的自定义编辑器:
清单 13. 注册框架级的自定义属性编辑器
>bean class="org.springframework.web.servlet.mvc.annotation.
AnnotationMethodHandlerAdapter"<
>property name="webBindingInitializer"<
>bean class="com.baobaotao.web.MyBindingInitializer"/<
>/property<
>/bean<
MyBindingInitializer 实现了 WebBindingInitializer 接口,在接口方法中通过 binder 注册多个自定义的属性编辑器,其代码如下所示:
清单 14.自定义属性编辑器
package org.springframework.samples.petclinic.web;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.samples.petclinic.Clinic;
import org.springframework.samples.petclinic.PetType;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.support.WebBindingInitializer;
import org.springframework.web.context.request.WebRequest;
public class MyBindingInitializer implements WebBindingInitializer {
public void initBinder(WebDataBinder binder, WebRequest request) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class,
new CustomDateEditor(dateFormat, false));
binder.registerCustomEditor(String.class, new StringTrimmerEditor(false));
}
}
如果希望某个属性编辑器仅作用于特定的 Controller,可以在 Controller 中定义一个标注 @InitBinder 注解的方法,可以在该方法中向 Controller 了注册若干个属性编辑器,来看下面的代码:
清单 15. 注册 Controller 级的自定义属性编辑器
@Controller
public class MyFormController {
@InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
}
…
}
注意被标注 @InitBinder 注解的方法必须拥有一个 WebDataBinder 类型的入参,以便 Spring MVC 框架将注册属性编辑器的 WebDataBinder 对象传递进来。
回页首
如何准备数据
在编写 Controller 时,常常需要在真正进入请求处理方法前准备一些数据,以便请求处理或视图渲染时使用。在传统的 SimpleFormController 里,是通过复写其 referenceData() 方法来准备引用数据的。在 Spring 2.5 时,可以将任何一个拥有返回值的方法标注上 @ModelAttribute,使其返回值将会进入到模型对象的属性列表中。来看下面的例子:
清单 16. 定义为处理请求准备数据的方法
package com.baobaotao.web;
import com.baobaotao.service.BbtForumService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
@Controller
@RequestMapping("/bbtForum.do")
public class BbtForumController {
@Autowired
private BbtForumService bbtForumService;
@Mode