博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
SpringMVC学习笔记六:使用Formatter解析或格式化数据
阅读量:2197 次
发布时间:2019-05-02

本文共 1485 字,大约阅读时间需要 4 分钟。

转载请注明原文地址: 

 

    Converter可以将一种类型转换成另一种类型,是任意Object之间的类型转换。

    Formatter则只能进行String与任意Object对象的转换,它提供 解析 与 格式化 两种功能。

    其中:解析是将String类型字符串转换为任意Object对象,格式化是将任意Object对象转换为字符串进行格式化显示。

     使用Formatter

    1: 实现Formatter<T>接口定义一个类,T为要解析得到或进行格式化的数据类型。

    在类中实现两个方法:String print(T t,Locale locale)和 T parse(String sourse,Locale locale),前者把T类型对象解析为字符串形式返回,后者由字符串解析得到T类型对象。

public class DateFormatter implements Formatter
{ private String datePattern; private SimpleDateFormat dateFormat; public DateFormatter(String datePattern) { this.dateFormat = dateFormat; dateFormat = new SimpleDateFormat(datePattern); dateFormat.setLenient(false); } public Date parse(String s, Locale locale) throws ParseException { try { SimpleDateFormat dateFormat = new SimpleDateFormat(datePattern); dateFormat.setLenient(false); return dateFormat.parse(s); } catch (ParseException e) { throw new IllegalArgumentException("invalid date format. Please use this pattern\"" + datePattern + "\""); } } public String print(Date date, Locale locale) { return dateFormat.format(date); }}

 

    2:在SpringMVC配置文件中配置自定义格式转换器

//注册
//在FormattingConversionServiceFactoryBean中,formatters是一个set变量
//实现类的路径
//注入构造参数,指定格式
//装配

 

转载于:https://www.cnblogs.com/ygj0930/p/6832903.html

你可能感兴趣的文章
【LEETCODE】118-Pascal's Triangle
查看>>
【LEETCODE】119-Pascal's Triangle II
查看>>
【LEETCODE】88-Merge Sorted Array
查看>>
【LEETCODE】19-Remove Nth Node From End of List
查看>>
【LEETCODE】125-Valid Palindrome
查看>>
【LEETCODE】28-Implement strStr()
查看>>
【LEETCODE】6-ZigZag Conversion
查看>>
【LEETCODE】8-String to Integer (atoi)
查看>>
【LEETCODE】14-Longest Common Prefix
查看>>
【LEETCODE】38-Count and Say
查看>>
【LEETCODE】278-First Bad Version
查看>>
【LEETCODE】303-Range Sum Query - Immutable
查看>>
【LEETCODE】21-Merge Two Sorted Lists
查看>>
【LEETCODE】231-Power of Two
查看>>
【LEETCODE】172-Factorial Trailing Zeroes
查看>>
【LEETCODE】112-Path Sum
查看>>
【LEETCODE】9-Palindrome Number
查看>>
【极客学院】-python学习笔记-Python快速入门(面向对象-引入外部文件-Web2Py创建网站)
查看>>
【LEETCODE】190-Reverse Bits
查看>>
【LEETCODE】67-Add Binary
查看>>