SpringBoot實戰(五)-Exception -服務器端API -Postman(再斷更)

2020.3.6

直接原因:UP主有時寫的亂,跟不下去

(發覺慕課網的實戰課程更加有條理,所以之後記錄之前沒有寫的日誌工具,報錯提示和Enums)

根本原因:打滿雞血衝了一個星期之後開始怠惰(看似不可避免)

But:其實也不算斷了,只不過是學其他的去了,其他的怠惰了這個可能又開始學了:)

(循環雞血,循環怠惰,說好聽點是遵循人性)

ExceptionHandler  //TODO

需要advice.CustomizeExceptionHandler,CommentController,exception包下還有三個class

 

API

寫一個服務端的接口(API),使用前後端約定好的Json格式,從前端發送到後端

現在API完成一個插入Comment過程

和以前的Get請求的區別:方法返回類型是Object,加上了@ResponseBody

@ResponseBody的作用其實是將Java對象轉爲Json格式的數據,會自動反序列化Json爲對象

 

網絡傳輸新建CommentDTO

@Data
public class CommentDTO {
    private Long id;
    private Long parentId;
    private Integer type;
    private Long commentator;
    private Long gmtCreate;
    private Long gmtModified;
    private Long likeCount;
    private Integer commentCount;
    private String content;
    private User user;
}

 

@RequestBody CommentDTO commentDTO

新註解@RequestBody可以直接傳一個對象,比傳參要快

@Controller
public class CommentController {

    @Autowired
    private CommentMapper commentMapper;

    @ResponseBody
    @RequestMapping(value = "/comment", method = RequestMethod.POST)
    public Object post(@RequestBody CommentDTO commentDTO) {
        Comment comment = new Comment();
        comment.setParentId(commentDTO.getParentId());
        comment.setContent(commentDTO.getContent());
        comment.setType(commentDTO.getType());
        comment.setGmtCreate(System.currentTimeMillis());
        comment.setGmtModified(System.currentTimeMillis());
        comment.setCommentator(1);
        commentMapper.insert(comment);
        return null;
    }
}

使用Postman

如果報錯content-type有問題:

傳入了數據庫:

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章