Maven+jersey Fast Build RESTful Web service integration mongodb-short and lean-worth owning

Source: Internet
Author: User
Tags glassfish jboss

Source: HTTP://PAN.BAIDU.COM/S/1GDIN4FP

Reprint please specify original address: http://blog.csdn.net/tianyijavaoracle/article/details/41708217

Jersey is the Jax-rs (JSR311) Open source reference implementation for building RESTful WEB service. In addition , Jersey provides some additional APIs and extension mechanisms so developers can scale Jersey to their own needs

The theory of things here I will not say more! This example is the implementation of the rest of the three basic get, put, delete functions, data stored in the MONGO. Below is the directory structure of the entire project


The project entrance is main in App.java,



Run the results such as: After running the App class entrance, the program listens to 8080 ports, we will find that we do not need Tomcat and other web containers can easily create Web services, concise and fast.



The following figure is run out of the TestClient test client output results, additions and deletions to check the output


The following figure is a successful addition of data after running add data in MONGO.




I'll take the following. Listing code



One, MAVEN's pom.xml code is as follows:

<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&Gt;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 if 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>


Second, the user entity class code is as follows

Package Model;import java.io.Serializable; public class User implements serializable{/** * */private static final long serialversionuid = 1l;private String id;priv Ate string Username;private string Phone;public User () {}public User (string ID, string userName, String phone) {super (); thi S.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 + ", u Sername= "+ UserName +", phone= "+ Phone +"] ";} @Overridepublic int hashcode () {final int prime = 31;int result = 1;result = Prime * result + (id = = NULL)? 0:ID.HASHC Ode ()); 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;re Turn true;}}

Third, the Userresource class code is as follows, the path of the access is established here.

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);}}

Iv. MyApplication class, by loading the userresourcer into the application

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 Exte NDS Application {    @Override public    set<class<?>> getclasses () {        final set<class<?> > classes = new hashset<class<?>> ();        Register Root Resource        Classes.add (userresource.class);        return classes;}    }

The App class is the entry for the entire project, and can be started by running the main function in the class.

After starting, you can test by running the client test code in the TestClient class. I continue to post the code.

The code is as follows:

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_u    RI = 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_ur            I, Root_path));            System.in.read ();        Server.shutdownnow ();        } catch (IOException ex) {Logger.getlogger (App.class.getName ()). log (Level.severe, NULL, ex); }    }}


VI. testclient test Client code:

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 (S Tring[] args) {User user = new User ("006", "Tianyi", "12355123891"), AddUser (user), GetAllUsers (), user = new User ("006", "Ti Anyi "," 33 "); String id = user.getid (); updateUser (user); Getuserbyid (ID); GetAllUsers ();d eluser (ID); GetAllUsers ();} /** * Add user */private static void addUser (user user) {System.out.println ("Add Users 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 ();} /** * Delete user */private static void Deluser (String id) {System.out.println ("Delete User * * * * * * * * *"); Client client = Clientbuilder.newclient (); Webtarget target = client.target (Serveruri + "/users/" + ID); Response Response = target.request (). Delete (); Response.close ();} /** * Modify user */private static void updateUser (user user) {System.out.println ("Modify user 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 ();} /** * Query user */private static void Getuserbyid (String id) {System.out.println ("query user based on ID") based on ID; Client client = Clientbuilder.newclient (). Register (Jacksonjsonprovider.class);//register JSON support 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 ();} /** * Query all users */private static void GetAllUsers () {System.out.println ("Query all 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 (); Close Connection}}


Seven, other code

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";p rivate static string mongodbserveraddress = "127.0. 0.1:2005 ";p rivate static String colname =" User ";p ublic static dbcollection getdbcollection () {try {if (MONGO = = null) {L ist<serveraddress> addlist = new arraylist<serveraddress> (); string[] Addrs = Mongodbserveraddress.split (";"); for (String Address:addrs) {serveraddress addr = new serveraddress (address); Addlist.add (addr);} MONGO = new MONGO (Addlis T); MongoDB Connection pool number 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 (); L Ist<user> users=new arraylist<user> ();D bcursor cur = coll.find (); if (cur.size () > 0) {while (Cur.hasnext ( ) {User user = new user ();D bobject 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 Basicd Bobject (). Append ("id", value));} catch (Exception e) {}}public static void Insertuserdata (user user) {dbcollection Dbcol = null;try {Dbcol = Getdbcollectio N (); 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 ());d Blist.add (subscribe);d Bcol.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.prints Tacktrace ();}}}


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.addus ER (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> ();p ublic 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 (). Equa LS (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.geti D (). 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 (US Er.getusername ()); U.setphone (User.getphone ());}} */mongodbutils.updatebyuser (user);} }


Run the results such as: After running the App class entrance, the program listens to 8080 ports, we will find that we do not need Tomcat and other web containers can easily create Web services, concise and fast.



The following figure is run out of the TestClient test client output results, additions and deletions to check the output


The following figure is a successful addition of data after running add data in MONGO.



Maven+jersey Fast Build RESTful Web service integration mongodb-short and lean-worth owning

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.