我们知道Ultimate的Idea可以用图形界面下直接创建SpringBoot项目,而社区版的则不提供。本文用最简洁的方式说明使用社区版的Idea创建Gradel + SpringBoot项目,并编写MVC和调试的完整过程。
编码
创建项目
利用https://start.spring.io/ 创建Spring BootGradle项目:
点击【Generate Project】下载RestfulApi.zip并解压到空目录E:\TQ\svn\ui\private\gophern\study\StudyInIdea\RestfulApi
在Idea中导入项目,Import Project >> Create project from existing sources
E:\TQ\svn\ui\private\gophern\study\StudyInIdea\RestfulApi\RestfulApi
为了连接本机的MongoDB服务,编辑src/resources/application.properties,加入以下内容:
|
创建模型或者实体类
项目右键 >> New >> Java Class 类:gophern.study.springboot.model.Product
package gophern.study.springboot.model; |
创建对象模型的操作接口
package gophern.study.springboot.repository; |
创建控制器
新建类:gophern.study.springboot.controller.ProductController
启动
有2种方式启动Spring Boot MongoDB RESTful网站
l 方式1、运行RestfulApiApplication类
l 方式2、在控制台下执行
gradlew bootRun
测试
新增资料
curl -i -X POST -H "Content-Type: application/json" -d '{"prodName":"产品1 ","prodDesc":"产品1描述","prodPrice":100,"prodImage":"https://www.oschina.net/build/oschina/components/imgs/oschina.svg?t=1484580008000"}' http://localhost:8080/products |
curl -i -X POST -H "Content-Type: application/json" -d '{"prodName":"产品2 ","prodDesc":"产品2描述","prodPrice":100,"prodImage":"https://www.oschina.net/build/oschina/components/imgs/oschina.svg?t=1484580008000"}' http://localhost:8080/products |
查询产品列表
curl -i -H "Accept: application/json" localhost:8080/products |
HTTP/1.1 200 Content-Type: application/json;charset=UTF-8 Transfer-Encoding: chunked Date: Fri, 06 Apr 2018 16:24:07 GMT
数据格式整理如下: |
[ { "id": "5ac81809bd8cd1328099c087", "prodName": "产品1 ", "prodDesc": "产品1描述", "prodPrice": 100, "prodImage": "https://www.oschina.net/build/oschina/components/imgs/oschina.svg?t=1484580008000" }, { "id": "5ac81819bd8cd1328099c088", "prodName": "产品2 ", "prodDesc": "产品2描述", "prodPrice": 100, "prodImage": "https://www.oschina.net/build/oschina/components/imgs/oschina.svg?t=1484580008000" } ] |
获取单个产品
curl -i -H "Accept:application/json" localhost:8080/products/5ac7453bbd8cd1328099c085
修改资料
curl -i -X PUT -H "Content-Type:application/json" -d '{"prodPrice":220}' localhost:8080/products/5ac81819bd8cd1328099c088
可以看到价格由100变成了220。
删除
curl -i -X DELETE localhost:8080/products/5ac81819bd8cd1328099c088
附代码
代码下载