夏梦,写最简洁有用的教程 ------ 欢迎关注
spring从3.0开始支持restful风格的项目,而springboot构建在spring之上,所以它继承了这个特性,在这之上它还新增了直接支持restful风格的注解,这几个注解分别为:
- @GetMapping —查询请求注解
- @PostMapping --新增请求注解
- @PutMapping --更新请求注解
- @DeleteMapping --删除请求注解
下面,开始介绍如何创建一个restful风格的项目
1,构建一个springboot项目
项目结构如下
2,创建controller控制器
创建一个名为ShowController的控制器,读者可根据需要自己更改
3,构建restful数据接口
package com.tmx.test.controller;
import com.tmx.test.domain.User;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/user")
public class ShowController {
@PostMapping
public void insertUser(@RequestBody User user){
System.out.println(user);
//.....连接数据库插入
}
@GetMapping
public void getUser(){
System.out.println("查询所有");
//....连接数据库查询---查询所有
}
@GetMapping("{id}")
public void getUserById(@PathVariable Integer id){
System.out.println(id);
//....连接数据库查询--根据id
}
@PutMapping
public void UpdateUser(@RequestBody User user){
System.out.println(user);
//.....连接数据库更新
}
@DeleteMapping("{id}")
public void deleteUser(@PathVariable Integer id){
System.out.println("删除");
//....连接数据库删除
}
}
到此,如果你已经看懂了,那就可以去实践了,实践了没问题就不用往下看了,下面是对接口的测试,有兴趣的话可以继续看
4,测试接口
测试工具:postman
4.1 测试查询请求接口
4.1.1 无参数
注意:请求方式为GET
访问连接为:http://localhost:8080/user
测试结果
4.1.2 带参数
注意:请求方式为GET
访问连接为:http://localhost:8080/user/1
测试结果
4.2 测试新增接口
注意:请求方式为POST
访问连接为:http://localhost:8080/user
数据格式:JSON
测试结果
4.3 测试更新接口
注意:请求方式为PUT
访问连接为:http://localhost:8080/user
数据格式:JSON
测试结果
4.4 测试删除接口
注意:请求方式为DELETE
访问连接为:http://localhost:8080/user
测试结果
教程到此结束。