zoukankan      html  css  js  c++  java
  • 2、SpringBoot------数据转换

    开发工具:STS

    代码下载链接:https://github.com/theIndoorTrain/Springboot/tree/083bb312526653d27ca56abf4f586e097cc4a980

    前言:

    在web项目中,前端传入的时间通常为字符串格式,比如‘1999-01-02’、‘1999/01/02’、‘1999年1月1日’等等,那么我们后端获取Date数据时就要把这种格式转换为日期格式。

    正好,Springboot中提供了@DateTimeFormat注解,方便我们的开发。

    下面来实现我们的实例。


    一、代码实现:

    1.User实体中添加Date型属性birth:

     1 package com.xm.pojo;
     2 
     3 import java.util.Date;
     4 
     5 import javax.validation.constraints.Min;
     6 
     7 import org.hibernate.validator.constraints.NotBlank;
     8 import org.springframework.format.annotation.DateTimeFormat;
     9 
    10 
    11 public class User {
    12     @Min(value=10,message="id不可以小于10")
    13     private int id;
    14     @NotBlank(message="name不能为空")
    15     private String name;
    16     @DateTimeFormat(pattern="yyyy-MM-dd")
    17     private Date birth;
    18     
    19     public Date getBirth() {
    20         return birth;
    21     }
    22     public void setBirth(Date birth) {
    23         this.birth = birth;
    24     }
    25     public int getId() {
    26         return id;
    27     }
    28     public void setId(int id) {
    29         this.id = id;
    30     }
    31     public String getName() {
    32         return name;
    33     }
    34     public void setName(String name) {
    35         this.name = name;
    36     }
    37     @Override
    38     public String toString() {
    39         return "User [id=" + id + ", name=" + name + ", birth=" + birth + "]";
    40     }
    41     
    42     
    43 
    44 }

    2.controller:

     1 package com.xm.controller;
     2 
     3 import java.util.List;
     4 
     5 import javax.validation.Valid;
     6 
     7 import org.springframework.validation.BindingResult;
     8 import org.springframework.validation.FieldError;
     9 import org.springframework.web.bind.annotation.PostMapping;
    10 import org.springframework.web.bind.annotation.RequestMapping;
    11 import org.springframework.web.bind.annotation.RestController;
    12 
    13 import com.xm.pojo.User;
    14 
    15 @RestController
    16 public class UserController {
    17     
    18     @RequestMapping("/hello")
    19     public String hello() {
    20         return "hello spring boot!";
    21     }
    22     
    23     @PostMapping("/user")
    24     public String addUser(@Valid User user) {
    25         return user.toString();
    26     }
    27 
    28 }

    二、测试结果

                                                  2018-06-23

  • 相关阅读:
    Cannot assign requested address问题总结
    Trying to connect an http1.x server
    从 0 到 1 搭建技术中台之推送平台实践:高吞吐、低延迟、多业务隔离的设计与实现
    思考gRPC :为什么是HTTP/2
    HTTP/1HTTP/2HTTP/3
    get_or_create update_or_create
    死锁案例 GAP 锁 没有就插入,存在就更新
    死锁产生必要条件
    京东零售mockRpc实践
    Certbot CA 证书 https
  • 原文地址:https://www.cnblogs.com/TimerHotel/p/springboot02.html
Copyright © 2011-2022 走看看