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
  • @rickincanada Thx for your tweet! Shoot us an email at asktheteam@keyholesoftware.com so we can set up a time to talk. Have a good day.
    July 24, 2014 at 3:33 PM
  • Never used JAXB? Check out a simple usage pattern that pairs #JAXB’s data binding capabilities with JPA - http://t.co/Ki9G04HV5e
    July 24, 2014 at 9:53 AM
  • Guess what today is? Tell An Old Joke Day - http://t.co/835ORWMX6N! So, why do programmers always confuse Halloween & Xmas? 31 Oct = 25 Dec
    July 24, 2014 at 8:45 AM
  • MT @midwestio: Posted another #midwestio talk recording to our YouTube channel: @MinaMarkham on modular CSS. Watch: http://t.co/aU3LpfUoi4
    July 24, 2014 at 8:25 AM
  • We just posted pictures from our National Hot Dog Day Lunch Cookout. Check them out - http://t.co/To06plaw1C
    July 23, 2014 at 4:14 PM
  • Good free cheat sheet - #Java Performance Optimization Refcard from @DZone: http://t.co/7vBgsmqy08
    July 23, 2014 at 10:48 AM
  • Did you know today is a holiday? It's National Hot Dog Day! We're gearing up for our team lunch hot dog cookout & can't wait to celebrate.
    July 23, 2014 at 9:43 AM
  • Check out our newest blog: #JAXB – A Newcomer’s Perspective, Part 1 http://t.co/Ki9G04HV5e
    July 22, 2014 at 1:22 PM
  • New post on the Keyhole blog by Mark Adelsberger: #JAXB – A Newcomer’s Perspective, Part 1 http://t.co/Ki9G04HV5e
    July 21, 2014 at 2:27 PM
  • If you're a Java dev, you're likely familiar with Annotations. But have you created your own #Java Annotations? Ex - http://t.co/BgCsYjxZKF
    July 18, 2014 at 12:10 PM
  • RT @gamasutra: Don't Miss: Unconventional Tips for Improving your Programming Skills http://t.co/6TFox7CKHU
    July 16, 2014 at 3:20 PM
  • We're about to send out our free monthly tech newsletter. Dev tips/articles via email. Not on the list yet? Sign up - http://t.co/F8h0NSiicZ
    July 15, 2014 at 11:57 AM
  • Have you ever tried creating your own #Java annotations? See a situation where it was beneficial - http://t.co/BgCsYjxZKF
    July 15, 2014 at 8:36 AM
  • There's a new post on the Keyhole blog by @jhackett01: Creating Your Own #Java Annotations - http://t.co/BgCsYjxZKF
    July 14, 2014 at 1:43 PM
  • We love development! Have you seen our weekly team blog? We show how to be successful with the tech we use. See it - http://t.co/nlRtb1XNQH
    July 12, 2014 at 2:35 PM
  • Rapid appdev has a bad rep, but there are ways to bring development time down the right way. Don't Fear the Rapid - http://t.co/aTPcAKOj0r
    July 11, 2014 at 3:10 PM
  • Automated Testing is great for dev, but does bring a set of challenges (especially for #agile teams). Success tips: http://t.co/1acl1ngO7i
    July 11, 2014 at 12:16 PM
  • This is fantastic - One small step for Google, one giant leap for empowering girls to code: http://t.co/R90V5DBkv1
    July 10, 2014 at 2:52 PM
  • #RabbitMQ: messaging software built on AMQP protocol. Learn relevant concepts & how to avoid common "gotchas" here: http://t.co/ZwMXlhKyX8
    July 10, 2014 at 9:31 AM
  • A huge welcome to Brian Wetzel who joins the Keyhole team today!
    July 10, 2014 at 8:50 AM
Keyhole Software
8900 State Line Road, Suite 455
Leawood, KS 66206
ph: 877-521-7769
© 2014 Keyhole Software, LLC. All rights reserved.