资源(Resource)资源的表述(Representation)状态转移(State Transfer)统一接口(Uniform Interface)超文本驱动(Hypertext Driven)6 个主要特性:面向资源(Resource Oriented)可寻址(Addressability)连通性(Connectedness)无状态(Statelessness)统一接口(Uniform Interface)超文本驱动(Hypertext Driven)具体这里就不一一展开,详见 http://www.infoq.com/cn/articles/understanding-restful-style2.Spring 对 REST 支持实现CityRestController.java 城市 Controller 实现 Restful HTTP 服务具体 Service 、dao 层实现看代码GitHub https://github.com/JeffLi1993/springboot-learning-example/tree/master/springboot-restful代码详解:@RequestMapping 处理请求地址映射。method – 指定请求的方法类型:POST/GET/DELETE/PUT 等value – 指定实际的请求地址consumes – 指定处理请求的提交内容类型,例如 Content-Type 头部设置application/json, text/htmlproduces – 指定返回的内容类型@PathVariable URL 映射时,用于绑定请求参数到方法参数@RequestBody 这里注解用于读取请求体 boy 的数据,通过 HttpMessageConverter 解析绑定到对象中3.HTTP 知识补充GET 请求获取Request-URI所标识的资源POST 在Request-URI所标识的资源后附加新的数据HEAD 请求获取由Request-URI所标识的资源的响应消息报头PUT 请求服务器存储一个资源,并用Request-URI作为其标识DELETE 请求服务器删除Request-URI所标识的资源TRACE 请求服务器回送收到的请求信息,主要用于测试或诊断CONNECT 保留将来使用OPTIONS 请求查询服务器的性能,或者查询与资源相关的选项和需求详情请看《JavaEE 要懂的小事:一、图解Http协议》
123456789101112131415161718192021222324252627282930 public
class
CityRestController {
@Autowired
private
CityService cityService;
@RequestMapping
(value =
"/api/city/{id}"
, method = RequestMethod.GET)
public
City findOneCity(
@PathVariable
(
"id"
) Long id) {
return
cityService.findCityById(id);
}
@RequestMapping
(value =
"/api/city"
, method = RequestMethod.GET)
public
List<City> findAllCity() {
return
cityService.findAllCity();
}
@RequestMapping
(value =
"/api/city"
, method = RequestMethod.POST)
public
void
createCity(
@RequestBody
City city) {
cityService.saveCity(city);
}
@RequestMapping
(value =
"/api/city"
, method = RequestMethod.PUT)
public
void
modifyCity(
@RequestBody
City city) {
cityService.updateCity(city);
}
@RequestMapping
(value =
"/api/city/{id}"
, method = RequestMethod.DELETE)
public
void
modifyCity(
@PathVariable
(
"id"
) Long id) {
cityService.deleteCity(id);
}
}
三、小结
Springboot 实现 Restful 服务,基于 HTTP / JSON 传输,适用于前后端分离。这只是个小demo,没有加入bean validation这种校验。还有各种业务场景。推荐:《 Springboot 整合 Mybatis 的完整 Web 案例》欢迎扫一扫我的公众号关注 — 及时得到博客订阅哦!— http://www.bysocket.com/ —— https://github.com/JeffLi1993 —
新闻热点
疑难解答