springboot2.0入门(三)----定义编程风格
2020-12-13 16:55
标签:slf4j rgs 例子 private ping 请求 排除 code tail 一、RESTFul风格API 1、优点: GET : 获取资源 二、代码演示: 新建Animal类,使用注解,包含设置get/set方法、全部参数构造器、无参数构造器、builder快速创建对象 新建 AnimalController,用postMan做测试: 新建一个post请求(添加),返回创建的对象; 上述注解可以改为上面的代码所示 @PathVariable 参数说明 delete请求例子 springboot默认json工具为:jackjson 各种json工具性能对比:https://blog.csdn.net/accountwcx/article/details/50252657 @JsonIgnore 排除属性不做序列化与反序列化 @JsonProperty 为属性换一个名 springboot2.0入门(三)----定义编程风格 标签:slf4j rgs 例子 private ping 请求 排除 code tail 原文地址:https://www.cnblogs.com/liweiweicode/p/11622313.html
HTTP方法体现对资源的操作:
POST : 添加资源
PUT : 修改资源
DELETE : 删除资源/**
* @author Levi
* @date 2019/9/18 9:31
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Animal {
private String name;
private Integer type;
private String num;
private Long id;
private Date birthDate;
}
/**
* @author Levi
* @date 2019/9/18 9:36
*/
@Slf4j
@RestController
@RequestMapping("/rest")
public class AnimalController {
@RequestMapping(value = "/animals", method = POST, produces = "application/json")
public AjaxResponse saveArticle(@RequestBody Animal animal) {
log.info("saveArticle:{}",animal);
return AjaxResponse.success(animal);
}
@RequestMapping(value = "/animals/{id}", method = DELETE, produces = "application/json")
public AjaxResponse deleteArticle(@PathVariable Long id) {
log.info("deleteAnimals:{}",id);
return AjaxResponse.success(id);
}
@RequestMapping(value = "/animals/{id}", method = PUT, produces = "application/json")
public AjaxResponse updateArticle(@PathVariable Long id, @RequestBody Animal animal) {
animal.setId(id);
log.info("updateArticle:{}",animal);
return AjaxResponse.success(animal);
}
@RequestMapping(value = "/animals/{id}", method = GET, produces = "application/json")
public AjaxResponse getArticle(@PathVariable Long id) {
Animal animal = Animal.builder().id(1L).name("levi").build();
return AjaxResponse.success(animal);
}
}
@RestController = @Controller + @ResponseBody
@Slf4j
@Controller
@RequestMapping("/rest")
public class AnimalController {
@RequestMapping(value = "/animals", method = POST, produces = "application/json")
public @ResponseBody AjaxResponse saveArticle(@RequestBody Animal animal) {
log.info("saveArticle:{}",animal);
return AjaxResponse.success(animal);
}
三、json配置:
@JsonPropertyOrder(value={"pname1","pname2"}) 改变json子属性的默认定义的顺序
@JsonInclude(JsonInclude.Include.NON_NULL) 排除为空的元素不做序列化反序列化
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") 指定属性格式全局时间配,在yml文件中配置,避免在请求时间的时候,格式不一致报错,
spring:
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
文章标题:springboot2.0入门(三)----定义编程风格
文章链接:http://soscw.com/index.php/essay/36592.html