05: Spring 4 MVC RESTful Web Service Beginner Tutorial step by step

Install RESTClient from WizTools.org

Step 1: RESTClient is required to test the RESful web services. Go to

http://download.wiztools.org/rest-client/archive/index.html

Download the latest version of “restclient-ui-3.2.2-jar-with-dependencies.jar” file. Copy it to “c:\tools” and run it by Double-Clicking if you are running on windows. If outside windows you can run it as shown below.

RESTClient from WizTools to test RESTful web services

pom.xml with XML & JSON data binding

Step 2: The pom.xml with “jackson-databind“, which will be used to convert the response data into JSON string, and “jackson-dataformat-xml“, which will be used to convert the response data to XML.

Define the model class Account.java

Step 3: Define the Account.java with 3 fields & getters/setters in the package “com.mytutorial.model”.

Define the controller class AccountController.java

Step 3: Define the AccountController.java with 3 fields & getters/setters in the package “com.mytutorial.controller”.

Spring Java Configs for wiring up

Step 4: Spring Java configs in the package “com.mytutorial.config”

Bootstrap the Spring dispatcher Servlet with the mapping URI of “/entry/*” & the above “SimpleWebConfiguration” for the controllers

Build simpleWeb.war & deploy to Tomcat

Step 5: Copy the “simpleWeb.war” to Tomcat’s “webapps” folder and start the Tomcat server.

Start the RESTClient from WizTools.org

Step 6: Double-Clicking “c:\tools\restclient-ui-3.2.2-jar-with-dependencies.jar” on windows or

XML Data

http://localhost:8080/simpleWeb/entry/v1/forecasting/account

JSON Data

http://localhost:8080/simpleWeb/entry/v1/forecasting/accounts.json

You need to add “.json” suffix to the URL to get JSON data.

Further discussions

Q. What if you want the URL “http://localhost:8080/simpleWeb/entry/v1/forecasting/accounts” to return JSON data instead of XML.
A. If you want it to return JSON data: “produces={MediaType.APPLICATION_JSON_VALUE}”:

If you want it to return XML data: produces={MediaType.APPLICATION_XML_VALUE}

Note that @RestController is used instead of “@Controller“. If you were to use “@Controller“, you need to use the annotation @ResponseBody as in “public @ResponseBody Account[] getAccounts()” as shown below:

You may like

“12 Rules” to write RESTFul Web Service API


Java developer & architect Q&As

Java developers Q&As

Top