In this article we mainly explain how to use the Jersey component to write a rest Service that can guarantee the basic operation, it is said that the basic operation is because the interface is exposed and simple, once encountered other circumstances, will not be able to properly handle our request. At the same time, this interface returns content is too simple, if the call fails, the caller can not exactly know the exact error message. So this section, we will improve the interface, for the caller to provide 400-bad request, 500-server Error, 304-not Modified, 200-response OK, 404-not found the identification mark, Let the caller understand what is wrong and where it is wrong.
Return Code Overview
1.400-bad request: This kind of error code is usually a demand error, for example, my userid needs to pass in the UUID type, but I passed the non-conforming data, such as int type, then the service received this request, You can return this error code directly to the client and attach the corresponding error description, then the client can understand where it is wrong.
2.500-bad Request: This error code is generally a processing error, that is, the entire processing pipeline exception handling of the capture, we can throw this error in the catch to the user and with the corresponding error code.
3.404-not Found: This error code is generally not found in the content caused. That is, this error can be returned if the requester sends a request, but the relevant information is not found in the database.
4.200-response OK: This status code can be sent when the client initiates the request and the server responds successfully.
5.304-not Modified: This return code is calculated by the ETag, the specific process is as follows: The client first sends a request to the server side, the server receives the request, and then computes the etag, which is passed to the client in the header. After the client requests later, it needs to attach the If-none-match:etag value, send to the server side, the server received this value, then regenerate the ETag value, and finally do the comparison, if not changed, then return to the client 304, if there is a change, you need to extract data from the database, Returns the 200 status code to the client.
Code Design
Here we are not detailing the specific design steps, I only show the specific code.
First, we define a Get API action method:
/** * Provide the endpoint used to get the summary of the user progress * /@GET @Path ("{" + Ptsresourcepath S.progress_summary_root_path_resource+ "}/" + ptsresourcepaths.progress_summary_binary_path_resource) @ Produces (Mediatype.application_json) Response userlearningsummaryrequest (@PathParam ( Ptsresourcepaths.progress_summary_root_path_resource) String Titanuserid, @Context request request);
From the definition above, we can see that it receives two parameters, one is the user ID, the other is the client request context (the Request object can evaluate the ETag value).
Then, let's take a look at the Database bean processing:
@Override public list<userlearningcourse> findlearnerprogresssummarybytitanuserident (String Titanuserid ) { return userlearningcoursedao.fetchsummaryprogressbyuserident (Titanuserid); }
is not very simple, the database processing this block directly from the database to get the data collection, return.
Then, let's look at the Business bean Processing:
@Override Public genericresponsewrapperdto<userlearningcoursesresponse> Processuserlearningsummaryrequest ( String Titanuserid, request request) throws Datavalidationexception {Genericresponsewrapperdto<userl earningcoursesresponse> responsewrapper = new genericresponsewrapperdto<userlearningcoursesresponse> (); Userlearningcoursesresponsedto userlearningcoursesresponsedto = new Userlearningcoursesresponsedto (); List userlearningsummarydtocollection = new ArrayList (); If the Titanuserid match the UUID format if (!titanuserid.matches ("[0-9a-fa-f]{8}-[0-9a-fa-f]{4}-[0-9a-fa-f]{4}-[ 0-9A-FA-F]{4}-[0-9A-FA-F]{12} ")) {Responsewrapper.sethttpstatuscode (PtsErrors.ErrorEnum.TITAN_USER_IDENT_INVAL Id.getstatus (). Getstatuscode ()); Responsewrapper.seterrormessage (PtsErrors.ErrorEnum.TITAN_USER_IDENT_INVALID.getErrorMessage ()); Responsewrapper.seterrorcode (PtsErrors.ErrorEnum.TITAN_USER_IDENT_INVALID. GetErrorCode ()); return responsewrapper; } list<userlearningcourse> resultcollection = Userlearningsummarybean.findlearnerprogresssummarybytitanuseri Dent (Titanuserid); if (resultcollection = = NULL | | resultcollection.size () ==0) {Responsewrapper.sethttpstatuscode (ptserrors.error Enum.USER_LEARNING_COURSE_SUMMARY_EMPTY.getStatus (). Getstatuscode ()); Responsewrapper.seterrormessage (PtsErrors.ErrorEnum.USER_LEARNING_COURSE_SUMMARY_EMPTY.getErrorMessage ()); Responsewrapper.seterrorcode (PtsErrors.ErrorEnum.USER_LEARNING_COURSE_SUMMARY_EMPTY.getErrorCode ()); return responsewrapper; }//mapper between the response entity and responsedto entity String etagstr = ""; for (Userlearningcourse userlearningcourse:resultcollection) {userlearningcourseresponsedto UserLearningCour Seresponsedto = new Userlearningcourseresponsedto (); Userlearningcourseresponsedto.setcourseId (Userlearningcourse.getcourseidentifier ()); Userlearningcourseresponsedto.setbestgrade (Userlearningcourse.getbestcoursegrade ()); Userlearningcourseresponsedto.setlatestgrade (Userlearningcourse.getlatestcoursegrade ()); list<userlearningsequence> userlearningsequences = Userlearningcourse.getuserlearningsequences (); list<userlearningsequenceresponse> userlearningsequenceresponses = new arraylist< Userlearningsequenceresponse> (); if (userlearningsequences! = null && userlearningsequences.size () > 0) {for (Userlearningsequen Ce userlearningsequence:userlearningsequences) {userlearningsequenceresponsedto userlearningsequence Response = new Userlearningsequenceresponsedto (); Userlearningsequenceresponse.setsequenceid (Userlearningsequence.getsequenceidentifier ()); Userlearningsequenceresponse.setbestgrade (userlearningsequence.getbestseqUencegrade ()); Userlearningsequenceresponse.setlatestgrade (Userlearningsequence.getlatestsequencegrade ()); Userlearningsequenceresponses.add (Userlearningsequenceresponse); }} userlearningcourseresponsedto.setsequences (userlearningsequenceresponses); Userlearningsummarydtocollection.add (userlearningcourseresponsedto); Calculate the ETAG etagstr + = FormatDate (Userlearningcourse.getlastmodifiedat ()); } userlearningcoursesresponsedto.setuserid (Titanuserid); Userlearningcoursesresponsedto.setcourses (userlearningsummarydtocollection); The hashcode should based on the last_modify_date in database. Entitytag ETag = new Entitytag (Etagstr.hashcode () + ""); Verify if it matched with etag available in HTTP request Response.responsebuilder Builder = Request.evaluatepreco Nditions (ETAG); Set ETag value Setetag (etag); if (builder = null) {//304 here, not modified,directly return Responsewrapper.sethttpstatuscode (R Esponse. Status.NOT_MODIFIED.getStatusCode ()); } else {//200 here, Content changed Responsewrapper.sethttpstatuscode (Response.Status.OK.getStatusC Ode ()); Responsewrapper.setpayload (userlearningcoursesresponsedto); } return responsewrapper; }
From the above code, we can see that the ETag calculation is to add the Lastmodifiyat time, and then through the Hashcode method to get processing results, and then sent to the client. When the client requests the ETag again, we can use the Request.evaluatepreconditions (ETag) to calculate whether the current etag is equal to the ETag sent by the client, and if it does, returns a 304 status code, if inconsistent, Indicates a change in database data, the data is retrieved directly from the database and then sent to the client.
Finally, let's look at how the server attaches the ETag to the client:
@Override public Response userlearningsummaryrequest (String titanuserid,request Request) { genericresponsewrapper<?> responsewrapper = Userlearningsummaryhandlerbean . Processuserlearningsummaryrequest (Titanuserid, request); Responsebuilder Responsebuilder = Response.Status (Responsewrapper.gethttpstatuscode ()); Responsebuilder.entity (responsewrapper); Send ETag back to client Responsebuilder.tag (Userlearningsummaryhandlerbean.getetag ()); return Responsebuilder.build (); }
Responsebuilder can be returned, Responsebuilder is the encapsulation of the client object of Jersey.
Interface debugging
1. Normal request, 200 status code return:
Then we look at the contents of the header:
The return value of the ETag is clearly seen.
2. When the user ID is not a UUID type, the 400 status code returns:
3. When the user ID does not exist in the database, the 404 status Code returns because the data is not queried:
4. The user attaches the ETag, request the same data, because the server has returned a consistent content, so there is no need to return, directly return 304 status code hint data is not updated:
5. The user attaches the wrong etag (without double quotation marks), causing the service side parsing error, and returning the 500 status code prompt error directly:
Java Scientia Basics: Return codes you don't know