请先戳此处按照教程创建一个项目 [如果你只是想简单的入门,只需浏览完 初始化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"
}

传递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")
}

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