Spring MVC 使用@InitBinder转换数据

示例【Spring MVC 使用@InitBinder转换数据】

创建MyConverter

package com.converter;
import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
//自定义属性编辑器
public class MyConverter extends PropertyEditorSupport{
	// 将传如的字符串数据转换成Date类型
	@Override
	public void setAsText(String text) throws IllegalArgumentException {
		SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
		try {
			Date date=df.parse(text);
			setValue(date);
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}	
}

创建UserController

package com.controller;
import java.util.Date;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.converter.MyConverter;
import com.po.User;
@Controller
public class UserController {
	// 在控制器初始化时注册属性编辑器
		 @InitBinder
		  public void initBinder(WebDataBinder binder){
			// 注册自定义编辑器
			binder.registerCustomEditor(Date.class, new MyConverter());
		  }
	@RequestMapping("/register")
	public String register(@ModelAttribute User user,Model model) {
		System.out.println(user);
		model.addAttribute("user", user);
		return "success";
	}
}

配置springmvc-config.xml









	
	

启动Tomcat访问register.jsp

Spring MVC 使用@InitBinder转换数据_第1张图片

Spring MVC 使用@InitBinder转换数据_第2张图片

你可能感兴趣的:(spring,mvc)