架构实战篇(三)-Spring Boot架构搭建RESTful API案例

轻松写代码 2018-02-08 14:00:06 ⋅ 689 阅读


前言

上一篇分享了Spring Boot 整合Swagger 让API可视化前后端分离架构 受到了大家一致好评 ,本节就接着上节的代码做了详细的查询代码的补充和完善并搭建RESTful API架构案例。

注意: 本节代码都是在上节代码的基础上追加的内容,如果需要源码的可以去看上节内容或者关注我们的公众号,回复 MyBatis(二) 和你的邮箱地址,我们发送给你。

点我!传送到上节 - 架构实战篇(二)-Spring Boot整合Swagger,让你的API可视化

我们先看下已经完成的项目结构图

项目结构

如果看过上节文章的同学应该注意到Code 和 Result 怎么没有了?那是因为为了节省篇幅我们用Spring提供的ResponseEntity 类代替了

最终运行结果

最终运行结果

下面开始一步一步的编写代码了

增加Spring boot的maven 依赖

在原有基础的pom结构中追加Swagger2的依赖

        <!-- swagger2-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.7.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.7.0</version>
        </dependency>

增加一个查询用的Form类

里面使用到了swagger 的注解

import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
import java.util.List;
public class HelpCategoryForm implements Serializable {    
// 查询条件@ApiModelProperty(value = "分类编号集合")    
private List<Integer> idList;    
@ApiModelProperty(value = "模糊查询分类名称")    
private String nameLike;    
@ApiModelProperty(value = "父类编号")    
private Integer parentId;    // 分页@ApiModelProperty(value = "第几页", example = "1")    
private Integer pageNum;    
@ApiModelProperty(value = "显示行数", example = "10")    
private Integer pageSize;    // 排序@ApiModelProperty(value = "排序", allowableValues = "help_category_id,name",            notes = "(后面空格追加 升序ASC, 降序DESC), 例如: name asc 或者 name desc")    
private String orderBy;        // 省略了get set 方法@Override    public String toString() {        
       return "HelpCategoryForm{" +                "idList=" + idList +                ", nameLike='" + nameLike + '\'' +                ", parentId=" + parentId +                ", orderBy='" + orderBy + '\'' +                ", pageNum=" + pageNum +                ", pageSize=" + pageSize +                '}';    } }

增加两个查询语句

<select id="selectList" resultMap="BaseResultMap" parameterType="com.example.model.HelpCategoryForm">
    select help_category_id, name, parent_category_id, url from help_category    <where>
      <if test="idList != null">
        and help_category_id in        
