Spring Boot通过提供开箱即用的默认依赖或者转换来补充Spring REST支持。在Spring Boot中编写RESTful服务与SpringMVC没有什么不同。总而言之,基于Spring Boot的REST服务与基于Spring的REST服务完全相同,只是在我们引导底层应用程序的方式上有所不同。

1.REST简短介绍

REST代表Representational State Transfer. 是一种架构风格,设计风格而不是标准,可用于设计Web服务,可以从各种客户端使用.

基于REST的基本设计,其是根据一组动词来控制的操作

  • 创建操作:应使用HTTP POST
  • 查询操作:应使用HTTP GET
  • 更新操作:应使用HTTP PUT
  • 删除操作:应使用HTTP DELETE

作为REST服务开发人员或客户端,您应该遵守上述标准。

2.准备工作

项目的环境工具

  • SpringBoot 2.0.1.RELEASE
  • Gradle 4.7
  • IDEA 2018.2
  • MySQL5.7

项目结构图

3.开始

下面基于一种方式讲解Restful

package com.example.controller;

import com.example.beans.PageResultBean;
import com.example.beans.ResultBean;
import com.example.entity.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController
@RequestMapping("/user")
public class UserControllerAPI { private final UserService userService; @Autowired
public UserControllerAPI(UserService userService) {
this.userService = userService;
} @RequestMapping(value = "/api", method = RequestMethod.GET)
public PageResultBean<List<User>> getUserAll(PageResultBean page) {
return new PageResultBean<>(userService.getUserAll(page.getPageNo(), page.getPageSize()));
} @RequestMapping(value = "/api/{id}", method = RequestMethod.GET)
public ResultBean<User> getUserByPrimaryKey(@PathVariable("id") Integer id) {
return new ResultBean<>(userService.selectByPrimaryKey(id));
} @RequestMapping(value = "/api/{id}", method = RequestMethod.PUT)
public ResultBean<Integer> updateUserByPrimaryKey(@PathVariable("id") Integer id,User user) {
user.setId(id);
return new ResultBean<>(userService.updateByPrimaryKeySelective(user));
} @RequestMapping(value = "/api/{id}", method = RequestMethod.DELETE)
public ResultBean<String> deletePrimaryKey(@PathVariable("id") Integer id) {
return new ResultBean<>(userService.deleteByPrimaryKey(id));
} @RequestMapping(value = "/api", method = RequestMethod.POST)
public ResultBean<Integer> deletePrimaryKey(User user) {
return new ResultBean<>(userService.insertSelective(user));
} }
  • 对于/user/api HTTP GET来请求获取全部用户
  • 对于/user/api HTTP POST来创建用户
  • 对于/user/api/1 HTTP GET请求来获取id为1的用户
  • 对于/user/api/1 HTTP PUT请求来更新
  • 对于/user/api/1 HTTP DELETE请求来删除id为1的用户
HTTP GET请求/user/api 查询全部

URL:http://localhost:8080/user/api

HTTP GET请求/user/api/65 跟据id查询

URL:http://localhost:8080/user/api/65

HTTP POST请求/user/api 创建用户

URL:http://localhost:8080/user/api

HTTP PUT请求/user/api/65 来更新用户信息

URL:http://localhost:8080/user/api/65

HTTP DELETE请求/user/api/85 来删除id为85的用户

URL:http://localhost:8080/user/api/85

4.业务层及dao层代码

UserService.java 接口

package com.example.service;

import com.example.entity.User;

import java.util.List;

public interface UserService {

   /**
* 删除
* @param id
* @return
*/
String deleteByPrimaryKey(Integer id); /**
* 创建
* @param record
* @return
*/
int insertSelective(User record); /**
* 单个查询
* @param id
* @return
*/
User selectByPrimaryKey(Integer id); /**
* 更新
* @param record
* @return
*/
int updateByPrimaryKeySelective(User record); /**
* 查询全部
* @return
*/
List<User> getUserAll(Integer pageNum, Integer pageSize);
}

UserServiceImpl.java

package com.example.service.impl;

