【发布时间】:2018-02-01 03:19:58
【问题描述】:
在 spring doc 中,我可以得到以下关于 spring mvc 和 spring rest 区别的解释。 Spring REST 架构也是基于 Spring MVC,在 View 部分略有不同。传统的 Spring MVC 依赖 View 技术来渲染模型数据,Spring REST 架构也是如此,只是模型对象直接设置为 HTTP 响应,@ResponseBody 自动将其转换为 JSON/XML。 RESTful Web 服务的输出必须是 JSON 或 XML,这是一种可以在不同的消费者应用程序平台上轻松处理的标准格式。
但是在https://en.wikipedia.org/wiki/Representational_state_transfer。 除了 json 响应之外,它还有一些功能,其余的将使用 HTTP PUT/DELETE/POST 方法来操作资源。
我想知道是否可以将以下弹簧控制器视为一项宁静的服务。我使用@RestController 来返回json 响应,但没有使用任何其他的rest 功能。
@RestController
@RequestMapping(value = "/employee")
public class EmployeeController {
@RequestMapping(value = RequestAction.LOADLIST, method = RequestMethod.POST)
public List<Employee> list(@RequestBody Employee bo) {
System.out.println(bo);
return employeeList;
}
@RequestMapping(value = RequestAction.LOAD, method = RequestMethod.POST)
public Employee getEmployee(
@RequestBody Employee input) {
for (Employee employee : employeeList) {
if (employee.getId().equals(input.getId())) {
return employee;
}
}
return input;
}
@RequestMapping(value = RequestAction.ADD, method = RequestMethod.POST)
public Employee addEmployee(@RequestBody Employee bo) {
System.out.println(bo);
return bo;
}
@RequestMapping(value = RequestAction.UPDATE, method = RequestMethod.POST)
public Employee updateEmployee(@RequestBody Employee bo) {
System.out.println(bo);
for (Employee employee : employeeList) {
if (employee.getId().equals(bo.getId())) {
employee.setName(bo.getName());
return employee;
}
}
return bo;
}
}
【问题讨论】:
-
您似乎将 设计模式 (REST) 与可用于实现 REST 或许多其他工具的 工具 (Spring) 混淆了模式。你当然可以在 Spring 中实现 REST,但我注意到你的例子不是一个好例子——你使用一堆自定义 URI 来描述动作而不是使用 HTTP 动词(例如,
updateEmployee应该是 @ 987654325@). -
你可以使用 Spring 实现 RESTFUL API,为了让你的控制器更加安静,你可以遵循 REST 模型,你可以参考martinfowler.com/articles/richardsonMaturityModel.html
标签: java spring rest spring-mvc restful-architecture