SpringBoot2.x【六】整合 Rest API 接口规范

SpringBoot2.x【六】整合 Rest API 接口规范

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

1.REST简短介绍

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

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

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

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

2.准备工做

项目的环境工具web

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

项目结构图spring

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> createPrimaryKey(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/apiapi

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

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

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
GitHub:github.com/cuifuan/spr…
实体层和mapper.xml代码都是能够自动生成的
教程导航:mp.weixin.qq.com/s/T1gdEYWD6…

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来完成,哈哈,这个只是一个开发的设计风格

相关文章
相关标签/搜索