Jersey building a restful style of webserivces (iii)

Source: Internet
Author: User

I. GENERAL description

Through the Jersey-client interface, create a client program to invoke the jersey implementation of restful services, to achieve the increase, delete, change, check and other operations.

Server is mainly through the memory of the way, to simulate the user's additions, deletions, modifications, queries and other operations.

Second, create the service side

1. In the above project,

Modify the code in "Com.waylau.rest.resources.UserResource".

First, create a hashmap to save the added user

[Java]View Plaincopyprint?
    1. Private static map<string,user> UserMap = new hashmap<string,user> ();
private static map<string,user> UserMap  = new hashmap<string,user> ();

2. Create Add, delete, change, check user resources and other operations

/*** Add *@paramUser*/@POST @Consumes ({mediatype.application_xml, mediatype.application_json}) Public voidcreatestudent (user user) {usermap.put (User.getuserid (), user); }        /*** Delete *@paramID*/@DELETE @Path ("{ID}")     Public voidDeletestudent (@PathParam ("id"String ID) {usermap.remove (ID); }        /*** Change *@paramUser*/@PUT @Consumes (mediatype.application_xml) Public voidupdatestudent (user user) {usermap.put (User.getuserid (), user); }     /*** Search by ID *@paramID *@return     */@GET @Path ("{ID}") @Produces ({mediatype.application_xml, mediatype.application_json}) PublicUser Getuserbyid (@PathParam ("id") (String id) {User u=usermap.get (ID); returnu; }       /*** Check all *@return     */@GET @Produces ({mediatype.application_xml, mediatype.application_json}) PublicList<user>getAllUsers () {List<User> users =NewArraylist<user>();          Users.addall (Usermap.values ()); returnusers; }    

Third, create the client program

1. Create the package "Com.waylau.rest.client", under the package to build a Userclient.java, the code is as follows:

 Packagecom.waylau.rest.client;Importjavax.ws.rs.client.Client;ImportJavax.ws.rs.client.ClientBuilder;Importjavax.ws.rs.client.Entity;ImportJavax.ws.rs.client.WebTarget;ImportJavax.ws.rs.core.MediaType;ImportJavax.ws.rs.core.Response;ImportOrg.codehaus.jackson.jaxrs.JacksonJsonProvider;ImportCom.waylau.rest.bean.User;/*** User Client, used to test resources *@authorwaylau.com * 2014-3-18*/ Public classuserclient {Private StaticString Serveruri = "Http://localhost:8089/RestDemo/rest"; /**     * @paramargs*/     Public Static voidMain (string[] args) {addUser ();        GetAllUsers ();        UpdateUser ();        Getuserbyid ();        GetAllUsers ();        Deluser ();    GetAllUsers (); }    /*** Add User*/     Private Static voidAddUser () {System.out.println (* * * * Add user adduser****); User User=NewUser ("006", "Susan", "21"); Client Client=clientbuilder.newclient (); Webtarget Target= Client.target (Serveruri + "/users")); Response Response=target.request (). Buildpost (entity.entity (user, Mediatype.application_xml)). Invoke ();    Response.close (); }         /*** Delete User*/     Private Static voidDeluser () {System.out.println (* * * * Delete User * * * * *); Client Client=clientbuilder.newclient (); Webtarget Target= Client.target (Serveruri + "/users/006")); Response Response=target.request (). Delete ();    Response.close (); }              /*** Modify User*/     Private Static voidUpdateUser () {System.out.println ("* * * Modify user updateuser****"); User User=NewUser ("006", "Susan", "33"); Client Client=clientbuilder.newclient (); Webtarget Target= Client.target (Serveruri + "/users")); Response Response=target.request (). Buildput (entity.entity (user, Mediatype.application_xml)). Invoke ();    Response.close (); }    /*** Query users by ID*/     Private Static voidGetuserbyid () {System.out.println (* * * * * query users by ID * * * *); Client Client= Clientbuilder.newclient (). Register (Jacksonjsonprovider.class);//Registering JSON supportWebtarget target = client.target (Serveruri + "/users/006"); Response Response=target.request (). get (); User User= Response.readentity (User.class); System.out.println (User.getuserid ()+ user.getusername () +user.getage ());    Response.close (); }    /*** Query All users*/     Private Static voidgetAllUsers () {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     }     }

Four, the operation

Start the service-side project, run the client program userclient, the console output is as follows

[HTML]View Plaincopyprint?
    1. Add User adduser****
    2. Find All getallusers****
    3. [{"UserId": "006", "UserName": "Susan", "Age": "21"}]
    4. Modify User updateuser****
    5. Query users by ID * * * *
    6. 006susan33
    7. Find All getallusers****
    8. [{"UserId": "006", "UserName": "Susan", "Age": "33"}]
    9. Delete User * * * *
    10. Find All getallusers****
    11. []
Add User adduser******** query all getallusers****[{"userId": "006", "UserName": "Susan", "Age": "21"}]**** Modify user updateuser** Query user ****006susan33**** by ID for all getallusers****[{"userId": "006", "UserName": "Susan", "Age": "33"}]**** Delete User * * * Find All getallusers****[]

V. Summary

1. JSON registration is required if the client needs JSON conversion

[Java]View Plaincopyprint?
    1. Client client = Clientbuilder.newclient (). Register (Jacksonjsonprovider.   Class);
Client client = Clientbuilder.newclient (). Register (Jacksonjsonprovider.class);

2.WebTarget indicates the address of the resource to be requested

3.target.request (). Followed by the requested method:post,get,put or delete

Transferred from: http://blog.csdn.net/kkkloveyou/article/details/21517165

Jersey building a restful style of webserivces (iii)

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.