Tools

Partitioning SPA Resources and API Implementations in Separate WAR Components

by on February 4, 2014 1:03 pm

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 Java EE 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 Java EE 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 Java EE 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 &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

  • Share:

Leave a Reply

Things Twitter is Talking About
  • There's a new blog from @ChrisShatrov - Becoming a Better Full-Stack Developer: Switching from Back to Front http://t.co/sYvZbWNdI6
    July 7, 2015 at 8:52 AM
  • .@Jinaljay transitioned to #Java from .NET & needed to switch IDEs. Tips that helped her in the switch to #eclipse - http://t.co/wbx9qFUAqp
    July 6, 2015 at 4:05 PM
  • Protip: Code For Maintainability So The Next Developer Doesn’t Hate You -http://t.co/G0gFOD7Pyj
    July 6, 2015 at 3:55 PM
  • Doing #Agile with a Distributed and/or Remote Team? No Problem! Tools and techniques for success - http://t.co/XrYJE8Xict
    July 6, 2015 at 12:35 PM
  • New to #JavaScript prototypal inheritance? Here are some notes to help you along the way - http://t.co/NTIDZS6Uhy
    July 5, 2015 at 7:55 AM
  • ICYMI: we've released a demo version of #GrokOla which is open to the public. Try out its features & capabilities - http://t.co/O4ladowmFU
    July 4, 2015 at 3:05 PM
  • Happy 4th of July from the Keyhole team! We hope that you have a happy and safe holiday with your family and friends.
    July 4, 2015 at 9:55 AM
  • Let's talk testing. Here are common challenges #Agile teams face when writing automated tests & how to overcome them: http://t.co/DrKbNZJcE0
    July 3, 2015 at 11:06 AM
  • #GrokOla users get free educational tutorials. But lucky you, we've released some to the public. #JavaScript primer - http://t.co/nIR9XiWY6O
    July 3, 2015 at 10:55 AM
  • Being able to isolate debugging techniques can help make you a better debugger. Here's Time-Oriented #Debugging http://t.co/UplJgP4VzC
    July 2, 2015 at 10:50 AM
  • RT @zachagardner: @zachagardner has declared it is @ChipotleTweets day at @KeyholeSoftware . You have been warned 🐓🐖🐄
    July 2, 2015 at 10:09 AM
  • Current state of random number generation & the differences in how #Java & #JavaScript approach it - http://t.co/5tBKNXnu8T #security
    July 1, 2015 at 2:45 PM
  • Woohoo - 600 followers! Thanks, everyone. We'd love to ask you - what type of tweets / dev content would you like to see more of from us?
    July 1, 2015 at 10:38 AM
  • We would like to welcome Dallas Monson to the team today! Dallas is a Senior Architect focused on UI/UX and #JavaScript. Welcome, Dallas!
    July 1, 2015 at 8:35 AM
  • Good introduction to TypeScript - http://t.co/0N22fVpAHt Plus, how to approach modularization in #TypeScript - http://t.co/wxRWGBj3Uh
    June 30, 2015 at 3:25 PM
  • .@mrbristopher just delivered a new S911 Night Drone to James Hayes, winner of our #kcdc15 giveaway! Congrats, James! http://t.co/RriJIxubH2
    June 30, 2015 at 11:35 AM
  • It feels like primitives could have been left out of the initial implementation of #Java. See why - http://t.co/A8ChCBHXJO
    June 29, 2015 at 4:05 PM
  • Developers in a bounce house! I repeat, developers in a bounce house! We had a blast at our 1st company picnic. Pics: http://t.co/XIqs7ECUst
    June 29, 2015 at 1:40 PM
  • New #SpringBatch tutorial from @jhackett01: Spring Batch – Replacing XML Job Configuration With JavaConfig http://t.co/PmdXnriKQu #java
    June 29, 2015 at 11:46 AM
  • We had such a fun time at the Keyhole company picnic! Pictures to come, including some of our developers in the bounce house. #loveourteam
    June 29, 2015 at 8:41 AM