SpringMVC中日期格式的转换问题

SpringMVC中日期格式的转换问题

1.前端传某一种日期格式的数据,后端如何接收?

前端传日期类的格式,后端该如何处理?以及前端传多种日期格式的数据,后端又如何处理??

下面会测试yyyy年MM月dd日、yyyy/MM/dd、yyyy-MM-dd等日期格式的数据,以及get方式和post方式传yyyy年MM月dd日的区别

1.2前端传yyyy-MM-dd日期格式
1.2.1、前端代码:
<form action="/date.action">
        时间:<input type="date" name="date">
        <input type="submit" value="提交">
 </form>
1.2.2、编写转换器(转换为date日期格式)以及测试
@Controller
public class MyDateFormat {
    /**
     * 处理某一种时间格式的方法
     * @param binder
     */
    @InitBinder
    public void aa(ServletRequestDataBinder binder){
        binder.registerCustomEditor(Date.class,new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),false));
    }
    /**测试
    */
      @RequestMapping("date")
    public String getDate(Date date){
        System.out.println("接收到的数据为"+date);
        return null;//这里我返回的是空,前端会报404-未找到,可自行返回一个指定的jsp页面(下同)
    }
}
1.3、前端传yyyy/MM/dd日期格式
1.3.1、前端代码
 <form action="/date.action" method="post">
        时间:<input type="text" name="date">
        <input type="submit" value="提交">
    </form>

手动输入yyyy/MM/dd格式的数据

1.3.2 、转换器与测试代码

与1.2.2相同

1.4、前端传年月日的格式
1.4.1、前端代码
 <form action="/date.action" method="post">
        时间:<input type="text" name="date">
        <input type="submit" value="提交">
    </form>
    <form action="/date.action" >
        时间:<input type="text" name="date">
        <input type="submit" value="提交">
    </form>
1.4.2、转换器与测试代码

与上面1.2.2相同

1.4.3、问题说明

form表单默认的提交方式是get

日期里面含有中文年月日,如果是get方式提交,则后端能解析出来数据,如果是post提交出现乱码,后端无法解析,则需要处理字符编码问题

1.4.4 、配置过滤器处理编码问题
 <!--  如果日期里面含有中文年月日并且提交方式是post方式则需要处理字符编码设置如下-->
  <filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
        <!--设置编码方式为utf-8--->
      <param-name>encoding</param-name>
      <param-value>utf-8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
1.5、自定义Editor转换多种共日期格式
1.5.1、模仿CustomDateEditor自定义DateEditor(只需要修改CustomDateEditor的三处)
**
 * 自定义editor(处理时间)
 */
public class MyCustomDateEditor extends PropertyEditorSupport {
    private  DateFormat dateFormats[];//修改1

    private final boolean allowEmpty;

    private final int exactDateLength;


    /**
     * Create a new CustomDateEditor instance, using the given DateFormat
     * for parsing and rendering.
     * <p>The "allowEmpty" parameter states if an empty String should
     * be allowed for parsing, i.e. get interpreted as null value.
     * Otherwise, an IllegalArgumentException gets thrown in that case.
     * @param allowEmpty if empty strings should be allowed
     */
    public MyCustomDateEditor(DateFormat[] dateFormats, boolean allowEmpty) {
        this.dateFormats = dateFormats;
        this.allowEmpty = allowEmpty;
        this.exactDateLength = -1;
    }

    /**
     * Create a new CustomDateEditor instance, using the given DateFormat
     * for parsing and rendering.
     * <p>The "allowEmpty" parameter states if an empty String should
     * be allowed for parsing, i.e. get interpreted as null value.
     * Otherwise, an IllegalArgumentException gets thrown in that case.
     * <p>The "exactDateLength" parameter states that IllegalArgumentException gets
     * thrown if the String does not exactly match the length specified. This is useful
     * because SimpleDateFormat does not enforce strict parsing of the year part,
     * not even with {@code setLenient(false)}. Without an "exactDateLength"
     * specified, the "01/01/05" would get parsed to "01/01/0005". However, even
     * with an "exactDateLength" specified, prepended zeros in the day or month
     * part may still allow for a shorter year part, so consider this as just
     * one more assertion that gets you closer to the intended date format.
     * @param allowEmpty if empty strings should be allowed
     * @param exactDateLength the exact expected length of the date String
     */
    public MyCustomDateEditor(DateFormat[] dateFormats, boolean allowEmpty, int exactDateLength) {
        this.dateFormats = dateFormats;
        this.allowEmpty = allowEmpty;
        this.exactDateLength = exactDateLength;
    }
    /**
     * Parse the Date from the given text, using the specified DateFormat.
     */
    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        if (this.allowEmpty && !StringUtils.hasText(text)) {
            // Treat empty String as null value.
            setValue(null);
        }
        else if (text != null && this.exactDateLength >= 0 && text.length() != this.exactDateLength) {
            throw new IllegalArgumentException(
                    "Could not parse date: it is not exactly" + this.exactDateLength + "characters long");
        }
        else {
            boolean b=false;
                for ( DateFormat d:dateFormats) {//修改2
                    try{
                        setValue(d.parse(text));
                        b=true;
                        return;
                    }catch (Exception e){
                        continue;
                    }
                }
            if(!b){
                throw new IllegalArgumentException("Could not parse date: ");
            }
        }
    }

    /**
     * Format the Date as String, using the specified DateFormat.
     */
    @Override
    public String getAsText() {
        Date value = (Date) getValue();
        if(null!= value){
            for (DateFormat d:dateFormats) {//修改3
               try{
                   return d.format(value) ;
               }catch (Exception e){
                   continue;
               }
            }
        }else{
            return "";
        }
        return null;
    }
}
1.5.2 、编写转换器与测试代码
@Controller
public class MyDateFormat {
    /**
     * 处理某一种时间格式的方法
     * @param binder
     */
    private DateFormat[] dateFormats={
        //这里写前端传来的日期格式
            new SimpleDateFormat("yyyy-MM-dd"),
            new SimpleDateFormat("yyyy/MM/dd"),
            new SimpleDateFormat("yyyy年MM月dd日")
    };
    /**
     * 使用自定义的编辑器处理时间格式
     * @param binder
     */
    @InitBinder
    public void aa(ServletRequestDataBinder binder){
        binder.registerCustomEditor(Date.class,new MyCustomDateEditor(dateFormats,false));
    }
    @RequestMapping("date")
    public String getDate(Date date){
        System.out.println("接收到的数据为"+date);
        return null;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值