大致解释一下什么是RESTFul
Restful是一种软件架构风格,而不是标准,只是提供了一组设计原则和约束条件。它主要用于客户端和服务器交互类的软件。基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机制。如果一个架构符合REST原则,就称它为RESTful架构
接下来进入正题,创建三个Model类,详细代码如下
Reader
package com.zimug.bootlaunch.model;
import lombok.Data;
@Data
public class Reader {
private String name;
private int age;
}
Article
package com.moli.zy.springboot2ml.model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
import java.util.List;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Article {
private Long id;
private String author;
private String title;
private String content;
private Date createTime;
private List<Reader> reader;
}
AjaxResponse
package com.moli.zy.springboot2ml.model;
import lombok.Data;
@Data
public class AjaxResponse {
private boolean isok;
private int code;
private String message;
private Object data;
private AjaxResponse() {
}
public static AjaxResponse success() {
AjaxResponse resultBean = new AjaxResponse();
resultBean.setIsok(true);
resultBean.setCode(200);
resultBean.setMessage("success");
return resultBean;
}
public static AjaxResponse success(Object data) {
AjaxResponse resultBean = new AjaxResponse();
resultBean.setIsok(true);
resultBean.setCode(200);
resultBean.setMessage("success");
resultBean.setData(data);
return resultBean;
}
}
当前结构如图所示
创建一个Controller类
ArticleRestController
package com.moli.zy.springboot2ml.controller;
import com.moli.zy.springboot2ml.model.AjaxResponse;
import com.moli.zy.springboot2ml.model.Article;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import static org.springframework.web.bind.annotation.RequestMethod.*;
@Slf4j
@RestController
@RequestMapping("/rest")
public class ArticleRestController {
@RequestMapping(value = "/article", method = POST, produces = "application/json")
public AjaxResponse saveArticle(@RequestBody Article article) {
log.info("saveArticle:{}", article);
return AjaxResponse.success(article);
}
@RequestMapping(value = "/article/{id}", method = DELETE, produces = "application/json")
public AjaxResponse deleteArticle(@PathVariable Long id) {
log.info("deleteArticle:{}", id);
return AjaxResponse.success(id);
}
@RequestMapping(value = "/article/{id}", method = PUT, produces = "application/json")
public AjaxResponse updateArticle(@PathVariable Long id, @RequestBody Article article) {
article.setId(id);
log.info("updateArticle:{}", article);
return AjaxResponse.success(article);
}
@RequestMapping(value = "/article/{id}", method = GET, produces = "application/json")
public AjaxResponse getArticle(@PathVariable Long id) {
Article article1 = Article.builder().id(28L).author("ml").content("spring boot 2").title("aaa").build();
return AjaxResponse.success(article1);
}
}
这个Controller就是本篇的重点,接下来详细讲解一下这个类
类上有三个注解
@Slf4j
@RestController
@RequestMapping("/rest")
【@Slf4j】:
这个注解可以省去手动new一个用于打印日志的对象
【@RestController】:
这个注解相当于@ResponseBody、@Controller的结合体,意思就是如果使用@RestController注解,那么方法不能再返回页面,而是返回JSON,XML或自定义mediaType内容。我们这里需要类的所有方法返回JSON格式的数据,所以加上这个注解即可。如果你不想整个类的方法都被影响,那你可以这样做
@Controller
public class ArticleRestController {
public @ResponseBody AjaxResponse saveArticle() {
}
}
如上代码所示,类上用@Controller注解,然后给你需要返回JSON、XML数据的方法加上@ResponseBody注解即可
【@RequestMapping("/test")】:
这个注解就是映射一个路径,让我们可以访问到对应的方法,最终获得我们想要的东西。例如你本地跑了一个项目,想访问被这个注解修饰的类下的某一个方法,那么你浏览器的地址就应该填【127.0.0.1:8080/test/xxxxx】
接下来我们观察一下类中这四个方法上的@RequestMapping注解
@RequestMapping(value = "/article", method = POST, produces = "application/json")
@RequestMapping(value = "/article/{id}", method = DELETE, produces = "application/json")
@RequestMapping(value = "/article/{id}", method = PUT, produces = "application/json")
@RequestMapping(value = "/article/{id}", method = GET, produces = "application/json")
可以看到,这四条的映射路径“article”都一样,区别是method请求方式不同,这就是RESTFul风格,POST就代表"添加"这个操作,DELETE就代表"删除",PUT代表"修改",GET代表"获取"
RESTFul风格的好处:
1.看地址就知道要什么资源
2.看请求类型就知道针对资源干什么
3.看返回状态码就知道结果如何
方法上的注解 除了这种写法,还有更简便的写法
@RequestMapping(value = "/article", method = POST, produces = "application/json")
public @ResponseBody AjaxResponse saveArticle(@RequestBody Article article) {
return AjaxResponse.success(article);
}
还可以这样写,效果是一样的,更简洁
@PostMapping("/article")
public @ResponseBody AjaxResponse saveArticle(@RequestBody Article article) {
return AjaxResponse.success(article);
}
下面讲解一下方法形参的注解含义
观察下面这三个方法的形参
@PostMapping("/article")
public @ResponseBody AjaxResponse saveArticle(@RequestBody Article article) {
}
@PostMapping("/article")
public @ResponseBody AjaxResponse saveArticle(@RequestParam String id, @RequestParam String author) {
}
@DeleteMapping("/article/{id}")
public @ResponseBody AjaxResponse deleteArticle(@PathVariable Long id) {
}
@RequestBody
该注解常用来处理Content-Type: 不是application/x-www-form-urlencoded编码的内容,例如application/json, application/xml等;
它是通过使用HandlerAdapter 配置的HttpMessageConverters来解析post data body,然后绑定到相应的bean上的。
提交JSON、XML数据格式的数据时用这个注解
@RequestParam
1.常用来处理简单类型的绑定,通过Request.getParameter() 获取的String可直接转换为简单类型的情况( String–> 简单类型的转换操作由ConversionService配置的转换器来完成);因为使用request.getParameter()方式获取参数,所以可以处理get 方式中queryString的值,也可以处理post方式中 body data的值;
2.用来处理Content-Type: 为 application/x-www-form-urlencoded编码的内容,提交方式GET、POST;
3.该注解有两个属性: value、required; value用来指定要传入值的id名称,required用来指示参数是否必须绑定;
比如表单方式提交就用这个注解
@PathVariable
当使用@RequestMapping URI template 样式映射时, 即 someUrl/{paramId}, 这时的paramId可通过 @Pathvariable注解绑定它传过来的值到方法的参数上
该注解可以接收请求路径中占位符的值
最终的ArticleRestController代码
package com.moli.zy.springboot2ml.controller;
import com.moli.zy.springboot2ml.model.AjaxResponse;
import com.moli.zy.springboot2ml.model.Article;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
@Slf4j
@Controller
@RequestMapping("/rest")
public class ArticleRestController {
@PostMapping("/article")
public @ResponseBody AjaxResponse saveArticle(@RequestBody Article article) {
log.info("saveArticle:{}",article);
return AjaxResponse.success(article);
}
@DeleteMapping("/article/{id}")
public @ResponseBody AjaxResponse deleteArticle(@PathVariable Long id) {
log.info("deleteArticle:{}",id);
return AjaxResponse.success(id);
}
@PutMapping("/article/{id}")
public @ResponseBody AjaxResponse updateArticle(@PathVariable Long id, @RequestBody Article article) {
article.setId(id);
log.info("updateArticle:{}",article);
return AjaxResponse.success(article);
}
@GetMapping( "/article/{id}")
public @ResponseBody AjaxResponse getArticle(@PathVariable Long id) {
Article article1 = Article.builder().id(28L).author("ml").content("spring boot 2").title("aaa").build();
return AjaxResponse.success(article1);
}
}
到此本节教程结束,项目跑起来之后接口就可以正常访问了
这是我通过学习对知识的整理及备忘,本博客的所有内容,仅是自己的一些学习笔记,如有错误,欢迎指正。如有侵权,请告知修改。