使用Formatter格式化数据

 代码:

registerForm.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>




测试Formatter接口


注册页面


success.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>




测试Formatter


登录名:${requestScope.user.loginname }
生日:

User.java

package com.bean;

import java.io.Serializable;
import java.util.Date;

// 域对象,实现序列化接口
public class User implements Serializable{
	
	private String loginname;
	private Date birthday;

	public User() {
		super();
		// TODO Auto-generated constructor stub
	}

	public String getLoginname() {
		return loginname;
	}

	public void setLoginname(String loginname) {
		this.loginname = loginname;
	}

	public Date getBirthday() {
		return birthday;
	}

	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}

	@Override
	public String toString() {
		return "User [loginname=" + loginname + ", birthday=" + birthday + "]";
	}
}

DateFormatter.java

package com.formatter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import org.springframework.format.Formatter;

public class DateFormatter implements Formatter {
	// 日期类型模板:如yyyy-MM-dd
	private String datePattern;
	// 日期格式化对象
	private SimpleDateFormat dateFormat;
	// 构造器,通过依赖注入的日期类型创建日期格式化对象
	public DateFormatter(String datePattern) {
		this.datePattern = datePattern;
		this.dateFormat = new SimpleDateFormat(datePattern);
	}

	// 显示Formatter的T类型对象
	public String print(Date date,Locale locale){
		return dateFormat.format(date);
	}
	
	// 解析文本字符串返回一个Formatter的T类型对象。
	public Date parse(String source, Locale locale) throws ParseException {
		try {
			return dateFormat.parse(source);
		} catch (Exception e) {
			throw new IllegalArgumentException();
		}
		
	}

}

UserController.java

package com.control;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.bean.User;

@Controller
public class UserController{
	private static final Log logger = LogFactory.getLog(UserController.class);
	 
	@RequestMapping(value="/{formName}")
	 public String loginForm(@PathVariable String formName){
		// 动态跳转页面
		return formName;
	} 
	 @RequestMapping(value="/register",method=RequestMethod.POST)
	 public String register(@ModelAttribute User user, Model model) {
		 logger.info(user);
		 model.addAttribute("user", user);
	     return "success";
	 }
}

截图:

使用Formatter格式化数据_第1张图片

使用Formatter格式化数据_第2张图片


效果与ConversionService转换数据差不多。

你可能感兴趣的:(Spring,MVC,框架学习笔记)