Best practice processing in post format in Jersey

Source: Internet
Author: User

In rest, we can write the method for accepting POST requests as follows:

@ Post

@ Consumes (mediatype. application_json)

Public Response createproduct (createproductjson, @ context uriinfo ){


Createproductjson is the JSON expression used by our server to receive a request such as createproudct. Then we can use createproductjson. similar methods such as getproduct () Get the product object, and then process the object around the product field.


This looks pretty good. createproductjson is similar to our DTO object, but the problem here is that the fault tolerance of createproductjson is poor. Assume that our current product requires two fields: Name and price. However, if the client transmits a description to us, it is very likely that an exception will be thrown when I deserialize the createproductjson object, and a 400 bad request error will be thrown. Such strict requirements are often unnecessary. For some explanations, refer to Martin Fowler's explanation of "customer driven contract".


So how can we make better fault tolerance? Actually very simple

@ Post
@ Consumes (mediatype. application_form_urlencoded)
Public Response createproduct (Form ){

We only need to define another transformer. For example, define productform, which contains the getproduct () method. In this method, we only need to extract the data we actually need from form, we can ignore unnecessary data.

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.