import com.example.dao.UserMapper;
import com.example.entity.User;
import com.example.service.UserService;
import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import java.util.List; @Service
public class UserServiceImpl implements UserService { private final static Logger logger = LoggerFactory.getLogger(UserServiceImpl.class); private final UserMapper userMapper; @Autowired(required = false)
public UserServiceImpl(UserMapper userMapper) {
this.userMapper = userMapper;
} /**
* 删除
*
* @param id
* @return
*/
@Transactional
@Override
public String deleteByPrimaryKey(Integer id) {
logger.info("UserServiceImpl deleteByPrimaryKey id => " + id);
User user = userMapper.selectByPrimaryKey(id);
String result;
if (user == null) {
result = "用户ID[" + id + "]找不到!";
} else {
result = String.valueOf(userMapper.deleteByPrimaryKey(id));
}
return result;
} /**
* 创建
*
* @param record
* @return
*/
@Transactional
@Override
public int insertSelective(User record) {
logger.info("UserServiceImpl insertSelective record=>"+record.toString());
return userMapper.insertSelective(record);
} /**
* 单个查询
*
* @param id
* @return
*/
@Override
public User selectByPrimaryKey(Integer id) {
logger.info("UserServiceImpl selectByPrimaryKey id=>"+id);
return userMapper.selectByPrimaryKey(id);
} /**
* 更新
*
* @param record
* @return
*/
@Override
public int updateByPrimaryKeySelective(User record) {
logger.info("UserServiceImpl updateByPrimaryKeySelective record=>"+record.toString());
return userMapper.updateByPrimaryKeySelective(record);
} /**
* 查询全部
*
* @param pageNum
* @param pageSize
* @return
*/
@Override
public List<User> getUserAll(Integer pageNum, Integer pageSize) {
logger.info("UserServiceImpl getUserAll pageNum=>"+pageNum+"=>pageSize=>"+pageSize);
PageHelper.startPage(pageNum,pageSize);
List<User> userList = userMapper.getUserAll();
logger.info("UserServiceImpl getUserAll userList"+userList.size());
return userList;
}
}

UserMapper.java

package com.example.dao;

import com.example.entity.User;

import java.util.List;

public interface UserMapper {
int deleteByPrimaryKey(Integer id); int insert(User record); int insertSelective(User record); User selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(User record); int updateByPrimaryKey(User record); List<User> getUserAll();
}

PageResultBean和ResultBean的代码在GitHub

https://github.com/cuifuan/springboot-demo

实体层和mapper.xml代码都是可以自动生成的,教程导航:

Spring全家桶系列--SpringBoot与Mybatis结合

4.理解RESTful

通过上面的编码,如果你已经走通了上面的代码,相信你已经对REST有了大致的掌握,时今当下的前端Client层出不穷,后端接口或许来自不同平台,这时候需要请求一批接口,而RESTful风格的api,使人从请求方式和地址一看就知道是要做什么操作,根据返回code状态就知道结果如何

使用RESTful直接带来的便利:

之前的接口

  • 删除 /user/delete
  • 添加 /user/create
  • 单个查询 /user/queryById
  • 查询全部 /user/queryAll
  • 更新 /user/update

采用RESTful设计API之后 /user/api一个URL地址解决,再也不用跟前端废舌头了,同时GET请求是幂等的,什么是幂等?简单通俗的说就是多次请求返回的效果都是相同的,例如GET去请求一个资源,无论请求多少次,都不会对数据造成创建修改等操作,PUT用来更新数据也是,无论执行多次的都是最终一样的效果

问题:使用PUT改变学生年龄并且这样做10次和做了一次,学生的年龄是相同的,是幂等的,那么如果POST做相同操作,那么它是如何不是幂等的?

答:因为POST请求会在服务端创建与请求次数相同的服务,假如服务端每次请求服务会存在一个密钥,那么这个POST请求就可能不是幂等的,也或许是幂等的,所以POST不是幂等的。

因为PUT请求URL到客户端定义的URL处完整地创建或替换资源,所以PUT是幂等的。 DELETE请求也是幂等的,用来删除操作,其实REST就是相当于一个风格规范。

注意了,GET请求请不要用在delete操作上,你要问我为啥不行,你偏要那么做,其实,整个CRUD操作你也都可以用GET来完成,哈哈,这个只是一个开发的设计风格。

