欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringBoot学习笔记8-SpringBoot实现Restful

程序员文章站 2022-07-13 13:37:43
...

【Android免费音乐下载app】【佳语音乐下载】建议最少2.0.3版本。最新版本:
https://gitlab.com/gaopinqiang/checkversion/raw/master/Music_Download.apk

一、认识 Restful

Restful
一种互联网软件架构设计的风格,但它并不是标准,它只是提出了一组客户端和服务器交互时的架构理念和设计原则,基于这种理念和原则设计的接口可以更简洁,更有层次;
REST这个词,是Roy Thomas Fielding在他2000年的博士论文中提出的;
如果一个架构符合REST原则,就称它为Restful架构;

比如:
我们要访问一个http接口:http://localhost:80080/api/order?id=1521&status=1
采用Restful风格则http地址为:http://localhost:80080/api/order/1021/1

二、SpringBoot开发Restful
Spring boot开发Restful 主要是几个注解实现:

  • 1、@PathVariable(最重要)

    获取url中的数据;该注解是实现Restful最主要的一个注解;

  • 2、增加 post方法

    PostMapping;接收和处理Post方式的请求;

  • 3、删除 delete方法

    DeleteMapping;接收delete方式的请求,可以使用GetMapping代替;

  • 4、修改 put方法

    PutMapping;接收put方式的请求,可以用PostMapping代替;

  • 5、查询 get方法

    GetMapping;接收get方式的请求;

示例演示:
在controller包下创建一个RestfulController

package com.springboot.web.controller;

import com.springboot.web.model.User;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RestfulController {
	@RequestMapping("/user/{id}")
	public Object getUser(@PathVariable("id") Integer id){
		System.out.println("id = " + id );
		User user = new User();
		user.setId(id);
		return user;
	}
	
	@RequestMapping("/user/{id}/{name}")
	public Object getUser(@PathVariable("id") Integer id,@PathVariable("name") String name){
		System.out.println("id = " + id + " || name = " + name);
		User user = new User();
		user.setName(name);
		user.setId(id);
		return user;
	}
}

运行截图如下:
SpringBoot学习笔记8-SpringBoot实现Restful

注意:如果@RequestMapping中的参数个数和类型一样,但是顺序不一样。请求会出现问题。
比如:@RequestMapping("/user/{id}/{age}") 和 @RequestMapping("/user/{age}/{id}") ,会报一个下面的异常。

java.lang.IllegalStateException: Ambiguous handler methods mapped for ‘/user/123/12’: {public java.lang.Object com.springboot.web.controller.RestfulController.getUser(java.lang.Integer,java.lang.String), public java.lang.Object com.springboot.web.controller.RestfulController.getUser2(java.lang.Integer,java.lang.Integer)}

三、SpringBoot 热部署插件(spring-boot-devtools)
在实际开发中,我们修改某些代码逻辑功能或页面都需要重启应用,这无形中降低了开发效率;
热部署是指当我们修改代码后,服务能自动重启加载新修改的内容,这样大大提高了我们开发的效率;
Spring boot热部署通过添加一个插件实现;

插件为:spring-boot-devtools,在Maven中配置如下:

	<!-- springboot 开发自动热部署 -->
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-devtools</artifactId>
		<optional>true</optional>
	</dependency>

该热部署插件在实际使用中会有一些小问题,明明已经重启,但没有生效,这种情况下,手动重启一下程序;