Reading:
Calling REST API from JSP

Calling REST API from JSP

Metamug

//: # ()

Calling REST APIs in Java

You require a rest client library like HttpClient, OKHttp or other jax-rs client libraries to invoke REST APIs. These libraries are require us to write Java code. Writing the rest client code in scriplets is a bad idea.

Sending REST API calls from JSP tags?

We can use JSTL tags to do external api calls. The tags are reusable and do not require you to litter code inside jsp. The response from the api call is added to var attribute which can be access later in the jsp file.

<jsp:directive.page pageEncoding="UTF-8" trimDirectiveWhitespaces="true"/>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@taglib uri="http://xml.metamug.net/jsp/jstl/mason" prefix="m" %>

<%-- Your JSP Code here --%>

<m:xrequest var="echoRequest" url="https://postman-echo.com/post" output="true" method="POST" >
    <m:header name="Content-Type" value="application/json"/>
    <m:xbody>
        {
            "foo1": "${requestScope.foo1}",
            "foo2": ${requestScope.foo2}
        }
    </m:xbody>
</m:xrequest>

<c:out value="${m:jsonPath('$.args.foo1', echoRequest)}" />

<%-- Your JSP Code here --%>

If the api call needs to be made inside a rest api. Here's an example

Maven Dependency

You need to add the following dependency to your pom.xml to run mason tag library.

<dependency>
    <groupId>com.metamug</groupId>
    <artifactId>mason</artifactId>
    <version>3.3</version>
</dependency>

Download the Github Project

If your project isn't a maven project, you can add mason jar from github releases to your lib folder. There is a mason sample project with all the jar libraries.

We have added a github maven project that demonstrates the above code.

Download Fork



Icon For Arrow-up
Comments

Post a comment