几分钟写一个接口

2018-01-24  本文已影响24人  iceIC

请先戳此处按照教程创建一个项目 [如果你只是想简单的入门,只需浏览完 初始化SpringBoot 篇幅即可]

简单Demo

@Controller
@EnableAutoConfiguration
class Test {
    @RequestMapping("/")
    @ResponseBody
    fun home(request: HttpServletRequest): String {
        return "hello world!"
    }
}

fun main(args: Array<String>) {
    SpringApplication.run(Test::class.java, *args)
}

http://localhost:8080


POST请求

@RequestMapping(value = "/",method = arrayOf(RequestMethod.POST))
@ResponseBody
fun home(request: HttpServletRequest): String {
    return "hello world!"
}

RestFul

@RequestMapping(value = "/{name}")
@ResponseBody
fun home(@PathVariable name: String, request: HttpServletRequest): String {
    return "hello world ! $name"
}

http://localhost:8080/ice


请求参数

GET
@RequestMapping("/")
@ResponseBody
fun home(@RequestParam(defaultValue = "ice") name: String, request: HttpServletRequest): String {
    return "hello world ! $name"
}

http://localhost:8080/?name=IC

POST
@RequestMapping("/",method = arrayOf(RequestMethod.POST))
@ResponseBody
fun home(@RequestParam(defaultValue = "ice") name: String, request: HttpServletRequest): String {
    return "hello world ! $name"
}
image.png

传递JSON串

@RequestMapping("/", method = arrayOf(RequestMethod.POST))
@ResponseBody
fun home(@RequestBody loginBean: LoginBean, request: HttpServletRequest): String {
    return "$loginBean"
}
data class LoginBean(var account: String, var pwd: String){
    constructor() : this("ice","IC")
}
image.png

以上就是基本的写法了,如果有什么额外的需求,欢迎留言。


上一篇 下一篇

猜你喜欢

热点阅读