spring mvc接收表单中的特殊类型字段

来源:互联网 发布:永航科技有限公司 知乎 编辑:程序博客网 时间:2024/06/02 01:47

controller中可以自动接收表单中的数据,但只是一些基本类型,如int,String,char等,若是date类型或其他,则会报错,类型不能转化;

若是只针对单一的controller,可以使用@initBinder注解,让请求到达controller的时候,先进行类型的转换。

示例:

1 .JavaBean(其中timeLimit为date类型)

public class {  private int id;  private String name;  private Date timeLimit;  public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}  public Date getTimeLimit() {return timeLimit;}public void setTimeLimit(Date timeLimit) {this.timeLimit = timeLimit;}}

2 Controller

@Controller@RequestMapping("user")public class UserController extends BaseController{@Resource(name="userService")private UserService userService;@RequestMapping(params="add",produces = "application/json; charset=utf-8")@ResponseBodypublic String addUser(User user,HttpServletRequest request){String result = userService.addUser(user);return result;}       /** * 时间类型转化 * @param binder */@InitBinderpublic void initBinder(WebDataBinder binder){  binder.registerCustomEditor(Date.class,"timeLimit",new DateEditor());}}

3 DateEditor类:继承PropertyEditorSupport类,重写getAsText()方法和setAsText()方法

public class DateEditor extends PropertyEditorSupport{@Overridepublic String getAsText() {Date date = (Date)getValue();if(date==null){date = new Date();}SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");return sf.format(date);}@Overridepublic void setAsText(String text) throws IllegalArgumentException {Date value = null;if(text!=null&&!text.equals("")){SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");try {value = sf.parse(text);} catch (ParseException e) {e.printStackTrace();}}setValue(value);}}


这样,就可以将表单中传入的String类型的字符串转化为Date类型注入到User中。


0 0