5.使用SpringBoot2.X开发第一个json接口
1. 什么是SpringBoot,有什么用?
①一个web开发框架
②Servlet、SpringMVC
③简化配置
2. SpringBoot常见的交互使用方式
①后端接口直接返回页面,现在比较少,常见的传统IT公司用得比较多,配合模板引擎,由后端页面渲染返回。
②返回json数据,主流场景,互联网公司用得比较多。比如微服务接口、前后端分离项目、手机APP等,基本都是通过json交互。
3. 如何使用SpringBoot开发json接口
①@RestController注解
②return一个POJO对象(不能返回字符串)
【项目实战】
1.项目结构
2.项目代码
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>org.example</groupId>
<artifactId>springboot2</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
</pluginRepository>
</pluginRepositories>
</project>
VideoController.java
package com.chencheng.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
/**
* @Description: 视频控制器类
* @author: 陈程
* @date: 2022年04月07日 0:21
*/
//@Controller
@RestController
@RequestMapping("/video")
public class VideoController {
@RequestMapping("list")
public Object list() {
Map<String, String> map = new HashMap<>();
map.put("1", "小程视频");
map.put("2", "SpringBoot实战");
return map;
}
}
然后启动springboot,在浏览器中输入http://localhost:8080/video/list。
如果你的浏览器没有安装json格式插件,则返回不会被美化。
安装json格式插件:https://www.cnblogs.com/songyanan/p/9224347.html
补充
为什么要用@RestController而不用@Controller?
①@RestController可以返回json数据,但是@Controller不能返回json数据。
②@Controller不会序列化字符串,会出现404错误,所以一般应该用@RestController。
③RequestMapping(" ")后面跟访问路径。
喜欢的别忘关注我哦!(づ ̄3 ̄)づ╭❤~
新版SSM项目实战专栏:https://blog.csdn.net/cc20183885/category_11727294.html