springmvc之数据格式化

阅读更多

一、使用内置的注解进行字段级别的解析/格式化:

1、在模型类字段级别添加@NumberFormat、@DateTimeFormat等内置注解:

public class FormatterModel {  
    @NumberFormat(style=Style.NUMBER, pattern="#,###")  
    private int totalCount;  
    @NumberFormat(style=Style.PERCENT)  
    private double discount;  
    @NumberFormat(style=Style.CURRENCY)  
    private double sumMoney;  
      
    @DateTimeFormat(iso=ISO.DATE)   
    private Date registerDate;  
      
    @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")   
    private Date orderDate;  
  
    //省略getter/setter  
}  

 

2、解析/格式化验证:

FormatterController类:

@Controller
public class FormatterController {

    @RequestMapping("/formatter/hello")
    public String formatter(@ModelAttribute("model")FormatterModel model) {
        model.setTotalCount(10000);
        model.setDiscount(0.51);
        model.setSumMoney(10000.13);
        model.setRegisterDate(new Date(2013-1900, 4, 1));
        model.setOrderDate(new Date(2013-1900, 4, 1, 20, 18, 18));

        return "formatter";
    }
}

 fomatter.jsp:

<%@ page language= "java" contentType= "text/html; charset=UTF-8" pageEncoding= "UTF-8"%>
<%@taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
totalCount:${status.value}
discount:${status.value}
sumMoney:${status.value}
registerDate:${status.value}
orderDate:${status.value}


 使用http://localhost:8080/formatter/hello访问可看到格式化后的结果。

 

二、功能处理方法参数级别的数据解析:

@Controller
public class FormatterController2 {

    @RequestMapping("/formatter/hello2")
    public String formatter(@DateTimeFormat(pattern="yyyy-MM-dd") @RequestParam("date") Date date) {
        System.out.println(date);
        return "success";
    }
}

访问地址:http://localhost:8080/formatter/hello2?date=2012-12-10

 

你可能感兴趣的:(springmvc之数据格式化)