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
  • Useful #JAXB primer that illustrates the power from tools & frameworks that unobtrusively interact with POJOs - http://t.co/J1s5DpcsCp
    October 24, 2014 at 12:00 PM
  • RT @JIRA: #Agile teams webinar starts in 30 mins. It's not too late to register: http://t.co/WrpAXnvKMr
    October 23, 2014 at 1:35 PM
  • Pssst... Our free monthly newsletter comes out tomorrow with dev tips/articles via email. Not on the list? Sign up: http://t.co/F8h0NSzleZ
    October 22, 2014 at 1:46 PM
  • How do we harness the power of callbacks without the confusing mess of nested functions in #JavaScript? Promises - http://t.co/obK811q48q
    October 21, 2014 at 2:18 PM
  • Pssst... Our free monthly newsletter comes out tomorrow with dev tips/articles via email. Not on the list? Sign up: http://t.co/F8h0NSzleZ
    October 21, 2014 at 12:05 PM
  • Did you know today is Clean Your Virtual Desktop Day? It really is: https://t.co/TCRpWgTmxg Celebrate by organizing your desktop files.
    October 20, 2014 at 4:50 PM
  • Don't miss the newest post from @bricemciver: Make Me a Promise - http://t.co/obK811q48q #JavaScript
    October 20, 2014 at 10:43 AM
  • RT @DZone: #Docker 1.3 Releases with Security, Signed Images, and Process Injection by @bendzone #devops http://t.co/uytIwFPgO6
    October 17, 2014 at 10:04 AM
  • If you have 15+ years #Java exp, you don't expect to be puzzled debugging a null pointer exception. See an exception: http://t.co/m2iDgNEleK
    October 17, 2014 at 9:51 AM
  • Many on our team attended the #Royals victory last night & @cdesalvo even got a selfie with the Gov. Go #KansasCity! http://t.co/N1Psooe2CE
    October 16, 2014 at 3:39 PM
  • Interesting ExplainLikeI'm5 talk: Why do companies develop iOS first when Android holds 70% of the 'Smart' Market? http://t.co/fxgjIBmqBi
    October 16, 2014 at 12:26 PM
  • We're looking for a top-notch #Java developer to join our team. Learn more about our company culture & the role - http://t.co/0fKsFmN0Ql
    October 16, 2014 at 9:08 AM
  • Want to learn to create custom #Java annotations & process them using the Reflection API? @jhackett01's tutorials - http://t.co/mf1F3eIDY3
    October 15, 2014 at 11:43 AM
  • Happy Ada Lovelace Day! It's a celebration of the achievements of women in STEM - if there's a woman in tech that you admire, tell her today
    October 15, 2014 at 9:13 AM
  • .@fpmoles We absolutely agree - thanks for reading!
    October 15, 2014 at 8:13 AM
  • With 15 yrs exp, @bmongar didn't expect surprise when debugging a null pointer exception. Why it puzzled him - http://t.co/m2iDgNEleK #Java
    October 14, 2014 at 11:20 AM
  • #Royals fans with tickets to tonight's canceled game, here's what you need to know - http://t.co/EErHht3zoN
    October 13, 2014 at 4:23 PM
  • RT @UzilitySoftware: Watch as Wayne explains to the boss, Marvin, what an agile board is about. #scrumalliance #scrum http://t.co/5MzB1bNw…
    October 13, 2014 at 12:01 PM
  • Getting started with #MongoDB? (Flexible #NoSQL for Humongous Data) Here's a free cheat sheet from the folks @Dzone - http://t.co/oBMvICzfcL
    October 13, 2014 at 11:10 AM
  • Brad Mongar's newest post is live on the Keyhole blog - #Java and the Sweet Science http://t.co/m2iDgNEleK
    October 13, 2014 at 8:59 AM
Keyhole Software
8900 State Line Road, Suite 455
Leawood, KS 66206
ph: 877-521-7769
© 2014 Keyhole Software, LLC. All rights reserved.