SpringMVC中遇到的一些問題

1.SpringMVC在Controller中接收Date類型的參數

首先定義一個接收Date類型的handler,代碼以下:ajax

@GetMapping(value = "/hour", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
public String getHourAverage(@RequestParam(value = "startTime") Date startTime, @RequestParam(value = "endTime") Date endTime){
return "startTime:" + startTime + "endTime" + endTime;
}

而後須要定義一個類型轉換器,此類須要實現Converter<String, Date>接口,代碼以下:spring

public class DateConvert implements Converter<String, Date> {

    private Logger LOGGER = LoggerFactory.getLogger(DateConvert.class);

    @Override
    public Date convert(String s) {
        try {

            return DateUtil.parse(s);

        }catch (Exception e){
          LOGGER.error("Date convert exception, source :"+ s +",exception:", e);
        }

        return null;
    }

}

最後須要將此轉換器注入到FormattingConversionServiceFactoryBean中,Spring中的配置代碼以下json

<mvc:annotation-driven conversion-service="customConversionService"/>瀏覽器

<bean id="customConversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
    <property name="converters">
        <set>
            <bean class="com.zjut.convert.DateConvert"></bean>
        </set>
    </property>
</bean>

完成此配置後,便可在hanler中接收Date類型的參數。開啓此服務,在瀏覽器中輸入:mvc

http://localhost:8088/average/hour.ajax?startTime=2017-01-01%2012:12:12&&endTime=2017-09-09%2012:12:12

會獲得如下輸出:
圖片描述app

2.SpringMVC返回json字符串時對Date類型的格式化

在使用SpringMVC實現返回json字符串的接口時候,當返回的數據類型由Date類型的時候,須要對這種類型作特殊的轉換才能獲得咱們想要的格式化的時間字符串,實現此功能只須要在Model類中的get方法作簡單的處理便可,首先咱們須要添加jackson依賴,配置以下:ide

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
      <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-core</artifactId>
      </dependency>
      <!-- https://mvnrepository.com/artifact/org.codehaus.jackson/jackson-core-asl -->
      <dependency>
          <groupId>org.codehaus.jackson</groupId>
          <artifactId>jackson-core-asl</artifactId>
      </dependency>

      <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
      <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-databind</artifactId>
      </dependency>

      <!-- https://mvnrepository.com/artifact/org.codehaus.jackson/jackson-mapper-asl -->
      <dependency>
          <groupId>org.codehaus.jackson</groupId>
          <artifactId>jackson-mapper-asl</artifactId>
      </dependency>

添加依賴後,只須要在Date類型的字段的get方法中添加以下註解便可,以下:spa

@JsonFormat(pattern = DateUtil.DEFAULT_DATE_FORMAT)
public Date getCreatedTime() {
    return createdTime;
}

其中pattern參數爲格式化參數。經過以上配置以後,訪問接口後獲得的數據以下所示,能夠看到createTime格式爲時間字符串:
圖片描述code

相關文章
相關標籤/搜索