Spring全家桶–SpringBoot Rest API的更多相关文章

  1. Spring全家桶——SpringBoot之AOP详解

    Spring全家桶--SpringBoot之AOP详解 面向方面编程(AOP)通过提供另一种思考程序结构的方式来补充面向对象编程(OOP). OOP中模块化的关键单元是类,而在AOP中,模块化单元是方 ...

  2. Spring全家桶——SpringBoot渐入佳境

    Spring全家桶系列--SpringBoot渐入佳境 萌新:小哥,我在实体类写了那么多get/set方法,看着很迷茫 小哥:那不是可以自动生成吗? 萌新:虽然可以自动生成,但是如果我要修改某个变量的 ...

  3. Spring全家桶系列–[SpringBoot入门到跑路]

    //本文作者:cuifuan Spring全家桶————[SpringBoot入门到跑路] 对于之前的Spring框架的使用,各种配置文件XML.properties一旦出错之后错误难寻,这也是为什么 ...

  4. Spring全家桶系列–SpringBoot渐入佳境

    //本文作者:cuifuan //本文将收录到菜单栏:<Spring全家桶>专栏中 首发地址:https://www.javazhiyin.com/20913.html 萌新:小哥,我在实 ...

  5. Spring全家桶系列–SpringBoot之AOP详解

    //本文作者:cuifuan //本文将收录到菜单栏:<Spring全家桶>专栏中 面向方面编程(AOP)通过提供另一种思考程序结构的方式来补充面向对象编程(OOP). OOP中模块化的关 ...

  6. Spring全家桶一一SpringBoot与Mybatis

    Spring全家桶系列一一SpringBoot与Mybatis结合 本文授权"Java知音"独家发布. Mybatis 是一个持久层ORM框架,负责Java与数据库数据交互,也可以 ...

  7. 10分钟详解Spring全家桶7大知识点

    Spring框架自2002年诞生以来一直备受开发者青睐,它包括SpringMVC.SpringBoot.Spring Cloud.Spring Cloud Dataflow等解决方案.有人亲切的称之为 ...

  8. 一文解读Spring全家桶 (转)

    Spring框架自2002年诞生以来一直备受开发者青睐,它包括SpringMVC.SpringBoot.Spring Cloud.Spring Cloud Dataflow等解决方案.有人亲切的称之为 ...

  9. 【转】Spring全家桶

    Spring框架自诞生以来一直备受开发者青睐,有人亲切的称之为:Spring 全家桶.它包括SpringMVC.SpringBoot.Spring Cloud.Spring Cloud Dataflo ...

随机推荐

  1. day13_雷神_前端01

    #前端 html 服务器端返回的就是一个字符串,浏览器根据html规则去渲染这个字符串. html 是超文本标记语言,相当于定义统一的一套规则,大家都遵守它,这样就可以让浏览器根据标记语言的规则去解释 ...

  2. PHPCMS9.6.0最新版SQL注入和前台GETSHELL漏洞分析 (实验新课)

    PHPCMS9.6.0最新版中,由于/modules/attachment/attachments.php的过滤函数的缺陷导致了可以绕过它的过滤机制形成SQL注入漏洞,可导致数据库中数据泄漏. 而且在 ...

  3. JavaScript中的三种弹出框的区别与使用

    JavaScript中有三种原生的弹出框,分别是alert.confirm.prompt.分别表示弹出框.确认框.信息框. 以下是示例代码: <!DOCTYPE html> <htm ...

  4. [CocoaPods]pod安装与pod更新

    简介 许多以CocoaPods开头的人似乎认为pod install只在第一次使用CocoaPods设置项目时使用,pod update之后才会使用.但事实并非如此. 本指南的目的是解释何时使用pod ...

  5. Swift5 语言指南(五) 基本运算符

    一个运营商是一个特殊的符号,或者你使用来检查,更改或合并值的短语.例如,加法运算符(+)添加两个数字,如,和逻辑AND运算符()组合两个布尔值,如.let i = 1 + 2&&if  ...

  6. 用O(1)的时间复杂度删除单链表中的某个节点

    给定链表的头指针和一个结点指针,在O(1)时间删除该结点.链表结点的定义如下: struct ListNode { int m_nKey; ListNode* m_pNext; }; 函数的声明如下: ...

  7. Win10手记-IIS部署网站问题解决

    最近在自己的Win10电脑上尝试部署ASP.NET网站时出现了问题,经过多方查找定位到IIS为问题来源. 开始之前 先描述下技术环境: 1.Windows 10 PC 2.Windows 自带的IIS ...

  8. app测试环境搭建(python)

    app测试环境的搭建大致如下几个: 1.appium安装 appium-server或者使用appium-desktop都可以,前者已经不再更新 下载地址:appium.io 2.Android SD ...

  9. 服务端如何安全获取客户端请求IP地址

    服务端如何获取客户端请求IP地址,网上代码一搜一大把.其中比较常见有x-forwarded-for.client-ip等请求头,及remote_addr参数,那么为什么会存在这么多获取方式,以及到底怎 ...

  10. 出现 The processing instruction target matching "[xX][mM][lL]" is not allowed错误

    错误原因与解决办法: 这个错误的原因是因为xml的开始有多余的空格造成的,只要把多余的空格删除就没有问题了. xml开始部分写注释也会出现此问题. 本文出自:艺意