简体   繁体   中英

Path on Client side of RESTful Web Service

Ok so this is the code on the server side i just have question on how is the path gonna be defined on the client's side. This is the method on the server

@Path("{index}/{product}/{amount}")
@PUT
@Produces("text/plain")
public String editTable (@PathParam("index") Integer index, @PathParam("product")     String product, @PathParam("amount") Integer amount)
{...}

Now on the client side

{url = new URL( "http://localhost:8080/OrderService/service/tableservice/"+num+"/"+product+"/"+amount);
.....}

/"+num+"/"+product+"/"+amount);

Is this the correct syntax??

Also can the num and amount be integers while the product a string or am i gonna have a problem with it?

If you are mapping any @QueryParam to Integer, ensure that you are taking care of the following:
From the link on Oracle docs:

If a query parameter exists in the query component of the request URI, then the value will be extracted and parsed as a 32–bit signed integer and assigned to the method parameter. If the value cannot be parsed as a 32–bit signed integer, then an HTTP 400 (Client Error) response is returned.

Just to be safe, have your index and amount as String . Parse them to Integer within your service and handle NumberFormatException instead of HTTP 400.

You will have problems if the product name has 'unsafe' URL characters in it. Which will probably be the case. To get around that you could URL encode the name before appending it to the URL.

But I think you should rethink your PATH definition in the first place. A good resource endpoint should uniquely identify it. But in your case you are including an amount field in the URL! Which means depending on who is ordering the product the resource URL is changing:

Customer A orders 2 Furbies:

/OrderService/service/tableservice/9/Furbies/2

Customer B orders 1 Furbie

/OrderService/service/tableservice/9/Furbies/1

But in both cases the customers are trying to order the same thing - a Furbie! This is not RESTful. Instead you should define a unique resource endpoint, then send the additional order information as appended data. So for example:

public class Order {
    private Integer productId;
    private Integer amount;
}

@PUT
@Path("/{productId}/orders")
@Produces("text/plain")
public String updateOrder(@PathParam("productId"), Order order) { ... }

You will notice I removed the index field as well, you can add that back in if absolutely required. You will notice I also added tacked an orders suffix to the end of the URL. To indicate that you are PUT'ing an updated representation for an order made for a product.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM