SpringMvc学习笔记(六)客户端数据的类型转换

后台接收前台传来的日期类型,@DateTimeFormat注解简单使用,认识注解InitBinde,对要转换的字符串类型进行处理,

源码获取github

1.项目结构

2.@DateTimeFormat注解简单使用

demo01.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
   <title>Title</title>
</head>
<body>
<h2>传递日期的字符串</h2>
<form action="client01" method="get">
   <input type="text" name="mydate">
   <button>日期字符串</button>
</form>
</body>
</html>

DateDemoController.java

/**
 * 接收日期类型的客户端传递数据,简写方式
 * 没有写注解,就写 2018/8/14 15:31:20
 * 写了注解就按照他的格式来,如果没有写时间,你输入了时间也不会认
 * 如果一个类中也有这样的属性,同时接收这个时间,注解里也要写格式
 *
 * @return
 */
@GetMapping("/client01")
public ModelAndView test01(
      @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date mydate,
      User user) {
   System.out.println(mydate);
   System.out.println(user);
   return null;
}

User.java

package com.hs.model;

import org.springframework.format.annotation.DateTimeFormat;

import java.util.Date;

public class User {
//注解放哪,根据公司要求
// @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
   Date mydate;

   public Date getMydate() {
      return mydate;
   }

   @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
   public void setMydate(Date mydate) {
      this.mydate = mydate;
   }

   @Override
   public String toString() {
      return "User{" +
            "mydate=" + mydate +
            '}';
   }
}

3.认识注解InitBinde

InitBinderDemoController.java

package com.hs.web;

import com.hs.model.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 认识注解InitBinder
 */
@Controller
public class InitBinderDemoController {
   @GetMapping("/test01")
   public ModelAndView test01() {
      System.out.println("test01");
      return null;
   }

   @GetMapping("/test02")
   public ModelAndView test02(HttpServletRequest request, HttpServletResponse response) {
      System.out.println("test02");
      return null;
   }

   @GetMapping("/test03")
   public ModelAndView test03(Map<String, Object> map) {
      System.out.println("test03");
      return null;
   }

   @GetMapping("/test04")
   public ModelAndView test04(Integer user_id) {
      System.out.println("test04");
      return null;
   }

   @GetMapping("/test05")
   public ModelAndView test05(String name, Integer user_id) {
      System.out.println("test05");
      return null;
   }

   @GetMapping("/test06")
   public ModelAndView test06(User user) {
      System.out.println("test06");
      return null;
   }

   @GetMapping("/test07")
   public ModelAndView test07(User user, String name) {
      System.out.println("test07");
      return null;
   }

   @InitBinder
   public void init01() {
      System.out.println("需要知道什么情况下执行?");
   }
}

运行之后发现,04,06都是调用了1次,05,07调用了两次,因为这些的形参,被传递过来,都要进行转换,所以就调用了@InitBinder注解:当传递过来的数据要进行转换的时候才调用。

4.对要转换的字符串类型进行处理

StringDemoController.java

package com.hs.web;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.servlet.ModelAndView;

import java.beans.PropertyEditorSupport;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 对要转换的字符串类型进行处理
 */
@Controller
public class StringDemoController {

   @GetMapping("hs01")
   public ModelAndView test01(Integer user_id) {
      System.out.println(user_id);
      return null;
   }

   @GetMapping("hs02")
   public ModelAndView test02(String user_name) {
      System.out.println(user_name);
      return null;
   }

   @GetMapping("hs03")
   public ModelAndView test03(String user_name, Integer user_id) {
      System.out.println(user_name);
      System.out.println(user_id);
      return null;
   }

   /**
    * 时间格式的转换
    *
    * @param date1
    * @return
    */
   @GetMapping("hs04")
   public ModelAndView test04(Date date1) {
      System.out.println("日期为" + date1);
      return null;
   }

   @InitBinder
   public void init01(WebDataBinder binder) {
      //监控要转换(String)的数据类型
      binder.registerCustomEditor(String.class, /*匿名对象*/new PropertyEditorSupport() {
         //重写了setAsText方法
         @Override
         public void setAsText(String text) throws IllegalArgumentException {
            System.out.println("之前接收的值----" + text);
            //对数据重新处理赋值,赋值给形参user_name
            this.setValue("对数据处理之后的值----" + text + "悟空");
         }
      });

      //监控Integer类型
      binder.registerCustomEditor(Integer.class, new PropertyEditorSupport() {
         @Override
         public void setAsText(String text) throws IllegalArgumentException {
            System.out.println(text);
            this.setValue("999");
         }
      });
   }

   @InitBinder
   public void init02(WebDataBinder binder) {
      binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
         @Override
         public void setAsText(String text) throws IllegalArgumentException {
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            try {
               Date date = df.parse(text);
               this.setValue(date);
            } catch (ParseException e) {
               e.printStackTrace();
            }

         }
      });
   }
}

5.用别人封装好的工具类实现各种日期类型都可以转换

需要commons-lang3-3.4.jar这个包

DateHelper.java

package com.hs.util;

import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;

