06 数据绑定之类型转化
发布日期:2022-03-30 20:19:32 浏览次数:25 分类:博客文章

本文共 2634 字,大约阅读时间需要 8 分钟。

本文将阐述springmvc中的数据类型转化。

1、环境约束

  • win10 64位操作系统
  • idea2018.1.5
  • jdk-8u162-windows-x64
  • spring4.2.4

2、前提约束

  • 完成基于注解的springmvc的demo

3、操作步骤

1.内置转化

springmvc内置了很多转化器,可以完成大部分的数据转化工作,换言之,绝大多数情况下我们可以不用去关心数据类型的转换,但对于一些特殊的数据类型,比如日期、时间戳等,是需要用户自定义类型转换的。

2.当前Controller

我们先来完成仅对当前Controller起作用的转化器。

  • 在src文件夹下创建net.wanho.controller.InitBinderController.java,内容如下:
import net.wanho.ssm.entity.Phone;import org.springframework.stereotype.Controller;import org.springframework.web.bind.WebDataBinder;import org.springframework.web.bind.annotation.InitBinder;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import java.beans.PropertyEditorSupport;import java.text.SimpleDateFormat;import java.util.Date;@Controllerpublic class InitBinderController {    @InitBinder    public void init(WebDataBinder binder)    {        binder.registerCustomEditor(Date.class, new PropertyEditorSupport(){            @Override            public String getAsText() {                return super.getAsText();            }            @Override            public void setAsText(String text) throws IllegalArgumentException {                try {                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");                    Date date = simpleDateFormat.parse(text);                    setValue(date);                }                catch (Exception e)                {                    e.printStackTrace();                }            }        });    }    @RequestMapping("/init/dateformat")    @ResponseBody    public String test0(Date date)    {        return date.toString();    }}
  • 启动tomcat,测试,在浏览器中输入
    上面的只针对当前的InitBinderController.java,我们接下来看对所有Controller起作用的类型转换。

3.全局Controller

  • 在src文件夹下创建net.wanho.convertor.String2DateConvertor.java,内容如下:
import org.springframework.core.convert.converter.Converter;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;public class String2DateConvertor implements Converter
{ @Override public Date convert(String s) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); Date date = null; try { date = simpleDateFormat.parse(s); } catch (ParseException e) { e.printStackTrace(); } return date; }}
  • 在spring-mvc.xml中加入以下内容:
  • 注释掉InitBinderController.java中的@InitBinder注解
  • 启动tomcat,测试,在浏览器中输入
    当前这个转换器,无论对哪一个Controller请求都会起作用。除了采用这种配置的方式完成全局的类型转换外,还可以采用@ControllerAdvice这种横切性的技术,后面我们将会阐述。
    以上就是spring中数据类型的转换。

转载地址:https://www.cnblogs.com/alichengxuyuan/p/12554611.html 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:05 异常的处理
下一篇:Python爬虫-----基于urllib,urllib2,re

发表评论

最新留言

路过按个爪印,很不错,赞一个!
[***.219.124.196]2024年04月21日 09时17分49秒