In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article focuses on "how to use spring annotations to develop a RESTful interface", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to use spring annotations to develop a RESTful interface.
First, develop REST interface
It has been introduced to you in the previous chapters of this column
Spring common notes and http data conversion tutorial
Use of lombok, a necessary tool for Spring Boot to improve development efficiency
RESTful Interface and http Protocol State statement developed by Spring Boot
The content of this section is to reflect what you have learned before in a code way.
1. Step 1: define the resource (object) @ Data@Builderpublic class Article {private Long id; private String author; private String title; private String content; private Date createTime; private List reader;} @ Datapublic class Reader {private String name; private Integer age;}
Data and Builder are all annotations provided to us by lombok, which helps us simplify the code. You can refer to the previous sections of this column to learn about lombok.
@ Builder provides us with a way to build objects through chained assignments of object properties, as described in the following code.
The @ Data annotation helps us define a series of common methods, such as getters, setters, hashcode, equals, etc.
two。 Step 2: HTTP method and Controller (Action)
We implement a simple RESTful interface
Add an Article, using the POST method
Delete an Article, use the DELETE method, and the parameter is id
Update an Article, using the PUT method with id as the primary key to update
Get an Article, using the GET method
Database operations are not actually done in the following code, and mybatis and JPA will be covered later in this column, which will be supplemented by that.
@ Slf4j@RestController@RequestMapping ("/ rest") public class ArticleController {/ / get an Article Using the GET method, query an article / / @ RequestMapping (value = "/ articles/ {id}" based on id) Method = RequestMethod.GET) @ GetMapping ("/ articles/ {id}") public AjaxResponse getArticle (@ PathVariable ("id") Long id) {/ / use the builder provided by lombok to build the object Article article = Article.builder () .id (id) .aut hor ("zimug") .content ("spring boot from Bronze to King") .createtime (new Date ()) .title ("T1") .build () Log.info ("article:" + article); return AjaxResponse.success (article) } / / add an Article, use the POST method (RequestBody method to receive parameters) / / @ RequestMapping (value = "/ articles", method = RequestMethod.POST) @ PostMapping ("/ articles") public AjaxResponse saveArticle (@ RequestBody Article article, @ RequestHeader String aaa) {/ / because lombok's Slf4j annotations are used, here you can directly use the log variable to print the log log.info ("saveArticle:" + article) Return AjaxResponse.success () } / / add an Article Use the POST method (RequestParam method to receive parameters) / * @ PostMapping ("/ articles") public AjaxResponse saveArticle (@ RequestParam String author, @ RequestParam String title, @ RequestParam String content) @ DateTimeFormat (pattern = "yyyy-MM-dd HH:mm:ss") @ RequestParam Date createTime) {log.info ("saveArticle:" + createTime) Return AjaxResponse.success () Update an Article using the PUT method to update / / @ RequestMapping with id as the primary key (value = "/ articles", method = RequestMethod.PUT) @ PutMapping ("/ articles") public AjaxResponse updateArticle (@ RequestBody Article article) {if (article.getId () = = null) {/ / article.id is a required parameter Because data is usually modified according to id / / TODO throws a custom exception} log.info ("updateArticle:" + article) Return AjaxResponse.success ();} / / Delete an Article, using the DELETE method. The parameter is id / / @ RequestMapping (value = "/ articles/ {id}", method = RequestMethod.DELETE) @ DeleteMapping ("/ articles/ {id}") public AjaxResponse deleteArticle (@ PathVariable ("id") Long id) {log.info ("deleteArticle:" + id); return AjaxResponse.success ();}}
Because you use lombok's @ Slf4j annotation (the definition of the class), you can print the log directly using the log variable. You don't need to write the following line of code.
Private static final Logger log = LoggerFactory.getLogger (HelloController.class); II. Data format of unified standard interface response
The following class is used to unify data response interface standards. Its function is to unify the return result format of all developers responding to front-end requests and reduce the communication cost of front-end and front-end developers. It is a standardized development convention of RESTful interface. The following code only encapsulates the success of the request, which will be explained in more detail in subsequent chapters related to exception handling.
@ Datapublic class AjaxResponse {private boolean isok; / / whether the request was successfully processed private int code; / / request response status code (200,400,500) private String message; / / request result description information private Object data / / request result data (usually used for query operation) private AjaxResponse () {} / / request successful response without query data (for delete, modify, new API) public static AjaxResponse success () {AjaxResponse ajaxResponse = new AjaxResponse (); ajaxResponse.setIsok (true); ajaxResponse.setCode (200); ajaxResponse.setMessage ("request response successful!"); return ajaxResponse } / / successful response of the request with query data (for data query interface) public static AjaxResponse success (Object obj) {AjaxResponse ajaxResponse = new AjaxResponse (); ajaxResponse.setIsok (true); ajaxResponse.setCode (200); ajaxResponse.setMessage ("request response successful!"); ajaxResponse.setData (obj); return ajaxResponse } / / successful response with query data (for data query interface) public static AjaxResponse success (Object obj,String message) {AjaxResponse ajaxResponse = new AjaxResponse (); ajaxResponse.setIsok (true); ajaxResponse.setCode (200); ajaxResponse.setMessage (message); ajaxResponse.setData (obj); return ajaxResponse }} at this point, I believe you have a deeper understanding of "how to develop a RESTful interface with spring annotations". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.