In this section we will look at how to invoke REST Services ( POST / PUT / Delete ) from Store JSPs using WCS framework.
Let's assume that you want to update quantity of an existing orderItem using REST Service. Looking at the swagger documentation we see that the REST URL to update an orderItem is:
https://localhost/wcs/resources/store/10001/cart/@self/update_order_item
HTTP Method is: PUT
Now to test this REST URL, you can use any REST Client (like HTTP Requester for FF or POSTMAN for chrome) and do a PUT with the JSON body set to something like below:
{
"orderId" : "123",
"orderItem" : [
{
"quantity"
: "4", // New quantity
"orderItemId"
: "1212",
}
]
]
}
Lets see how you can invoke this REST Service from JSP. Say, you have a shopping cart page where customers are allowed to modify the quantity and hit a submit button to save it. So how do you invoke a REST action and POST / PUT a JSON body as part of form submission ? Who converts the name value pair to JSON input required for the REST call ?
WCS framework provides you an Action class (RESTAction) to achieve this in a much simpler way. Its as simple as invoking a controller command from a view. Following list gives you step by step instructions to do the same:
- Create a mapping in rest-template-config.xml in Stores.war/web-inf/config/com.ibm.commerce.order-fep/rest-template-config.xml OR in your own XML file inside Stores.war/web-inf/config/<yourDir>. Make sure your XML file name ends with rest-template-config.xml
![]() |
rest-template-config.xml Mapping |
- Resource path ${serverHost}/wcs/resources/store/${storeId}/cart is mapped to name "orderlist".
- HTTP PUT Method for path @self/update_order_item is mapped to name updateOrderItem
- Input name value parameters are mapped to JSON structure inside <template> tag.
Update struts-config-order-rest-services.xml (or your custom struts file) to create a mapping URL as shown below:
![]() |
Struts mapping entry. |
- parameter value refers to resourcePathName.methodName defined in rest-template-config.xml.
- type is set to AjaxRESTAction. If you like to invoke the REST Service in Web1.0 style without using Ajax, then change type to RESTAction
With the above setup done, you can now submit the HTML Form to "AjaxRESTOrderItemUpdate" and pass name value parameter.
So the final URL to which HTML form will be posted looks something like:
https://localhost/webapp/wcs/stores/servlet/AjaxRESTOrderItemUpdate?orderId=123&orderItemId=123&quantity=4
This request is handled by the Store Struts servlet which invokes AjaxRESTAction class. This action class builds the complete REST URL and the JSON body using the mappings present in rest-template-config.xml and invokes that URL either remotely (using java.net.URL object) or locally (using RequestDispatcher).
You can follow similar pattern to make POST and DELETE calls from Store JSP
No comments:
Post a Comment