接收Date类型数据

当客户端发起这样的请求时,服务端如何接收其中的日期参数settleDate呢:

http://localhost:8080/calculate/1?settleDate=2016-10-30

 

以前我们基本上是用一个字符串来接收这个参数,然后在代码中手动将其转换为Date类型。如:

public void test(@PathViriable lendId, @RequestParam String settleDate){
    Date actualSettleDate;
    if(settleDate ==null){
        actualSettleDate = new Date();
    }else{
        actualSettleDate = DateUtils.parseDate(settleDate,"yyyy-MM-dd");
    }
    ......
}

然而SpringMVC提供了一个更简便的方法: 

public void test(@PathViriable lendId,@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) Date settleDate){
    if(settleDate == null){
 
        settleDate = new Date();
    }
    ......
}

其中的iso属性预定义了yyyy-MM-dd、HH:mm:ss.SSSZ、yyyy-MM-dd'T'HH:mm:ss.SSSZ这三种格式。如果需要别的格式,可以用其中的pattern属性来自定义。

不过,如果要通过SpringMVC的注解来给日期参数设定默认值(比如设值为当前日期),需要自己进行扩展。


 

用一个复杂对象接收多个参数

当客户端发起这样的请求时,服务端如何接收其中的全部参数呢:

http://localhost:8080/calculate/product/97?currentPhase=1&overdueDays=1,16&channelType=UCREDIT&fundSource=RENRENDAI&monthlyRepay=1000&originPrincipal=900000

 

常用的做法,是在Controller的对应方法上,把所有参数一一列出来:

public void calcluate(@PathViriable productId, @RequestParam int currentPhase, @RequestParam Integer[] overdueDays, @RequestParam ChannelType channelType, @RequestParam FundSource fundSource, @RequestParam BigDecimal monthlyRepay, @RequestParam BigDecimal originPrincipal){
    ......
}


或者用一个Map<String, String>,来接收全部参数,然后手动将其转化为对应的格式:

public void calcluate(@PathViriable productId, @RequestParam(required = false) Map<String, String> param){
    ......
}

其实还有第三种方式,即定义一个数据封装类,用这个类来接收参数:

public void calcluate(@PathViriable productId, RestParam param){
    ......
}

其中的数据封装类如下:

public class RestParam extends NonIDBaseModel {
    /**
     *
     */
    private static final long serialVersionUID = 3550863010097047054L;
 
    private int currentPhase;
 
    private List<Integer> overdueDays = new ArrayList<>();

    private ChannelType channelType;
   
    private FundSource fundSource;
    
    private BigDecimal monthlyRepay;
  
    private BigDecimal originPrincipal;
 
    // getters/setters
}

需要注意的是,controller的方法上,对 RestParam param不要再加@RequestParam注解。

 

参考

http://www.cnblogs.com/fangjian0423/p/springMVC-request-param-analysis.html