Spring MVC 4 RESTFul Web Services CRUD例子(带源码)【这才是restful,超经典】
【本系列其他教程正在陆续翻译中,点击分类:spring 4 mvc 进行查看。源码下载地址在文章末尾。】
【翻译 by 明明如月 QQ 605283073】
原文地址:http://websystique.com/springmvc/spring-mvc-4-restful-web-services-crud-example-resttemplate/上一篇:
Spring 4 MVC @RestController 注解实现REST Service
下一篇:Spring
MVC 4 文件上传下载 Hibernate+MySQL例子 (带源码)
详解:
本文非常好,推荐大家好好看看,很多人理解的restful不对
本文我们将使用Spring
MVC 4实现 CRUD Restful WebService , 通过RestTemplate写一个 REST 客户端,定义这些服务. 我们也可以通过外部的一些客户端来测试这些服务。
简短 & 快速介绍REST
REST表示 Representational State Transfer(表示性状态转换).它是可以用来设计web services的框架,可以被不同的客户端调用。
核心思想是:使用简单的HTTP协议来实现调用,而不是CORBA, RPC 或者 SOAP等负责的机制。
在Rest 基础设计中,资源使用以下动词进行操作。
- 创建资源 : 使用 HTTP POST
- 获取资源 : 使用 HTTP GET
- 更新资源 : 使用 HTTP PUT
- 删除资源 : 使用 HTTP DELETE
尽管没有限制必须返回的类型,但是一般基于Web services的Rest返回JSON或者XML作为响应。
客户端可以指定(使用HTTP Accept header)他们想要的资源类型吗,服务器返回需要的资源。
指明资源的Content-Type。如果想详细的理解 restful可以参考这里:StackOverflow link
基于Rest的Controller(控制器)
我们的 REST API :
- GET 方式请求 /api/user/ 返回用户列表
- GET 方式请求 /api/user/1返回id为1的用户
- POST 方式请求 /api/user/ 通过user对象的JSON 参数创建新的user对象
- PUT 方式请求 /api/user/3 更新id为3的发送json格式的用户对象
- DELETE 方式请求/api/user/4删除 ID为 4的user对象
- DELETE 方式请求/api/user/删除所有user
package com.websystique.springmvc.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder;
import com.websystique.springmvc.model.User;
import com.websystique.springmvc.service.UserService;
@RestController
public class HelloWorldRestController {
@Autowired
UserService userService; //Service which will do all data retrieval/manipulation work
//-------------------Retrieve All Users--------------------------------------------------------
@RequestMapping(value = "/user/", method = RequestMethod.GET)
public ResponseEntity<List<User>> listAllUsers() {
List<User> users = userService.findAllUsers();
if(users.isEmpty()){
return new ResponseEntity<List<User>>(HttpStatus.NO_CONTENT);//You many decide to return HttpStatus.NOT_FOUND
}
return new ResponseEntity<List<User>>(users, HttpStatus.OK);
}
//-------------------Retrieve Single User--------------------------------------------------------
@RequestMapping(value = "/user/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<User> getUser(@PathVariable("id") long id) {
System.out.println("Fetching User with id " + id);
User user = userService.findById(id);
if (user == null) {
System.out.println("User with id " + id + " not found");
return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<User>(user, HttpStatus.OK);
}
//-------------------Create a User--------------------------------------------------------
@RequestMapping(value = "/user/", method = RequestMethod.POST)
public ResponseEntity<Void> createUser(@RequestBody User user, UriComponentsBuilder ucBuilder) {
System.out.println("Creating User " + user.getName());
if (userService.isUserExist(user)) {
System.out.println("A User with name " + user.getName() + " already exist");
return new ResponseEntity<Void>(HttpStatus.CONFLICT);
}
userService.saveUser(user);
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/user/{id}").buildAndExpand(user.getId()).toUri());
return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
}
//------------------- Update a User --------------------------------------------------------
@RequestMapping(value = "/user/{id}", method = RequestMethod.PUT)
public ResponseEntity<User> updateUser(@PathVariable("id") long id, @RequestBody User user) {
System.out.println("Updating User " + id);
User currentUser = userService.findById(id);
if (currentUser==null) {
System.out.println("User with id " + id + " not found");
return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
}
currentUser.setName(user.getName());
currentUser.setAge(user.getAge());
currentUser.setSalary(user.getSalary());
userService.updateUser(currentUser);
return new ResponseEntity<User>(currentUser, HttpStatus.OK);
}
//------------------- Delete a User --------------------------------------------------------
@RequestMapping(value = "/user/{id}", method = RequestMethod.DELETE)
public ResponseEntity<User> deleteUser(@PathVariable("id") long id) {
System.out.println("Fetching & Deleting User with id " + id);
User user = userService.findById(id);
if (user == null) {
System.out.println("Unable to delete. User with id " + id + " not found");
return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
}
userService.deleteUserById(id);
return new ResponseEntity<User>(HttpStatus.NO_CONTENT);
}
//------------------- Delete All Users --------------------------------------------------------
@RequestMapping(value = "/user/", method = RequestMethod.DELETE)
public ResponseEntity<User> deleteAllUsers() {
System.out.println("Deleting All Users");
userService.deleteAllUsers();
return new ResponseEntity<User>(HttpStatus.NO_CONTENT);
}
}详解:
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。
- 上一篇: 利用session完成用户登录与注销
- 下一篇: Yii2 使用 RESTful 写API接口 实例
copyright © 2008-2019 亿联网络 版权所有 备案号:粤ICP备14031511号-2
