Generic GUI embeddable in a jar?


Writing a GUI for a library/tool is quite common and each time the question how do I do or package it leads to a headache.

You can use any existing web framework but you risk a conflict with the application. So basically the solution is to use client side technology or a jsp/servlet.

So how to do so? First you need a servlet 3.0 server (or any JavaEE 6 server). It basically means it works in Tomcat, TomEE, Glassfish, JBoss…

Then you need to know you can put resources in META-INF/resources as if it was in your webapp directly in root folder (= accessible from the web) – I discovered it recently on Alexis MP blog.

Then in my case I didn’t want a full client side development since it was bringing back too much js dependencies and a JAXRS server to be clean…but the GUI was very light so I simply used a controller (a servlet) and few views (JSPs) that I put in META-INF/resources.

At this point my views are accessible but since my controller is not bound it is quite useless.

To bind it automatically Servlet 3.0 specification brings you javax.servlet.ServletContainerInitializer. Implementing it you get a hook called at startup and thanks to javax.servlet.ServletContext you can add your servlet. Here is my implementation:

public class MyServletInitializer implements ServletContainerInitializer {
    @Override
    public void onStartup(final Set<Class<?>> classes, final ServletContext ctx) throws ServletException {
        ctx.addServlet("My Controller", new MyController()).addMapping("/demo/*");
    }
}

And that’s all! Now i add my jar to any WEB-INF/lib and the gui is accessible :). Awesome for admin GUIs!

Advertisements

2 thoughts on “Generic GUI embeddable in a jar?

  1. jieryn

    Seems easier to just use @WebServlet or META-INF/web-fragment.xml? Or do you expect to have metadata-complete=”true” specified in the master web.xml? I think if they disable scanning, your SCI won’t be picked up anyway..

    I’m a big fan of this general method of META-INF/resources though! 🙂

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s