Follow these steps to create a standalone application with Jersey and Tomcat:
Adding Maven dependencies
Add the following dependencies to your pom.xml:
8.5.4
2.23.2
UTF-8
org.apache.tomcat.embed
tomcat-embed-core
${tomcat.version}
org.apache.tomcat.embed
tomcat-embed-jasper
${tomcat.version}
org.apache.tomcat
tomcat-jasper
${tomcat.version}
org.apache.tomcat
tomcat-jasper-el
${tomcat.version}
org.apache.tomcat
tomcat-jsp-api
${tomcat.version}
org.glassfish.jersey.containers
jersey-container-servlet
${jersey.version}
Adding Maven plugins
Add the following plugins to your pom.xml:
tomcat-embedded-sample
org.apache.maven.plugins
maven-compiler-plugin
3.5.1
true
1.8
1.8
org.apache.maven.plugins
maven-shade-plugin
2.4.3
tomcat-embedded-sample-${project.version}
package
shade
com.example.launch.Launcher
Creating a launcher class
Define a launcher class as following:
public class Launcher {
public static void main(String[] args) throws Exception {
new Launcher().start();
}
public void start() throws Exception {
String contextPath = "";
String appBase = ".";
String port = System.getenv("PORT");
if (port == null || port.isEmpty()) {
port = "8080";
}
Tomcat tomcat = new Tomcat();
tomcat.setPort(Integer.valueOf(port));
tomcat.getHost().setAppBase(appBase);
Context context = tomcat.addWebapp(contextPath, appBase);
Tomcat.addServlet(context, "jersey-container-servlet",
new ServletContainer(resourceConfig()));
context.addServletMapping("/api/*", "jersey-container-servlet");
tomcat.start();
tomcat.getServer().await();
}
private ResourceConfig resourceConfig() {
return new JerseyConfiguration();
}
}
Defining Jersey configuration
Create a class to configure your Jersey application:
public class JerseyConfiguration extends ResourceConfig {
public JerseyConfiguration() {
packages("com.example");
}
}
Creating resource classes
Define your resource class. The following is just an example:
@Path("hello")
public class HelloWorldResource {
@GET
@Produces(MediaType.TEXT_PLAIN)
public Response helloWorld() {
return Response.ok("Hello World").build();
}
}
Compiling and running the application
To compile and run the application, follow these steps:
Open a command line window or terminal.
Navigate to the root directory of the project, where the pom.xml resides.
Compile the project: mvn clean compile.
Package the application: mvn package.
Look in the target directory. You should see a file with the following or a similar name: tomcat-embedded-sample-1.0-SNAPSHOT.jar.
Change into the target directory.
Execute the JAR: java -jar tomcat-embedded-sample-1.0-SNAPSHOT.jar.
The application is available at http://localhost:8080/api/hello.