Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / API

Partitioning SPA Resources and API Implementations in Separate WAR Components

0.00/5 (No votes)
10 Feb 2014CPOL3 min read 4.5K  
How to partition 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:

Example 1

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:

Example 2

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:

XML
<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:

Java
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 &lt;init-param&gt;");
        }
    }
    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.

– David Pitt, asktheteam@keyholesoftware.com

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)