【学习笔记 - Spring Boot】04 - Spring Boot整合Web开发
1. 返回json数据
2. 静态资源访问
3. 文件上传
4. 异常处理
5. 自定义错误页
6. 跨域资源共享 CORS支持
7. 注册拦截器
1. 返回json数据
Spring Boot的spring-boot-starter-web
的依赖中已经默认加入了jackson-databind作为json处理器,此时不需要添加额外的处理器就能返回一段json数据了。主流的json解析工具有jackson,Goole的Gson
,阿里巴巴的fastjson
示例
- 使用默认的jackson
1.创建实体类 Person.java
package com.chapter04.bean;
import lombok.Getter;
import lombok.Setter;
public class Person {
public Person(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
@Getter @Setter
private int id;
@Getter @Setter
private String name;
@Getter @Setter
private int age;
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
2.创建PersonController.java
@RestController
public class PersonController {
@RequestMapping("/person")
@ResponseBody
public Person person(){
return new Person(1, "AlanLee", 22);
}
}
3.浏览器访问地址http://localhost:8080/person
即可得到json数据
{
"id":1,"name":"AlanLee","age":22}
上面的实体类使用了lombok插件,起到简化实体类的作用,比如使用@Setter和@Getter注解代替了setter方法和getter方法。
使用lombok的方法(不想使用这种方法的可以跳过此步骤)
1.添加依赖
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
<scope>provided</scope>
</dependency>
2.在IntelliJ IDEA中安装lombok插件
3.在实体类中的字段上面添加注解。(具体注解的用法请百度)
- 使用Gson
1.添加Gson依赖、排除默认的jackson-databind
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.1.9.RELEASE</version>
<!--排除jackson-databind-->
<exclusions>
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
- 代码与上面使用jackson的示例代码一样
- 使用fastjson
1.添加fastjson依赖、排除默认的jackson-databind
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.1.9.RELEASE</version>
<!--排除jackson-databind-->
<exclusions>
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</exclusion>
</exclusions>
</dependency