Rest之路 -- 从第二个Rest application里面分析 Rest 方法
引言
在此之前,我们实现了第一个Rest application,通过分析她,我们了解了 Rest 程序的基本要素;这里,我们将会对第一个 Rest application 的功能进行扩充(实现 CRUD)。为了简化流程,我们依然采用文件的方式来模拟数据库操作。
第二个 Rest application
User
import java.io.Serializable; import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "user")
public class User implements Serializable { private int id;
private String name;
private String profession; public User(){} public User(int id, String name, String profession){
this.id = id;
this.name = name;
this.profession = profession;
} public int getId() {
return id;
}
@XmlElement
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
@XmlElement
public void setName(String name) {
this.name = name;
}
public String getProfession() {
return profession;
}
@XmlElement
public void setProfession(String profession) {
this.profession = profession;
} @Override
public boolean equals(Object object){
if(object == null){
return false;
}else if(!(object instanceof User)){
return false;
}else {
User user = (User)object;
if(id == user.getId()
&& name.equals(user.getName())
&& profession.equals(user.getProfession())
){
return true;
}
}
return false;
}
}
Userdao
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List; public class UserDao {
public List<User> getAllUsers(){
List<User> userList = null;
try {
File file = new File("Users.dat");
if (!file.exists()) {
User user = new User(1, "Mahesh", "Teacher");
userList = new ArrayList<User>();
userList.add(user);
saveUserList(userList);
}
else{
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
userList = (List<User>) ois.readObject();
ois.close();
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return userList;
} public User getUser(int id){
List<User> users = getAllUsers(); for(User user: users){
if(user.getId() == id){
return user;
}
}
return null;
} public int addUser(User pUser){
List<User> userList = getAllUsers();
boolean userExists = false;
for(User user: userList){
if(user.getId() == pUser.getId()){
userExists = true;
break;
}
}
if(!userExists){
userList.add(pUser);
saveUserList(userList);
return 1;
}
return 0;
} public int updateUser(User pUser){
List<User> userList = getAllUsers(); for(User user: userList){
if(user.getId() == pUser.getId()){
int index = userList.indexOf(user);
userList.set(index, pUser);
saveUserList(userList);
return 1;
}
}
return 0;
} public int deleteUser(int id){
List<User> userList = getAllUsers(); for(User user: userList){
if(user.getId() == id){
int index = userList.indexOf(user);
userList.remove(index);
saveUserList(userList);
return 1;
}
}
return 0;
} private void saveUserList(List<User> userList){
try {
File file = new File("Users.dat");
FileOutputStream fos; fos = new FileOutputStream(file); ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(userList);
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
UserService
import java.io.IOException;
import java.util.List; import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.OPTIONS;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType; @Path("/UserService")
public class UserService { UserDao userDao = new UserDao();
private static final String SUCCESS_RESULT="<result>success</result>";
private static final String FAILURE_RESULT="<result>failure</result>"; @GET
@Path("/users")
@Produces(MediaType.APPLICATION_XML)
public List<User> getUsers(){
return userDao.getAllUsers();
} @GET
@Path("/users/{userid}")
@Produces(MediaType.APPLICATION_XML)
public User getUser(@PathParam("userid") int userid){
return userDao.getUser(userid);
} @PUT
@Path("/users")
@Produces(MediaType.APPLICATION_XML)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public String createUser(@FormParam("id") int id,
@FormParam("name") String name,
@FormParam("profession") String profession,
@Context HttpServletResponse servletResponse) throws IOException{
User user = new User(id, name, profession);
int result = userDao.addUser(user);
if(result == 1){
return SUCCESS_RESULT;
}
return FAILURE_RESULT;
} @POST
@Path("/users")
@Produces(MediaType.APPLICATION_XML)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public String updateUser(@FormParam("id") int id,
@FormParam("name") String name,
@FormParam("profession") String profession,
@Context HttpServletResponse servletResponse) throws IOException{
User user = new User(id, name, profession);
int result = userDao.updateUser(user);
if(result == 1){
return SUCCESS_RESULT;
}
return FAILURE_RESULT;
} @DELETE
@Path("/users/{userid}")
@Produces(MediaType.APPLICATION_XML)
public String deleteUser(@PathParam("userid") int userid){
int result = userDao.deleteUser(userid);
if(result == 1){
return SUCCESS_RESULT;
}
return FAILURE_RESULT;
} @OPTIONS
@Path("/users")
@Produces(MediaType.APPLICATION_XML)
public String getSupportedOperations(){
return "<operations>GET, PUT, POST, DELETE</operations>";
}
}
WebServiceTester(Write test client ourselves)
Jersey允许我们自己实现测试类(Web Service Client)
import java.util.List; import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType; public class WebServiceTester { private Client client;
private String REST_SERVICE_URL = "http://localhost:8080/UserManagement/rest/UserService/users";
private static final String SUCCESS_RESULT="<result>success</result>";
private static final String PASS = "pass";
private static final String FAIL = "fail"; private void init(){
this.client = ClientBuilder.newClient();
} public static void main(String[] args){
WebServiceTester tester = new WebServiceTester();
//initialize the tester
tester.init();
//test get all users Web Service Method
tester.testGetAllUsers();
//test get user Web Service Method
tester.testGetUser();
//test update user Web Service Method
tester.testUpdateUser();
//test add user Web Service Method
tester.testAddUser();
//test delete user Web Service Method
tester.testDeleteUser();
}
//Test: Get list of all users
//Test: Check if list is not empty
private void testGetAllUsers(){
GenericType<List<User>> list = new GenericType<List<User>>() {};
List<User> users = client
.target(REST_SERVICE_URL)
.request(MediaType.APPLICATION_XML)
.get(list);
String result = PASS;
if(users.isEmpty()){
result = FAIL;
}
System.out.println("Test case name: testGetAllUsers, Result: " + result );
}
//Test: Get User of id 1
//Test: Check if user is same as sample user
private void testGetUser(){
User sampleUser = new User();
sampleUser.setId(1); User user = client
.target(REST_SERVICE_URL)
.path("/{userid}")
.resolveTemplate("userid", 1)
.request(MediaType.APPLICATION_XML)
.get(User.class);
String result = FAIL;
if(sampleUser != null && sampleUser.getId() == user.getId()){
result = PASS;
}
System.out.println("Test case name: testGetUser, Result: " + result );
}
//Test: Update User of id 1
//Test: Check if result is success XML.
private void testUpdateUser(){
Form form = new Form();
form.param("id", "1");
form.param("name", "suresh");
form.param("profession", "clerk"); String callResult = client
.target(REST_SERVICE_URL)
.request(MediaType.APPLICATION_XML)
.post(Entity.entity(form,
MediaType.APPLICATION_FORM_URLENCODED_TYPE),
String.class);
String result = PASS;
if(!SUCCESS_RESULT.equals(callResult)){
result = FAIL;
} System.out.println("Test case name: testUpdateUser, Result: " + result );
}
//Test: Add User of id 2
//Test: Check if result is success XML.
private void testAddUser(){
Form form = new Form();
form.param("id", "2");
form.param("name", "naresh");
form.param("profession", "clerk"); String callResult = client
.target(REST_SERVICE_URL)
.request(MediaType.APPLICATION_XML)
.put(Entity.entity(form,
MediaType.APPLICATION_FORM_URLENCODED_TYPE),
String.class); String result = PASS;
if(!SUCCESS_RESULT.equals(callResult)){
result = FAIL;
} System.out.println("Test case name: testAddUser, Result: " + result );
}
//Test: Delete User of id 2
//Test: Check if result is success XML.
private void testDeleteUser(){
String callResult = client
.target(REST_SERVICE_URL)
.path("/{userid}")
.resolveTemplate("userid", 2)
.request(MediaType.APPLICATION_XML)
.delete(String.class); String result = PASS;
if(!SUCCESS_RESULT.equals(callResult)){
result = FAIL;
} System.out.println("Test case name: testDeleteUser, Result: " + result );
}
}
在Eclipse里面,选中 WebServiceTester, 右键 -> run as Java application, 我们会在 console 里面看到一下输出
Test case name: testGetAllUsers, Result: pass
Test case name: testGetUser, Result: pass
Test case name: testUpdateUser, Result: pass
Test case name: testAddUser, Result: pass
Test case name: testDeleteUser, Result: pass
Rest verbs
现在,我们再来分析一下 Rest verbs, 通过一下的表格我们能够更好地理解他们...
S.N. | HTTP Method, URI and Operation |
---|---|
1 | GET http://localhost:8080/UserManagement/rest/UserService/users 获取 users 列表 (只读的) |
2 | GET http://localhost:8080/UserManagement/rest/UserService/users/1 获取 id=1 的user (只读的) |
3 | PUT http://localhost:8080/UserManagement/rest/UserService/users/2 插入 id =2 的 user (幂等的) |
4 | POST http://localhost:8080/UserManagement/rest/UserService/users/2 更新 id=2 的 user (N/A) |
5 | DELETE http://localhost:8080/UserManagement/rest/UserService/users/1 删除 id=1 的 user (幂等的) |
6 | OPTIONS http://localhost:8080/UserManagement/rest/UserService/users 列出 service 上面的所有 operations (Read Only) |
7 | HEAD http://localhost:8080/UserManagement/rest/UserService/users 返回 HTTP HEAD (Read Only) |
注: 从URI 中, 我们不容易看出来究竟要执行 Rest service 的那个operation,operation需要体现以Class.Method的形式体现出来。
Rest之路 -- 从第二个Rest application里面分析 Rest 方法的更多相关文章
- Python之路【第二十篇】:待更新中.....
Python之路[第二十篇]:待更新中.....
- 【Android 应用开发】 Application 使用分析
博客地址 : http://blog.csdn.net/shulianghan/article/details/40737419 代码下载 : Android 应用 Application 经典用法; ...
- Application 使用分析
一. Application 分析 1. Application 简介 (1) Application 概念 Application 概念 : Application 属于组件范畴; -- 本质 : ...
- Python之路【第二十篇】Tornado框架
Tornado Tornado是使用Python编写的一个强大的.可扩展的Web服务器.它在处理严峻的网络流量时表现得足够强健,但却在创建和编写时有着足够的轻量级,并能够被用在大量的应用和工具中. 我 ...
- Python之路【第二十二篇】CMDB项目
浅谈ITIL TIL即IT基础架构库(Information Technology Infrastructure Library, ITIL,信息技术基础架构库)由英国政府部门CCTA(Central ...
- NYOJ 118 路方案(第二小的跨越)
修路方案 时间限制:3000 ms | 内存限制:65535 KB 难度:5 描写叙述 南将军率领着很多部队,它们分别驻扎在N个不同的城市里,这些城市分别编号1~N.因为交通不太便利,南将军准备修 ...
- 【Python之路】第二篇--初识Python
Python简介 Python可以应用于众多领域,如:数据分析.组件集成.网络服务.图像处理.数值计算和科学计算等众多领域.目前业内几乎所有大中型互联网企业都在使用Python,如:Youtube.D ...
- 【Python之路】第二十一篇--Memcached、Redis
Memcached Memcached 是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数据库负载.它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提高动态.数据库驱动网站的速度 ...
- Python之路【第二十四篇】Python算法排序一
什么是算法 1.什么是算法 算法(algorithm):就是定义良好的计算过程,他取一个或一组的值为输入,并产生出一个或一组值作为输出.简单来说算法就是一系列的计算步骤,用来将输入数据转化成输出结果. ...
随机推荐
- KVO 进阶
Key-value coding (KVC) 和 key-value observing (KVO) 是两种能让我们驾驭 Objective-C 动态特性并简化代码的机制.在这篇文章里,我们将接触一些 ...
- Course
Coursera计算机专业课程列表 巴黎中央理工学院人工视觉中的离散推理和学习 教授 Nikos Paragios & Pawan Kumar Jan 10th 2014 8 ...
- cc2530 -----SampleApp.c解析
/************************************************************************************************** ...
- STM32F4xx FPU的设置
原文:http://blog.csdn.net/dlutxie/article/details/7980389 浮点运算一直是定点CPU的难题,比如一个简单的1.1+1.1,定点CPU必须要按照IEE ...
- HDU 4685 Prince and Princess
强连通分量,看大神的题解才会写的.... http://www.cnblogs.com/kuangbin/p/3261157.html 数据量有点大,第一次Submit 2995ms过的,时限3000 ...
- 编程实现prim算法和Dijkstra算法。
网址链接:http://blog.csdn.net/anialy/article/details/7603170
- javascript之定义函数时 this 和prototype区别
注:原文 http://www.2cto.com/kf/201406/307790.html 这里作为学习,写在这里 在面向对象的方式编写js脚本时,定义实例的方法主要有两种:this.XXX = f ...
- poj 3628 Bookshelf 2 基本01背包
题目大意:FJ有n头奶牛,和一个高为h的架子,给出每头奶牛高度,求使奶牛叠加起来超过架子的最低高度是多少. 题目思路:求出奶牛叠加能达到的所有高度,并用dp[]保存,最后进行遍历,找出与h差最小的dp ...
- 【百度地图开发之二】基于Fragment的地图框架的使用
写在前面的话: [百度地图开发之二]基于Fragment的地图框架的使用(博客地址:http://blog.csdn.net/developer_jiangqq),转载请注明. Author:hmji ...
- JAVA字符串编码转换常用类
无论是对程序的本地化还是国际化,都会涉及到字符编码的转换的问题.尤其在web应用中常常需要处理中文字符,这时就需要进行字符串的编码转换,将字符串编码转换为GBK或者GB2312.一.关键技术点: ...