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.