/**
 * 扩展DateUtils的基础上扩展属于自己的工具类
 *造轮子
 * @author 刘文铭
 * @see com.shxt.commons.helper.DateHelper
 * @since 1.0
 */

public final class DateHelper extends DateUtils {
   private final static String[] parsePatterns = {"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm",
         "yyyy-MM", "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM", "yyyy.MM.dd",
         "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

   private final static String DEFAULT_DATE_TIME = "yyyy-MM-dd HH:mm:dd";
   private final static String DEFAULT_DATE = "yyyy-MM-dd";
   private final static String DEFAULT_TIME = "HH:mm:dd";
   private final static String DEFAULT_YEAR = "yyyy";
   private final static String DEFAULT_MONTH = "MM";
   private final static String DEFAULT_DAY = "dd";
   private final static String DEFAULT_E = "E";

   private static Date nowDate = new Date();

   private static Calendar calendar = Calendar.getInstance();

   /**
    * java.util.Date转换格式(yyyy-MM-dd)
    *
    * @return String
    */
   public static String getCurrentDate() {
      return DateHelper.getDefDateTime(DEFAULT_DATE);
   }

   /**
    * java.util.Date转换格式(HH:mm:ss)
    *
    * @return String
    */
   public static String getCurrentTime() {
      return DateHelper.getDefDateTime(DEFAULT_TIME);
   }

   /**
    * java.util.Date转换格式(yyyy-MM-dd HH:mm:ss)
    *
    * @return String
    */
   public static String getCurrentDateTime() {
      return DateHelper.getDefDateTime(DEFAULT_DATE_TIME);
   }

   /**
    * 获取自定义格式的当前日期
    * <p>
    * 获取特定格式的日期
    * </p>
    *
    * @param pattern 默认格式(yyyy-MM-dd) 可以为:"yyyy-MM-dd" "HH:mm:ss" "E"
    * @return String
    */
   public static String getDefDateTime(String pattern) {
      return DateFormatUtils.format(nowDate, pattern);
   }

   /**
    * 得到当前年份字符串 格式(yyyy)
    *
    * @return String
    */
   public static String getYear() {
      return DateHelper.getDefDateTime(DEFAULT_YEAR);
   }

   /**
    * 得到当前月份字符串 格式(MM)
    *
    * @return String
    */
   public static String getMonth() {
      return DateHelper.getDefDateTime(DEFAULT_MONTH);
   }

   /**
    * 得到当天字符串 格式(dd)
    *
    * @return String
    */
   public static String getDay() {
      return DateHelper.getDefDateTime(DEFAULT_DAY);
   }

   /**
    * 得到当前星期字符串 格式(E)星期几
    *
    * @return String
    */
   public static String getWeek() {
      return DateHelper.getDefDateTime(DEFAULT_E);
   }

   /**
    * 获取日期字符串,java.util.Date转化为字符串
    * <p>
    * 使用格式化数据,
    * </p>
    *
    * @param date
    * @param pattern 默认格式(yyyy-MM-dd) 可以为:"yyyy-MM-dd" "HH:mm:ss" "E"
    * @return String
    */
   public static String formatDate(Date date, String... pattern) {
      String formatDate = null;
      if (pattern != null && pattern.length > 0) {
         formatDate = DateFormatUtils.format(date, pattern[0].toString().trim());
      } else {
         formatDate = DateFormatUtils.format(date, DEFAULT_DATE);
      }
      return formatDate;
   }

   /**
    * 日期型字符串转化为日期 格式
    * { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm",
    * "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm",
    * "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm" }
    */
   public static Date parseDate(Object date_str) {
      try {
         if (date_str == null || String.valueOf(date_str).trim().length() == 0) {
            return null;
         }
         return DateUtils.parseDate(String.valueOf(date_str).trim(), parsePatterns);
      } catch (ParseException pe) {
         System.out.println("DateHelper-->parseDate方法格式化错误");
         return null;
      }
   }

   /**
    * 获取过去的天数
    *
    * @param date
    * @return
    */
   public static long pastDays(Date date) {
      long t = new Date().getTime() - date.getTime();
      return t / (24 * 60 * 60 * 1000);
   }

   /**
    * 获取过去的小时
    *
    * @param date
    * @return
    */
   public static long pastHour(Date date) {
      long t = new Date().getTime() - date.getTime();
      return t / (60 * 60 * 1000);
   }

   /**
    * 获取过去的分钟
    *
    * @param date
    * @return
    */
   public static long pastMinutes(Date date) {
      long t = new Date().getTime() - date.getTime();
      return t / (60 * 1000);
   }

   /**
    * 转换为时间(天,时:分:秒.毫秒)
    *
    * @param timeMillis
    * @return
    */
   public static String formatDateTime(long timeMillis) {
      long day = timeMillis / (24 * 60 * 60 * 1000);
      long hour = timeMillis / (60 * 60 * 1000) - day * 24;
      long min = timeMillis / (60 * 1000) - day * 24 * 60 - hour * 60;
      long s = timeMillis / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60;
      long sss = timeMillis - day * 24 * 60 * 60 * 1000 - hour * 60 * 60 * 1000 - min * 60 * 1000 - s * 1000;
      return (day > 0 ? day + "," : "") + hour + ":" + min + ":" + s + "." + sss;
   }

   /**
    * 获取两个日期之间的天数
    *
    * @param before
    * @param after
    * @return
    */
   public static double getDistanceOfTwoDate(Date before, Date after) {
      long beforeTime = before.getTime();
      long afterTime = after.getTime();
      return (afterTime - beforeTime) / (1000 * 60 * 60 * 24);
   }

   /**
    * 获取当前日期,一周前的日期字符串
    *
    * @return String
    */
   public static String getLastWeek() {
      long rightnow = calendar.getTimeInMillis();
      long aweekbefore = 6 * 24 * 60 * 60 * 1000;
      return DateFormatUtils.format(rightnow - aweekbefore, DEFAULT_DATE);
   }

   /**
    * 获取格式化当前月第一天的表达式
    *
    * @return String
    */
   public static String getFirstDayInMonth() {
      calendar.set(DateHelper.getYearNUM(), DateHelper.getMonthNUM() - 1, 1);// 设为当前月的1号 ,月从0开始
      return DateFormatUtils.format(calendar.getTime(), DEFAULT_DATE);
   }

   /**
    * 获取格式化给定月(参数:逻辑月)第一天的表达式,重载方法
    *
    * @param month
    * @return String
    */
   public static String getFirstDayInMonth(int month) {
      calendar.set(DateHelper.getYearNUM(), month - 1, 1);// 设为当前月的1号 ,月从0开始
      return DateFormatUtils.format(calendar.getTime(), DEFAULT_DATE);
   }

   /**
    * 获取格式化给定月(参数:逻辑月)最后一天的表达式
    *
    * @param month
    * @return String
    */
   public static String getLastDayInMonth(int month) {
      calendar.set(DateHelper.getYearNUM(), month, 1); // 设成下个月的一号,往前减一天的时间
      return DateFormatUtils.format(calendar.getTimeInMillis() - 24 * 60 * 60 * 1000, DEFAULT_DATE);
   }

   /**
    * 获取格式化当前季度第一天的表达式
    *
    * @return String
    */
   public static String getFirstDayInQuart() {
      int month = DateHelper.getMonthNUM();
      if (month >= 1 && month <= 3) {
         month = 1;
      }
      if (month >= 4 && month <= 6) {
         month = 4;
      }
      if (month >= 7 && month <= 9) {
         month = 7;
      }
      if (month >= 10 && month <= 12) {
         month = 10;
      }
      calendar.set(DateHelper.getYearNUM(), month - 1, 1); // 当年当季一号,月从0开始
      return DateFormatUtils.format(calendar.getTime(), DEFAULT_DATE);
   }

   /**
    * @return String 获取格式化一年第一天的表达式
    */
   public static String getFirstDayInYear() { /** 获取格式化一年第一天的表达式 **/
      calendar.set(calendar.get(Calendar.YEAR), 0, 1); // 当年第一个月一号,月从0开始
      return DateFormatUtils.format(calendar.getTime(), DEFAULT_DATE);
   }

   /**
    * @return int 获得当前年份
    */
   public static int getYearNUM() { /** 获得当前年份 */
      return calendar.get(Calendar.YEAR);
   }

   /**
    * @return int 获得当前月份
    */
   public static int getMonthNUM() { /*** 获得当前月份 **/
      return calendar.get(Calendar.MONTH) + 1;
   }

   /**
    * @return int 获得当前周数
    */
   public static int getWeekNUM() { /*** 获得当前周数 **/
      return calendar.get(Calendar.DAY_OF_WEEK);
   }

   /**
    * @return int 取到一天中的小时数
    */
   public static int getHoursofDay() {
      return Calendar.HOUR_OF_DAY;
   }

   /**
    * 获取最近ndays天(含今天)的日期,返回日期表达式数组
    *
    * @param ndays
    * @return String[]
    */
   public static String[] getDaysBackward(int ndays) {
      String[] daysBackward = new String[ndays];
      Calendar lastDate;
      for (int i = 0; i < ndays; i++) {
         lastDate = Calendar.getInstance();
         lastDate.add(Calendar.DATE, -1 * i); // 减去一天,变为上月最后一天
         daysBackward[ndays - 1 - i] = DateFormatUtils.format(lastDate.getTimeInMillis(), DEFAULT_DATE);
      }
      return daysBackward;
   }

}

DateDemoController.java

/**
 * 用别人封装好的时间类型转换类,造轮子
 *
 * @param mydate
 * @return
 */
@GetMapping("/client01")
public ModelAndView test01(Date mydate) {
   System.out.println(mydate);
   return null;
}

@InitBinder
public void initDate(WebDataBinder binder) {
   binder.registerCustomEditor(Date.class, new PropertyEditorSupport(){
      @Override
      public void setAsText(String text) throws IllegalArgumentException {

         this.setValue(DateHelper.parseDate(text));
      }
   });
}

页面还是那个demo01.jsp页面

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值