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
  • In Part 2 of our series on creating your own #Java annotations, learn about processing them with the Reflection API - http://t.co/E1lr3RmjI7
    September 17, 2014 at 3:18 PM
  • We send out our free monthly tech newsletter tomorrow - dev tips/articles via email. Not on the list? Sign up: http://t.co/h8kpjn419s
    September 16, 2014 at 2:58 PM
  • Want to chuckle? If programming languages were vehicles -http://t.co/quqHsUFCtR #funny
    September 16, 2014 at 11:41 AM
  • In Part 2 of our series on creating your own annotations, learn about processing #Java annotations using Reflection: http://t.co/DJZvQuarkc
    September 16, 2014 at 9:06 AM
  • Don't miss @jhackett01's newest post on the Keyhole blog - Processing #Java Annotations Using Reflection: http://t.co/E1lr3RmjI7
    September 15, 2014 at 12:02 PM
  • We're pretty excited - Keyhole's #BikeMS team raised 158% of their fundraising goal to benefit @MidAmericaMS. Plus, they had a great ride!
    September 15, 2014 at 10:38 AM
  • A huge welcome to David Kelly (@rheomatic) who officially joins the Keyhole team today! :-)
    September 15, 2014 at 10:00 AM
  • Sending warm thoughts to @eastlack, @cdesalvo, @wdpitt & all participating in #BikeMS this AM. Thanks for helping in the fight against MS!
    September 13, 2014 at 8:10 AM
  • .@rheomatic We are so excited to have you joining the team! Welcome :-)
    September 12, 2014 at 4:11 PM
  • As the official holiday is a Saturday, we're celebrating today! Happy (early) #ProgrammersDay to you! http://t.co/1CvUfrzytE
    September 12, 2014 at 1:55 PM
  • Tomorrow @cdesalvo, @eastlack, & @wdpitt are riding #BikeMS to benefit @MidAmericaMS. You can get involved, too - http://t.co/9boQwEUxth
    September 12, 2014 at 11:00 AM
  • RT @AgileDevs: 5 tips for great code reviews http://t.co/9PdbtEv0z8
    September 11, 2014 at 2:53 PM
  • The BEMs of Structuring #CSS - http://t.co/159suYtfx6 A quick introduction to the Block Element Modifier methodology.
    September 10, 2014 at 2:49 PM
  • A huge welcome to Joseph Post (@jsphpst) who has joined the Keyhole team this week!
    September 10, 2014 at 9:52 AM
  • @TheGrisExplores Absolutely, and thanks for the compliment! Here's an article that you might find helpful, too - http://t.co/7oxpaohCS1
    September 9, 2014 at 2:22 PM
  • Express.js seems to be the top pick! MT @TheGrisExplores: "what's your fave server-side MVC framework for NodeJS when SPA is not an option?"
    September 9, 2014 at 1:56 PM
  • RT @TheGrisExplores: Yo @KeyholeSoftware dudes and dudettes: what is your favorite server-side MVC framework for NodeJS when SPA is not an …
    September 9, 2014 at 1:15 PM
  • There is a new post on the Keyhole blog by @brianletteri - The BEMs of Structuring CSS: http://t.co/159suYtfx6
    September 9, 2014 at 12:12 PM
  • Know a bright grad? We're looking for a business support / recruiting representative to join our team in Kansas City: http://t.co/GDvFVmoMF9
    September 8, 2014 at 11:31 AM
  • A huge welcome to @jeremygard who joins the Keyhole team today!
    September 8, 2014 at 8:40 AM
Keyhole Software
8900 State Line Road, Suite 455
Leawood, KS 66206
ph: 877-521-7769
© 2014 Keyhole Software, LLC. All rights reserved.