<foreach collection="idList" open="(" separator="," close=")" item="id">          #{id}        
</foreach>      </if>      <if test="nameLike != null">        and name like concat(#{nameLike}, '%')      </if>      <if test="parentId != null">        and parent_category_id = #{parentId}      </if>    </where>  </select>  <select id="selectById" resultMap="BaseResultMap" parameterType="int">    select help_category_id, name, parent_category_id, url from help_category WHERE help_category_id = #{id}  </select>

Mapper 的修改

import com.example.model.HelpCategory;
import com.example.model.HelpCategoryForm;
import org.springframework.stereotype.Repository;
import java.util.List;@Repository

public interface HelpCategoryMapper {    
List<HelpCategory> selectList(HelpCategoryForm form);    
   HelpCategory selectById(Integer id); }

编写服务层代码

这边用到了github的pagehelper工具类,他会去找你的类中有没有pageNum,pageSize,orderBy属性,所以命名上不要自己太个性化了

import com.example.model.HelpCategory;
import com.example.mapper.HelpCategoryMapper;
import com.example.model.HelpCategoryForm;
import com.example.service.HelpCategoryService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Servicepublic class HelpCategoryServiceImpl implements HelpCategoryService {    
   @Autowired    private HelpCategoryMapper helpCategoryMapper;    
   @Override    public List<HelpCategory> selectList(HelpCategoryForm form) {        PageHelper.startPage(form);        
   return helpCategoryMapper.selectList(form);    }    
   @Override    public HelpCategory selectById(Integer id) {        
       return helpCategoryMapper.selectById(id);    } }

API 接口

import com.example.model.HelpCategory;
import com.example.model.HelpCategoryForm;
import com.example.service.HelpCategoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;@Api(value = "帮助类别", description = "帮助类别")@RestController@RequestMapping("help/category")
public class HelpCategoryController {    
@Autowired    private HelpCategoryService helpCategoryService;    
// 注意:GET 请求不支持 RequestBody 注解    @ApiOperation("列表查询")    
@RequestMapping(value = "/", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")    
public ResponseEntity<List<HelpCategory>> list(@RequestBody HelpCategoryForm form) {        List<HelpCategory> list = helpCategoryService.selectList(form);        
   return ResponseEntity.ok(list);    }    
@ApiOperation("详情查询")    
@ApiResponses({          
 @ApiResponse(code = 404, message = "分类不存在", response = Void.class)    })    
 @RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")    
 public ResponseEntity<HelpCategory> detail(@PathVariable("id") Integer id) {        HelpCategory category = helpCategoryService.selectById(id);        // 如果分类不存在返回编码 404        if(category == null)
     return ResponseEntity.status(HttpStatus.NOT_FOUND).build();        
     return ResponseEntity.ok(category);    } }

注意:GET 请求不支持 RequestBody 注解

程序的入口处有所调整,增加了一个api入口方便访问

import io.swagger.annotations.ApiOperation;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@SpringBootApplication
@RestController

public class Application {    
@ApiOperation("Hello World")    
@RequestMapping(value = "/", method = RequestMethod.GET)    
public String index() {        
return "Hello Spring Boot";    }    @ApiOperation("API接口")    
@RequestMapping(value = "/api", method = RequestMethod.GET)    
public void api(HttpServletResponse response) throws IOException {        response.sendRedirect("swagger-ui.html");    }    
public static void main(String[] args) {        SpringApplication.run(Application.class, args);    } }

到这里所有的类都编写完了,好了见证奇迹的时候到了

让我们打开浏览器地址栏访问
http://localhost:8081/demo/api

测试列表查询


列表查询

点击Try it out!

{  "idList": [    1,2,3,4,5,6,7,8,9,10,11,12
  ],  "nameLike": "P",  "orderBy": "help_category_id desc",  "pageNum": 1,  "pageSize": 10,  "parentId": 33}

查看下结果


查询结果

测试详情查询


详情查询

点击Try it out!

查询结果


查询结果

测试下不存在的分类
输入一个不存在的分类编号:1111111 点击查询返回404说明成功


image.png

404

你的运行结果对了吗?

更多精彩内容请关注“IT实战联盟”公众号吧!







全部评论: 0

    我有话说:

    架构实战(一)-Spring Boot+MyBatis基础架构

    Spring的追求一定是简单点简单点,让java的开发变得更加简单、容易。瞧瞧的告诉你们直接copy就能用哦~~~

    码云推荐:一个优秀的分布式spring boot/Spring Cloud API限流框架,特别适合微服务架构

    一个优秀的分布式spring boot/Spring Cloud API限流框架,特别适合微服务架构.

    架构实战(十七):Spring Boot Assembly 整合 thymeleaf

    如何让服务器上的 sprig boot 项目升级变的方便快捷

    架构实战(六):Spring Boot RestTemplate的使用

    RestTemplate是Spring提供的用于访问Rest服务的客户端,RestTemplate提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率。

    架构实战(七):Spring Boot Data JPA 快速入门

    Spring Data JPA 是Spring Data 的一个子项目,它通过提供基于JPA的Repository极大了减少了操作JPA的代码。

    SpringBoot+zk+dubbo架构实践(一):本地部署zookeeper

    SpringBoot+zk+dubbo架构实践系列实现目标:自己动手微服务架构

    SpringBoot+zk+dubbo架构实践):部署Dubbo-admin管理平台

    本系列架构实践不做深入探讨,主旨是带领大家能够快速踏入微服务架构门槛,能够轻松的一套属于自己的微服务架构。——写代码我们是认真滴!

    SpringBoot+zk+dubbo架构实践(二):SpringBoot 集成 zookeeper

    不啰嗦,本完成两件事:1、SpringBoot 框架;2、基于spring boot框架访问zookeeper。

    架构实战(十五):Spring Boot 解耦之事件驱动

    通过使用spring 事件来解决业务代码的耦合

    架构实战(五):Spring Boot 表单验证和异常处理

    为了让API 能够更好的提供服务,表单数据验证和异常的处理是必不可少的,让我们来看看怎么处理......

    架构实战(十一):Spring Boot 集成企业级搜索引擎 SolrCloud

    Solr是以Lucene为基础实现的文本检索应用服务。Solr部署方式有单机方式、多机Master-Slaver方式、Cloud方式。

    微服务架构实战(六):Spring boot2.x 集成阿里大鱼短信接口详解与Demo

    Spring boot2.x 集成阿里大鱼短信接口,发送短信验证码及短信接口详解。

    架构实战(十):Spring Boot Logback 邮件通知

    日志对于应用程序来说是非常重要的,当你的程序报错了,而你又不知道是多么可怕的一件事情,本文使用logback把程序报错信息邮件到开发者

    SpringBoot+zk+dubbo架构实践(四):sb+zk+dubbo框架(内附源码GitHub地址)

    案例模拟了一个provider服务提供方和PC、Web两个服务消费方内附GitHub源码......

    微服务架构网站扫码登录的功能设计

    微信扫码登录大家都是应用比较多的登录方式了,现在大的购物网站像京东、淘宝等都支持使用APP扫码登录网站了。今天就用APP扫码登录网站的实例来举例说明微服务架构过程。

    架构实战(二)-Spring Boot整合Swagger,让你的API可视化

    你还在跟前端对接上花费很多的时间而没有效果吗?你还在为写接口文档而烦恼吗?今天就教大家一个接口对接神器...

    微服务架构学习笔记:gRPC Spring Boot Starter 2.2.0 发布,及使用步骤

    gRPC Spring Boot Starter 项目是一个 gRPC 的 Spring Boot 模块。内嵌一个 gRPC Server 对外提供服务,并支持 Spring Cloud 的服务发现