Maven+jersey快速构建RESTful Web service集成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; } @Override public String toString() { return "User [id=" + id + ", userName=" + userName + ", phone=" + phone + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public 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中添加成功的数据。
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。