Rest path-Analyze rest methods from the second rest application

Source: Internet
Author: User

Introduction

Prior to this, we implemented the first rest application, and by analyzing her, we learned about the basic elements of rest programs, and here we will expand the functionality of the first Rest application (to implement CRUD). To streamline the process, we still use file-based methods to simulate database operations.

A second Rest ApplicationUser
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.GETPR         Ofession ())) {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.ge   Tallusers (); } @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 Crea      Teuser (@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) PU Blic 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, pro      Fession);      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 ("Useri      D ") 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 () {retur   N "<operations>get, PUT, POST, delete</operations>"; }}

Webservicetester (Write test client ourselves)

Jersey allows us to implement our own test classes (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 was not empty private void testgetallusers () {generictype& Lt      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 sample      user = 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 (Ent      Ity.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 (Enti         Ty.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); }}

Inside Eclipse, select webservicetester, right-click Run as Java application, and we'll see the output in the console

Test case Name:testgetallusers, result:passtest case Name:testgetuser, result:passtest case Name:testupdateuser, Resu Lt:passtest case Name:testadduser, result:passtest case Name:testdeleteuser, Result:pass

Rest verbs

Now, let's analyze the Rest verbs, and we'll get a better understanding of them through the table.

S.N. HTTP Method, URI, and Operation
1 GET
Http://localhost:8080/UserManagement/rest/UserService/users
Get the Users list
(Read-only)
2 GET
Http://localhost:8080/UserManagement/rest/UserService/users/1
Get the user of id=1
(Read-only)
3 PUT
Http://localhost:8080/UserManagement/rest/UserService/users/2
Insert ID =2 User
(idempotent)
4 POST
Http://localhost:8080/UserManagement/rest/UserService/users/2
Update the user of id=2
(N/a)
5 DELETE
Http://localhost:8080/UserManagement/rest/UserService/users/1
Delete the id=1 user
(idempotent)
6 OPTIONS
Http://localhost:8080/UserManagement/rest/UserService/users
List all operations on service
(Read only)
7 HEAD
Http://localhost:8080/UserManagement/rest/UserService/users
return HTTP HEAD
(Read only)

Note: From the URI, it is not easy to see that the operation,operation to perform the Rest service needs to be embodied in the form of Class.method.

Rest path-Analyze rest methods from the second rest application

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.