About Keyhole Software

Keyhole is a midwest-based consulting firm with a tight-knit technical team. We work primarily with Java, JavaScript and .NET technologies, specializing in application development. We love the challenge that comes in consulting and blog often regarding some of the technical situations and technologies we face.

Partitioning SPA Resources and API Implementations in Separate WAR Components

Single Page Applications are quickly gaining traction as a way to implement rich, robust, and mobile friendly web-based applications. Essentially, this requires a shift in application architecture where the entire application user interface is implemented using JavaScript and the server side code supplies a RESTful, JSON-based API for  server side application logic and data access. This model is shown below:

example1

A case for separate client and server side deployment components

This SPA shift provides user experience and performance benefits as well as an opportunity to completely decouple the user interface from server side logic. Decoupling the UI from application logic is something we do from a code partitioning standpoint by applying the Model View Controller (MVC) pattern. From a deployment application life cycle perspective, they are still coupled – that is, the application is packaged and deployed with static client side elements and server side elements in one component.

It seems that the natural instinct is to package both client and server side elements into a single JEE WAR component. This can make the application lifecycle simpler, however, the construction of the application seems to naturally organize developers working on the UI and developers working on the server side API, and even more since two different development languages are used. So, instead of one WAR, separating applications into separate deployable WARs for UI and server side API elements can provide the following benefits:

  • API remains stable for UI development (not a moving target)
  • UI controls when server side API changes are introduced
  • Supports concurrent developer paths of UI and API layers
  • Changes to UI can be tested and moved into QA and production environments without having to retest the API layer
  • Underlying API implementation/technology can be changed without impacting UI
  • UI implementation/technology can change without impacting API
  • Opportunity to introduce UI elements during runtime (exploits JavaScripts dynamic behavior)

Here’s a picture of this topology:

example2

How?

Since UI is implemented with dynamic JavaScript, a JEE WAR component does not have to be used to house UI resources. Any web server such as Apache or the very popular Node.js server can be used. However, enterprises that already have support for JEE will have lifecycle support for WARs in place, and it keeps the door open for using server side dynamic behavior for initial loading of resources, authentication, and integrating or mediating things in a dynamic manner.

For example, instead of initial loading of the SPA with index.html, an index.jsp could be used to apply some user/client specific logic to the loading process.

Servlet Solution

One solution to supporting SPA API/endpoints is to implement a servlet in static content SPA WAR that will redirect API URL routes to a server where the endpoint resides. This is accomplished by defining a servlet in the web.xml with a mapping for API calls to the server.

Here’s an example web.xml configuration that handles URIs starting with API:

<servlet>
  		<servlet-name>api</servlet-name>
		<display-name>api</display-name>
		<servlet-class>com.khs.spa.servlet.ApiServlet</servlet-class>
		<init-param>
			<param-name>redirect</param-name>
			<param-value>localhost:8080/khs-command-ref</param-value>
		</init-param>

	</servlet>

	<servlet-mapping>
		<servlet-name>api</servlet-name>
		<url-pattern>/api/*</url-pattern>
	</servlet-mapping>

The servlet will redirect to the API WAR(s) based upon the URL defined in the redirect initialization parameter value shown above.

The API servlet implementation that redirects API HTTP GET/POST/PUT/DELETE requests is shown below:

package com.khs.spa.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ApiServlet extends HttpServlet {
    private static final long serialVersionUID = 4345668988238038540L;
    private String redirect = null;
    @Override
    public void init() throws ServletException {
        super.init();
        // load redirect for servlet
        redirect = getServletConfig().getInitParameter("redirect");
        if (redirect == null) {
            throw new RuntimeException("redirect value not set in servlet <init-param>");
        }
    }
    private void doService(HttpServletRequest request,
    HttpServletResponse response) throws RuntimeException, IOException {
        // you could do extra stuff here, i.e. logging etc...
        String path = request.getRequestURI().split(request.getContextPath())[1];
        String route = redirect + path;
        response.sendRedirect(route);
    }
    @Override
    protected void doPost(HttpServletRequest request,
    HttpServletResponse response) throws ServletException, IOException {
        doService(request, response);
    }
    @Override
    protected void doGet(HttpServletRequest request,
    HttpServletResponse response) throws ServletException, IOException {
        doService(request, response);
    }
    @Override
    protected void doPut(HttpServletRequest request,
    HttpServletResponse response) throws ServletException, IOException {
        doService(request, response);
    }
    @Override
    protected void doDelete(HttpServletRequest request,
    HttpServletResponse response) throws ServletException, IOException {
        doService(request, response);
    }
    @Override
    protected long getLastModified(HttpServletRequest req) {
        return super.getLastModified(req);
    }
    @Override
    protected void doHead(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
        super.doHead(req, resp);
    }
    @Override
    protected void doOptions(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
        super.doOptions(req, resp);
    }
    @Override
    protected void doTrace(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
        super.doTrace(req, resp);
    }
}

Considerations

This approach assumes a stateless API implementation. Since a redirect is involved, if the API WAR is session-based, it will not work unless some kind of federated session mechanism is in place. Authentication and authorization mechanisms can occur either at the client SPA UI-WAR and/or the API layer. Likewise, if multiple API services or enterprise systems need to be accessed for the SPA, they can still be applied in the SPA UI-WAR.

Single Page Applications not only allow us to implement rich/responsive user interfaces, but promote the usage of lightweight, easy-to-use restful APIs for data and application logic. This physical runtime decoupling of the user interface makes the notion of a “throwaway” user interface more realistic, and the availability of reusable services via an API layer more achievable.

 

Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

Leave a Reply


eight − = 4



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books