Spring MVC 4.0: Consuming RESTFul Web Services using RestTemplate
This article is a continuation of my previous article on Spring MVC 4.0 RESTFul web services . So far I have written two articl...
https://www.programming-free.com/2014/04/spring-mvc-consuming-restful-web-services.html
This article is a continuation of my previous article on Spring MVC 4.0 RESTFul web services. So far I have written two articles on how to create restful web service using Spring MVC 4.0. Last tutorial explained how to create a RESTFul web service in spring that would return user information from mysql table in JSON format. Let us now implement a Spring MVC application that issues web service requests and fetches the response returned by the web service.
Articles on Spring MVC RESTFul Web Services
- CRUD using Spring Data Rest and AngularJS using Spring Boot
- CRUD using Spring MVC 4.0 RESTful Web Services and AngularJS
- Spring MVC 4.0 RESTFul Web Services Simple Example
- Spring MVC 4.0 RESTFul Web Service JSON Response with @ResponseBody
- Spring MVC 4.0: Consuming RESTFul Web Services using RestTemplate
In this tutorial, we will extend our previous example to include a class that fetches user data from the spring service we had already created and display it in a jsp page (view). Spring MVC is a complete framework with lot of inbuilt features that facilitates easy and quick web development, including a template class - 'RestTemplate' for consuming web services.
I assume that you have gone through my previous article and have created a web service as explained. I am not going to repeat anything here. Let me start from where I left in my previous tutorial. You can download the sample application provided in my previous tutorial and start from there. Make sure to create mysql table and change connection string configuration in the downloaded application.
RestTemplate
Spring MVC provides a template class called RestTemplate to support client side access to REST web service. This class has methods to support the six HTTP methods listed below,
The above link has an excellent article explaining the usage of RestTemplate for client side access.
Enough of theory, now let us proceed with the sample application.
1. Download the application we created in previous article from here. Take a look at the article and create mysql table accordingly.
2. Import the downloaded project in eclipse and alter connection string configuration in 'config.properties' file to match your mysql configuration.
3. The idea is to issue request to the web service methods present in 'SpringServiceController' class and display the response in views (jsp's). In order to do this, we need to add a viewresolver to spring configuration file.
Add 'InternalResourceViewResolver' to 'rest-servlet.xml' file present in Webcontent/WEB-INF folder,
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<context:component-scan
base-package=
"com.programmingfree.springservice.controller" />
<mvc:annotation-driven />
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
Configuration code to be added to existing code is highlighted above. The view-resolver will look for jsp files as the 'suffix' property contains '.jsp' in it and in the path 'WEB-INF/jsp/' as the prefix propery is set as such.
2. Let us add a controller class which uses RestTemplate to query the web service we had already created. Create a new class called 'ListUsersController.java' under 'com.programmingfree.springservice.controller' and copy the below code in it.
package com.programmingfree.springservice.controller; import java.util.LinkedHashMap; import java.util.List; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.client.RestTemplate; import org.springframework.web.servlet.ModelAndView; import com.programmingfree.springservice.domain.User; @Controller public class ListUsersController { @RequestMapping("/listUsers") public ModelAndView listUsers() { RestTemplate restTemplate = new RestTemplate(); String url="http://localhost:8080/SpringServiceJsonSample/service/user/"; List<LinkedHashMap> users=restTemplate.getForObject(url, List.class); return new ModelAndView("listUsers", "users", users); } @RequestMapping("/dispUser/{userid}") public ModelAndView dispUser(@PathVariable("userid") int userid) { RestTemplate restTemplate = new RestTemplate(); String url="http://localhost:8080/SpringServiceJsonSample/service/user/{userid}"; User user=restTemplate.getForObject(url, User.class,userid); return new ModelAndView("dispUser", "user", user); } }
In the previous example, the url 'http://localhost:8080/SpringServiceJsonSample/service/user/' returned list of all users in json format. This controller contains two methods, one to list all users in a table and the other to list a single user information. Each method uses different jsp pages - 'listUsers.jsp & dispUser.jsp' to display data retreived from web service. RestTemplate automatically converts the json response to Java model class, in this case 'User' class for us.
3. Create two jsp files under "WEB-INF/jsp/" folder and copy the code given below. Make sure to use the same name as given below for the jsp files as we have used these names already in the controller class.
listUsers.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>List of Users</title> </head> <body> <table border="1" align="center" style="width:50%"> <thead> <tr> <th>User Id</th> <th>First Name</th> <th>Last Name</th> <th>Email</th> </tr> </thead> <tbody> <c:forEach var="users" items="${users}" > <tr> <td>${users.userid}</td> <td>${users.firstName}</td> <td>${users.lastName}</td> <td>${users.email}</td> </tr> </c:forEach> </tbody> </table> </body> </html>
I have used JSTL(Java Standard Tag Libraries) to loop through the list of user objects here.
dispUser.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>User Details</title> </head> <body> <table border="1" align="center" style="width:50%"> <thead> <tr> <th>User Id</th> <th>First Name</th> <th>Last Name</th> <th>Email</th> </tr> </thead> <tbody> <tr> <td>${user.userid}</td> <td>${user.firstName}</td> <td>${user.lastName}</td> <td>${user.email}</td> </tr> </tbody> </table> </body> </html>
This is how the project structure will look after creating all necessary classes and files,
4. Finally, add the below servlet mapping to web.xml file. This is to avoid 'no mapping found error' for jsp pages, caused by the '/*' mapping we have given for dispatcher servlet.
<servlet> <servlet-name>jsp</servlet-name> <servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>jsp</servlet-name> <url-pattern>/WEB-INF/jsp/*</url-pattern> </servlet-mapping>
That is all. Now run the application in Tomcat server and hit this url, 'http://localhost:8080/SpringServiceJsonSample/listUsers'. This request will be routed to ListUsersController and the response will be displayed utilizing the corresponding view (listUser.jsp) such as this,
To display specific user information, hit 'http://localhost:8080/SpringServiceJsonSample/dispUser/2',
hi what if i want to save a user?
ReplyDeleteSuppose a web service method is taking user object as parameter in order to save the user object sent to it,
now how can i send the user object from client?
This isn't working for me. My data is not getting replaced. The fields show up as ${user.userid}. What am I doing wrong?
ReplyDeleteWhat is the exception or error message found in your logs?
DeleteThanks,
Priya
Hello Madam,
ReplyDeletethis is rest-servlet.xml
and this web.xml
SpringServiceJsonSample
index.html
index.htm
index.jsp
default.html
default.htm
default.jsp
jsp
org.apache.jasper.servlet.JspServlet
jsp
/WEB-INF/jsp/*
It is not at all working, means hitting the controller
http://localhost:8080/SpringServiceJsonSample/listUsers/
http://localhost:8080/SpringServiceJsonSample/dispUser/3
please help
Hello admin,
ReplyDeleteit is not work for me,
http://localhost:8080/SpringServiceJsonSample/listUsers
i get error 404
and log said :
org.springframework.web.servlet.PageNotFound noHandlerFound
WARNING: No mapping found for HTTP request with URI [/SpringServiceJsonSample/listUsers] in DispatcherServlet with name 'rest'
Did you add a controller called ListUsersController as given in this tutorial and followed all steps after downloading the project?
DeleteThanks,
Priya
Hello Admin,
DeleteI got HTTP Status 500 - org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.web.client.HttpClientErrorException: 401 Unauthorized
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:943)
Please help, how to solve and running the code
expecting your reply
ramesh
Hello Admin,
DeleteI followed all the steps you explined in the tutorial, I got 500 error. Please can you give download as a war file?
regards
ramesh
Hi, I will like to know how I can get values returned i.e List users=restTemplate.getForObject(url, List.class); I want to get properties of the users returned e.g send email to them before binding to view. Please kindly explain how I can achieve this.
ReplyDeleteThanks
You already have the user object in the controller, so before the return statement include your logic to send email to them.
DeleteThanks, its working for me after minor changes.
ReplyDeleteHi' Priya,
ReplyDeleteCan you pl enhance your blog to demonstrate how we can consume a POST rest service, with some JSON input in body.
Thanks
Sure, I will try my best to write one whenever possible.
Deleteexcellent blog.....love u
ReplyDeletemam, i'm following your tutorial . Can you please provide add/update and delete part of this tutorial !!! I know you have done that using angularjs in the later part of these tutorial. But right now I need it without using angularjs or ajax. If you can please...
ReplyDeleteThank you
Mathematics Examples
ReplyDeleteSo nice that I found this article, was searching for exact information you have drafted in this article. Please keep sharing more like this because it is very useful for programmers and paper help professionals like us.
ReplyDeleteI think these spring RESTful services are quite effective because my friend has recently created a website of his own and with help of these web services, his business is booming. Now, I’m in a rush as I have to hire someone to Take My College Class For Me otherwise, I have so much more to discuss on the realted topic.
ReplyDeleteSuch a 3D printed residence decor will look recent and festive in your window sill. Below, we’ll share some fashionable 3D printed stuff to embellish your home home}. The list of useful 3D printed stuff within the kitchen features a bottle opener. Being extremely easy, a one-handed bottle opener 3D mannequin is every thing you need to|you should|you have to} Direct CNC address any bottle rapidly. Nowadays, many of us wish to take wonderful photos and record secure videos. Of course, you'll be able to|you presumably can} visit the closest store looking for this gadget.
ReplyDeleteNice and amazing article and I wish to come around for a more powerful update. Thanks for sharing your knowledge. I had a good time with your article. Thanks so much for sharing. plapoly nsuk-affiliated postgraduate admission form out
ReplyDelete