標籤:jersey web服務 資料 mongodb
源碼:http://pan.baidu.com/s/1gdIN4fp
轉載請註明原著地址:http://blog.csdn.net/tianyijavaoracle/article/details/41708217
Jersey是JAX-RS(JSR311)開源參考實現用於構建RESTful Web service。此外Jersey還提供一些額外的API和擴充機制,所以開發人員能夠按照自己的需要對Jersey進行擴充
理論的東西在這裡我就不多說了!這個執行個體是實現了REST的三個基本get、put、delete功能,資料存放區在mongo裡。下面的是整個工程的目錄結構
工程入口是App.java 裡的main,
運行結果如:運行app類中入口後,程式監聽8080連接埠,大家會發現,我們不需要tomcat等web容器即可輕鬆建立web服務,簡潔快速。
下面這張圖是運行完TestClient測試用戶端的輸出結果,增刪改查輸出結果
下面這張圖是 運行添加資料後,mongo中添加成功的資料。
下面我來依依列出代碼
一、maven的pom.xml代碼如下:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.example</groupId><artifactId>jerseyUserDemo</artifactId><packaging>war</packaging><version>0.0.1-SNAPSHOT</version><name>jerseyUserDemo Maven Webapp</name><url>http://maven.apache.org</url><repositories><repository><id>snapshot-repository.java.net</id><name>Java.net Snapshot Repository for Maven</name><url>https://maven.java.net/content/repositories/snapshots/</url><layout>default</layout></repository><repository><id>spring.test-mvc</id><url>http://repo.springsource.org/libs-milestone</url></repository><repository><id>repo1</id><name>repo1</name><url>http://repo1.maven.org/maven2</url></repository><repository><id>jboss-cache</id><name>jboss-cache</name><url>http://repository.jboss.org/maven2</url></repository><repository><id>mvnsearch</id><name>mvnsearch Maven Repository</name><url>http://www.mvnsearch.org/maven2</url></repository><repository><id>ibiblio</id><name>ibiblio Maven Repository</name><url>http://www.ibiblio.org/maven2</url></repository><repository><id>mirrors.ibiblio</id><name>mirrors.ibiblio Maven Repository</name><url>http://mirrors.ibiblio.org/pub/mirrors/maven2</url></repository></repositories><dependencies><!-- Tomcat Servlet API --><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>3.1.0</version></dependency><dependency><groupId>org.glassfish.jersey.containers</groupId><artifactId>jersey-container-grizzly2-servlet</artifactId><version>2.13</version></dependency><dependency><groupId>org.glassfish.jersey.containers</groupId><artifactId>jersey-container-servlet-core</artifactId><version>2.13</version></dependency><dependency><groupId>org.glassfish.jersey.media</groupId><artifactId>jersey-media-json-jackson</artifactId><version>2.13</version></dependency><!-- Required only when you are using JAX-RS Client --><dependency><groupId>org.glassfish.jersey.core</groupId><artifactId>jersey-client</artifactId><version>2.13</version></dependency><!-- mongodb --><dependency><groupId>org.mongodb</groupId><artifactId>mongo-java-driver</artifactId><version>2.12.4</version></dependency></dependencies><build><finalName>jerseyUserDemo</finalName></build></project>
二、User實體類代碼如下
package model;import java.io.Serializable; public class User implements Serializable{/** * */private static final long serialVersionUID = 1L;private String id;private String userName;private String phone;public User(){}public User(String id, String userName, String phone) {super();this.id = id;this.userName = userName;this.phone = phone;}public String getId() {return id;}public void setId(String id) {this.id = id;}public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;}public String getPhone() {return phone;}public void setPhone(String phone) {this.phone = phone;} @Overridepublic String toString() {return "User [id=" + id + ", userName=" + userName + ", phone=" + phone + "]";}@Overridepublic int hashCode() {final int prime = 31;int result = 1;result = prime * result + ((id == null) ? 0 : id.hashCode());return result;}@Overridepublic boolean equals(Object obj) {if (this == obj)return true;if (obj == null)return false;if (getClass() != obj.getClass())return false;User other = (User) obj;if (id == null) {if (other.id != null)return false;} else if (!id.equals(other.id))return false;return true;}}
三、UserResource類代碼如下,這裡制定了訪問的路徑。
package resource;import java.util.List;import javax.inject.Singleton;import javax.ws.rs.Consumes;import javax.ws.rs.DELETE;import javax.ws.rs.GET;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 model.User;import service.UserService;@Singleton@Path("/users")public class UserResource {@GET@Produces({ "application/json", "application/xml" })public List<User> getMyResources() {List<User> users = UserService.getUsers(); return users;}@GET@Path("/list")@Produces({ "application/json", "application/xml" })public List<User> getListOfUsers() {List<User> users = UserService.getUsers(); return users;}@GET@Path("/{id}")@Produces({ "application/json" })public User getUser(@PathParam("id") String id) { User u=UserService.getUserById(id);return u;}@PUT//@Path("/ids/{id}")@Consumes({ "application/json", "application/xml" })public void putUser(User user) {UserService.updateUser(user); }@POST//@Path("/ids/{id}")@Consumes({ "application/json", "application/xml" })public void postUser(User user) {UserService.addUser(user); }@DELETE@Path("/{id}")public void deleteUser(@PathParam("id") String id) { UserService.delUserById(id);}}
四、MyApplication類,通過將UserResourcer載入到應用中
package main;import java.util.HashSet;import java.util.Set;import javax.ws.rs.ApplicationPath;import javax.ws.rs.core.Application;import resource.UserResource;/** * @author Pavel Bucek (pavel.bucek at oracle.com) */@ApplicationPath("/")public class MyApplication extends Application { @Override public Set<Class<?>> getClasses() { final Set<Class<?>> classes = new HashSet<Class<?>>(); // register root resource classes.add(UserResource.class); return classes; }}
五、App類是整個工程的入口,通過運行該類中的main函數啟動即可
啟動後可以通過運行TestClient類中的用戶端測試代碼進行測試。我繼續貼代碼。
代碼如下:
package main;import java.io.IOException;import java.net.URI;import java.util.HashMap;import java.util.Map;import java.util.logging.Level;import java.util.logging.Logger;import org.glassfish.grizzly.http.server.HttpServer;import org.glassfish.jersey.grizzly2.servlet.GrizzlyWebContainerFactory;import org.glassfish.jersey.server.ServerProperties;import org.glassfish.jersey.servlet.ServletContainer;import resource.UserResource;/** * @author Pavel Bucek (pavel.bucek at oracle.com) */public class App { private static final URI BASE_URI = URI.create("http://localhost:8080/webapp/"); public static final String ROOT_PATH = "users"; public static void main(String[] args) { try { Map<String, String> initParams = new HashMap<String, String>(); initParams.put(ServerProperties.PROVIDER_PACKAGES, UserResource.class.getPackage().getName()); final HttpServer server = GrizzlyWebContainerFactory.create(BASE_URI, ServletContainer.class, initParams); System.out.println(String.format("Application started.%nTry out %s%s%nHit enter to stop it...", BASE_URI, ROOT_PATH)); System.in.read(); server.shutdownNow(); } catch (IOException ex) { Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex); } }}
六、TestClient測試用戶端代碼:
package client;import javax.ws.rs.client.Client;import javax.ws.rs.client.ClientBuilder;import javax.ws.rs.client.Entity;import javax.ws.rs.client.WebTarget;import javax.ws.rs.core.MediaType;import javax.ws.rs.core.Response;import model.User;import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;/** * * @author zhongtianyi * */public class TestClient {private static String serverUri = "http://localhost:8080/webapp";/** * @param args */public static void main(String[] args) {User user = new User("006", "tianyi", "12355123891");addUser(user);getAllUsers();user = new User("006", "tianyi", "33");String id = user.getId();updateUser(user);getUserById(id);getAllUsers();delUser(id);getAllUsers();}/** * 添加使用者 */private static void addUser(User user) {System.out.println("****增加使用者addUser****");Client client = ClientBuilder.newClient();WebTarget target = client.target(serverUri + "/users");Response response = target.request().buildPost(Entity.entity(user, MediaType.APPLICATION_JSON)).invoke();response.close();}/** * 刪除使用者 */private static void delUser(String id) {System.out.println("****刪除使用者****");Client client = ClientBuilder.newClient();WebTarget target = client.target(serverUri + "/users/" + id);Response response = target.request().delete();response.close();}/** * 修改使用者 */private static void updateUser(User user) {System.out.println("****修改使用者updateUser****");Client client = ClientBuilder.newClient();WebTarget target = client.target(serverUri + "/users");Response response = target.request().buildPut(Entity.entity(user, MediaType.APPLICATION_JSON)).invoke();response.close();}/** * 根據id查詢使用者 */private static void getUserById(String id) {System.out.println("****根據id查詢使用者****");Client client = ClientBuilder.newClient().register(JacksonJsonProvider.class);// 註冊json 支援WebTarget target = client.target(serverUri + "/users/" + id);Response response = target.request().get();User user = response.readEntity(User.class); System.out.println(user.getId() + user.getUserName());response.close();}/** * 查詢所有使用者 */private static void getAllUsers() {System.out.println("****查詢所有getAllUsers****");Client client = ClientBuilder.newClient();WebTarget target = client.target(serverUri + "/users");Response response = target.request().get();String value = response.readEntity(String.class);System.out.println(value);response.close(); // 關閉串連}}
七、其他代碼
package utils; import java.util.ArrayList; import java.util.List;import model.User;import com.mongodb.BasicDBList;import com.mongodb.BasicDBObject;import com.mongodb.DB;import com.mongodb.DBCollection;import com.mongodb.DBCursor;import com.mongodb.DBObject;import com.mongodb.Mongo;import com.mongodb.MongoOptions;import com.mongodb.ServerAddress;public class MongoDBUtils {public static Mongo mongo = null;public static DB db = null;private static String dbName = "UserAdmin";private static String mongodbServerAddress = "127.0.0.1:2005";private static String colName = "User";public static DBCollection getDBCollection() {try {if (mongo == null) { List<ServerAddress> addList = new ArrayList<ServerAddress>();String[] addrs = mongodbServerAddress.split(";");for (String address : addrs) {ServerAddress addr = new ServerAddress(address);addList.add(addr);} mongo = new Mongo(addList); // mongodb串連池數MongoOptions opt = mongo.getMongoOptions();opt.connectionsPerHost = 400;opt.threadsAllowedToBlockForConnectionMultiplier = 20;opt.maxWaitTime = 5000;opt.socketTimeout = 0;opt.connectTimeout = 15000;}if (db == null) {db = mongo.getDB(dbName);}} catch (Exception e) {}return db.getCollection(colName);}public static User findUserByID(String id) {DBCollection coll = null; coll = getDBCollection(); DBCursor cur = coll.find(new BasicDBObject("id", id));User user = new User();if (cur.size() > 0) {while (cur.hasNext()) {DBObject o = (DBObject) cur.next();String userName = o.get("username").toString();String phone = o.get("phone").toString();user.setId(id);user.setPhone(phone);user.setUserName(userName);}}return user;}public static List<User> findUsers() {DBCollection coll = null;DBObject queryType = null;coll = getDBCollection();List<User> users=new ArrayList<User>();DBCursor cur = coll.find();if (cur.size() > 0) {while (cur.hasNext()) {User user = new User();DBObject o = (DBObject) cur.next();String id = o.get("id").toString();String userName = o.get("username").toString();String phone = o.get("phone").toString();user.setId(id);user.setPhone(phone);user.setUserName(userName);users.add(user);}}return users;}public static void removeByID(String value) {DBCollection coll = null;try {coll = getDBCollection();coll.remove(new BasicDBObject().append("id", value));} catch (Exception e) {}}public static void insertUserData(User user) {DBCollection dbCol = null;try {dbCol = getDBCollection();List<DBObject> dbList = new ArrayList<DBObject>();BasicDBObject subscribe = new BasicDBObject();subscribe.put("id", user.getId());subscribe.put("username", user.getUserName());subscribe.put("phone", user.getPhone());dbList.add(subscribe);dbCol.insert(dbList);} catch (Exception e) {}}public static void updateByUser(User user) {DBCollection coll = null;try {coll = getDBCollection();BasicDBObject newDocument3 = new BasicDBObject().append("$set",new BasicDBObject().append("username", user.getUserName()).append("phone", user.getPhone()));coll.update(new BasicDBObject().append("id", user.getId()), newDocument3);} catch (Exception e) {}}public static void close() {try {if (mongo != null) {mongo.close();}} catch (Exception e) {e.printStackTrace();}}}
package service;import java.util.List;import dao.UserDao;import model.User;public class UserService {public static User getUserById(String id) {return UserDao.getUserById(id);}public static List<User> getUsers() {return UserDao.getUsers();}public static void delUserById(String id) {UserDao.delUserById(id);} public static void addUser(User user) { UserDao.addUser(user);}public static void updateUser(User user) { UserDao.updateUser(user);}}
package dao;import java.util.ArrayList;import java.util.List;import utils.MongoDBUtils;import model.User;public class UserDao {private UserDao() {}private static List<User> users = new ArrayList<User>();public static void addUser(User u) {//users.add(u);MongoDBUtils.insertUserData(u);}public static User getUserById(String id) {return MongoDBUtils.findUserByID(id);/*for (User u : users) {if (u.getId().equals(id)) {return u;}}return null;*/}public static List<User> getUsers() {return MongoDBUtils.findUsers();}public static void delUserById(String id) {MongoDBUtils.removeByID(id);/*User user = null;for (User u : users) {if (u.getId().equals(id)) {user = u;}}if (user != null) {users.remove(user);}*/}public static void updateUser(User user) {/*for (User u : users) {if (u.getId().equals(user.getId())) {u.setUserName(user.getUserName());u.setPhone(user.getPhone());}}*/MongoDBUtils.updateByUser(user);} }
運行結果如:運行app類中入口後,程式監聽8080連接埠,大家會發現,我們不需要tomcat等web容器即可輕鬆建立web服務,簡潔快速。
下面這張圖是運行完TestClient測試用戶端的輸出結果,增刪改查輸出結果
下面這張圖是 運行添加資料後,mongo中添加成功的資料。
Maven+jersey快速構建RESTful Web service整合mongodb-短小而精悍-值得擁有