美文网首页
Spring Boot + Kotlin,快速构建RESTful

Spring Boot + Kotlin,快速构建RESTful

作者: KwokKwok | 来源:发表于2018-05-10 16:24 被阅读153次

对相同的url进行GETPOSTPUTDELETE操作,并根据操作的不同返回JSON类型的对象或提示信息

文章结构如下:

  1. 创建Spring Boot项目
  2. 返回值(一个普通的Bean类,和一个提示信息类。
  3. 路由处理
  4. 全局异常处理
  5. 附录(git

环境:Win10+IDEA 2018.1

一、创建项目

选择Spring Initializr 配置名称、语言、项目类型等 依赖,只选一个Web即可 项目目录 选中auto-import,自动导包

二、返回值处理

正常的Bean类

data class Person(val name: String, val age: Int, val isMale: Boolean)

提示信息类

data class Result(val code: Int, val message: String) {
    constructor(status: ResultStatus) : this(status.code, status.message)
}

提示信息枚举,这里暂时只写了三种提示

enum class ResultStatus(val code: Int, val message: String) {
    DELETE_SUCCESS(204, "删除成功"),
    NOT_FOUND(404, "找不到对应的资源"),
    UNKNOWN_ERROR(500, "未知错误"),
}

三、路由处理

注解解释:

  1. @RestController,相当于@ResponseBody+@Controller
  2. @RequestMapping(),路由匹配,写在类上则表示整个类都以该路由为基础。
  3. @GetMapping等四个以请求方法开头的注解,相当于指定了请求方式的@RequestMapping
  4. @PathVariable,路径参数,匹配路径中{}包含的字段
  5. @RequestBody,将所有请求参数作为JSON解析,映射到匹配的实例中。前端可以直接提交一个JSON对象作为请求数据,请求的Content-Type需为application/json

参数解释:

  1. response: HttpServletResponse,响应对象,不需要可以不写。同理还有请求对象request:HttpServletRequest。(对象命名没有规定
@RestController
@RequestMapping("/persons")
class PersonController {

    //可以直接返回
    @GetMapping  //查找所有,GET访问 `http://localhost:8080/persons`
    fun getAll(): Any = persons

    //直接返回可省略返回类型,因为可以自动推断返回值;另外注意路径变量的写法
    @GetMapping("/{index}") 
    fun get(@PathVariable index: Int) = persons[index]

    //前端提交JSON对象,可以使用RequestBody解析。提交成功后,将响应码的状态码设置为201
    @PostMapping
    fun save(@RequestBody person: Person, response: HttpServletResponse): Any {
        persons.add(person)
        response.status = 201
        return person
    }

    //put修改。修改成功后,将响应码的状态码设置为201
    @PutMapping("/{index}")
    fun modify(@RequestBody person: Person, @PathVariable index: Int, response: HttpServletResponse): Any {
        //判断,返回错误码
        if (index >= persons.count()) {
            response.status = 404
            return Result(ResultStatus.NOT_FOUND)
        }
        persons[index] = person
        response.status = 201
        return persons[index]
    }

    //delete删除。删除成功后,将响应码的状态设置为204
    @DeleteMapping("/{index}")
    fun delete(@PathVariable index: Int, response: HttpServletResponse): Any {
        persons.removeAt(index)
        response.status = 204
        return Result(ResultStatus.DELETE_SUCCESS)
    }

    companion object {
        //数据源
        private val persons = MutableList(4, { index -> Person("Person$index", 20 + index, index % 2 == 0) })
    }
}

四、全局异常处理

捕获全局的异常进行处理。可以将其写入日志,或是对异常做类型判断,返回更详细的信息。

@ControllerAdvice
class ExceptionHandler {

    @ExceptionHandler(value = [Exception::class])
    @ResponseBody
    fun error(e: Exception, response: HttpServletResponse): Any {
        response.status = 500
        return Result(ResultStatus.UNKNOWN_ERROR)
    }
}

五、附录

访问路径及方法(基础域名:http://localhost:8080):

  1. 查找所有,GET访问 /persons
  2. 查找指定索引为2的(数字大可触发全局异常处理逻辑),GET访问 /persons/2
  3. 增加一个,POST访问 /persons
  4. 修改指定索引为2的实例,PUT访问 /persons/2
  5. 修改指定索引为2的实例,DELETE访问 /persons/2

需要项目代码请访问Git仓库地址

相关文章

网友评论

      本文标题:Spring Boot + Kotlin,快速构建RESTful

      本文链接:https://www.haomeiwen.com/subject/qextdftx.html