• 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

  • 相关阅读:
    CF700C Break Up
    CF865C Gotta Go Fast
    CF1559D2 Mocha and Diana (Hard Version)
    CF1500C Matrix Sorting
    排列计数机
    CSP-S 2021 退役记
    【做题记录】[NOIP2011 提高组] 观光公交
    【做题记录】构造题
    乱搞
    二维树状数组
  • 原文地址:https://www.cnblogs.com/TimerHotel/p/springboot02.html
Copyright © 2020-2023  润新知