1. 程式人生 > 程式設計 >Springmvc資料格式化原理及程式碼案例

Springmvc資料格式化原理及程式碼案例

1、簡介

  • Converter可以將一種型別轉換成另一種型別,是任意Object之間的型別轉換。
  • Formatter則只能進String與任意Object物件的轉換,它提供解析與格式化兩種功能
    • 解析:將String型別字串轉換為任意Objec物件,
    • 格式化:將任意Objec物件轉換為字串進行格式化顯示。
  • 使用Formatter
    • 實現Formatter介面定義一個類,T為要解析得到或進行格式化的資料型別。
    • 在類中實現兩個方法
      • String print(T t,Locale locale):把T型別物件解析為字串形式返回
      • T parse(String sourse,Locale locale):由字串解析得到T型別物件。

2、示例

2.1、實體類

package com.yl.bean;

import java.util.Date;

public class User {
  private String username;
  private Date date;

  public User() {
  }

  public String getUsername() {
    return username;
  }

  public void setUsername(String username) {
    this.username = username;
  }

  public Date getDate() {
    return date;
  }

  public void setDate(Date date) {
    this.date = date;
  }

  @Override
  public String toString() {
    return "User{" +
        "username='" + username + '\'' +
        ",date=" + date +
        '}';
  }
}

2.2、控制器

package com.yl.controller;

import com.yl.bean.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class UserController {

  @RequestMapping("/stringToDate")
  public ModelAndView jsonToObject(User user){
    ModelAndView modelAndView=new ModelAndView();
    modelAndView.addObject("user",user);
    modelAndView.setViewName("success");

    System.out.println(user);

    return modelAndView;
  }

}

2.3、jsp

<form action="${pageContext.servletContext.contextPath}/stringToDate" method="post">
  請輸入日期(yyy-mm-dd):<input type="text" name="date"><br>
  <button type="submit">提交</button>
</form>

2.4、資料格式化類

package com.yl.utils;

import org.springframework.format.Formatter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * 日期格式化
 */
public class DateFormatter implements Formatter<Date> {

  /**
   * 字串轉Date
   * @param text
   * @param locale
   * @return
   * @throws ParseException
   */
  @Override
  public Date parse(String text,Locale locale) throws ParseException {
    SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd");
    return sf.parse(text);
  }

  /**
   * Date轉字串
   * @param date
   * @param locale
   * @return
   */
  @Override
  public String print(Date date,Locale locale) {
    SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd");
    return sf.format(date);
  }
}

2.5、在配置檔案註冊自定義資料格式化類

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation=" http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">

  <!--指定要掃描的包-->
  <context:component-scan base-package="com.yl"></context:component-scan>
  <!--配置檢視解析器-->
  <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/pages/"></property>
    <property name="suffix" value=".jsp"></property>
  </bean>

  <!--資料格式化工廠-->
  <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
    <property name="formatters">
      <list>
        <!--自定義格式化類-->
        <bean class="com.yl.utils.DateFormatter"/>
      </list>
    </property>
  </bean>

  <!-- 設定靜態資源不過濾-->
  <mvc:default-servlet-handler/>
  <!--開啟springmvc註解支援,註冊自定義資料格式化類-->
  <mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>

</beans>

3、使用註解實現資料格式化

package com.yl.bean;

import org.springframework.format.annotation.DateTimeFormat;

import java.util.Date;

public class User {
  private String username;
  @DateTimeFormat(pattern = "yyyy-MM-dd")
  private Date date;

  public User() {
  }

  public String getUsername() {
    return username;
  }

  public void setUsername(String username) {
    this.username = username;
  }

  public Date getDate() {
    return date;
  }

  public void setDate(Date date) {
    this.date = date;
  }

  @Override
  public String toString() {
    return "User{" +
        "username='" + username + '\'' +
        ",date=" + date +
        '}';
  }
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。