Packaging embedded tomcat server

First time ever using tomcat/setting up a webapp from scratch so please be mercyful. I have created an embedded tomcat server which basically looks like this:

public class Server implements Runnable {
private Tomcat tomcat;

public Server() {
    tomcat = new Tomcat();
    tomcat.setPort(8080);

    tomcat.addWebapp("", new File("src/webapp").getAbsolutePath());
}

@Override
public void run() {
    try {
        tomcat.start();
        tomcat.getServer().await();
    } catch (LifecycleException e) {
        e.printStackTrace();
    }
}

And I run it in a main that looks like this:

public static void main(String[] args) throws Exception {
    Thread thread = new Thread(server);
    thread.start();

    Foo foo = new Foo();

    (thread.isAlive()) {
        foo.doStuff();
        TimeUnit.HOURS.sleep(interval);
    }
}

The purpose of the program is to run the http-server on one thread while the class Foo does some stuff in the backend once every so-and-so hours. Probably not the correct way to create a webapp, but it’s the best I’ve managed.

However, now that I’m trying to package it I’m running into issues because once it is packaged (using Maven) the Server doesn’t seem to be able to find the webapp-folder. After a couple hours of googling and trying out a a lot of stuff involving war:s and jar:s I’ve come to the conclusion that there is something about this embedded tomcat stuff that I’m not understanding.

So, my questions are:

  1. Is the way I’ve implemented my webapp correct? I’m getting the feeling that it’s not but I can’t really confirm it.

2a. If incorrect, how does one do it correctly?

2b. If correct, how does one package it into a runnable jar/war?

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

This is a little bit of a non-standard way of going about it. Rather than writing all your own application logic to handle an integrated web server, would you not consider leveraging something that’s already there? You can create a Java project in Spring boot which contains its own embedded web server.

There’s a sample starter example here that should get you going – https://spring.io/guides/gs/serving-web-content/

I would recommend this approach rather than writing it yourself as Spring Boot is an industry standard that is widely used, proven, and tested.