SpringMVC学习系列(7) 之 格式化显示(二)
cale();
formatModel.setMoney(currencyFormatter.print(12345.678, locale));
formatModel.setDate(dateFormatter.print(new Date(), locale));
model.addAttribute("contentModel", formatModel);
}
return "formattest";
}
}
复制代码
运行测试:
2
更改
浏览器首选语言:
3
刷新页面:
4
2.这次用DefaultFormattingConversionService来做演示,把FormatController.java改为如下内容:
复制代码
package com.demo.web.controllers;
import java.math.RoundingMode;
import java.util.Date;
import org.springframework.format.datetime.DateFormatter;
import org.springframework.format.number.CurrencyFormatter;
import org.springframework.format.support.DefaultFormattingConversionService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.demo.web.models.FormatModel;
@Controller
@RequestMapping(value = "/format")
public class FormatController {
@RequestMapping(value="/test", method = {RequestMethod.GET})
public String test(Model model) throws NoSuchFieldException, SecurityException{
if(!model.containsAttribute("contentModel")){
FormatModel formatModel=new FormatModel();
CurrencyFormatter currencyFormatter = new CurrencyFormatter();
currencyFormatter.setFractionDigits(2);//保留2位小数
currencyFormatter.setRoundingMode(RoundingMode.HALF_UP);//向(距离)最近的一边舍入,如果两边(的距离)是相等的则向上舍入(四舍五入)
DateFormatter dateFormatter=new DateFormatter();
dateFormatter.setPattern("yyyy-MM-dd HH:mm:ss");
DefaultFormattingConversionService conversionService = new DefaultFormattingConversionService();
conversionService.addFormatter(currencyFormatter);
conversionService.addFormatter(dateFormatter);
formatModel.setMoney(conversionService.convert(12345.678, String.class));
formatModel.setDate(conversionService.convert(new Date(), String.class));
model.addAttribute("contentModel", formatModel);
}
return "formattest";
}
}
复制代码
这次没有了Locale locale=LocaleContextHolder.getLocale();再次运行测试并更改语言后刷新,可以看到与第一种方法截图同样的效果,说明DefaultFormattingConversionService会自动根据浏览器请求的信息返回相应的格式。
3.估计有人会觉得,啊…我只是想要格式化显示而已,还要这么麻烦,写代码一个字段一个字段的转换???别急,上面只是对内置的格式化转换器做一下演示,实际项目中肯定不会这么用的,下面就介绍一下基于注解的格式化。首先把FormatModel.java改为如下内容:
复制代码
package com.demo.web.models;
import java.util.Date;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.annotation.NumberFormat;
import org.springframework.format.annotation.NumberFormat.Style;
public class FormatModel{
@NumberFormat(style=Style.CURRENCY)
private double money;
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
private Date date;
public double getMoney(){
return money;
}
public Date getDate