Tuesday, December 26, 2017

Create embedded Jetty Java application

Here are the exact steps:

1. Download and install Eclipse:
https://www.eclipse.org/downloads/ 

2. Crete New Maven Project:



3. Create a simple project (skip archetype selection)

4. Configure project with following values:


 

5. In the end, your project structure shall look like this:


 

6. Edit pom.xml by adding latest Jetty dependencies. You can find it from here:

https://www.eclipse.org/jetty/download.htmlhttps://www.eclipse.org/jetty/download.html


pom.xml shall look like this:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.dtechnotes</groupId>
  <artifactId>embedded-jetty-java</artifactId>
  <version>1.0.0</version>
  <dependencies>
 <!--Jetty  dependencies-->
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-server</artifactId>
            <version>9.4.8.v20171121</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-servlet</artifactId>
            <version>9.4.8.v20171121</version>
        </dependency>
        <!--Jetty  dependencies end-->
    </dependencies>
</project>


7. Add 2 new packages as per below:



8.  Add 2 new Java classes for each of the above packages:
 9. JettyJavaMain.java

package com.dtechnotes.jettyjava;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;

import com.dtechnotes.jettyjava.servlet.TestServlet;

public class JettyJavaMain {
    public static void main(String[] args) throws Exception {

        Server server = new Server(8082);
        ServletContextHandler handler = new ServletContextHandler(server, "/dtech");
        handler.addServlet(TestServlet.class, "/");
        server.start();

    }
}


10. TestServlet.java

package com.dtechnotes.jettyjava.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.jetty.http.HttpStatus;

public class TestServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        resp.setStatus(HttpStatus.OK_200);
        resp.getWriter().println("<b>This is my first Jetty Test</b>");
    }
}


11.  You can run directly JettyJavaMain.java class and get result by navigating to:
http://localhost:8082/dtech/



12. Additionaly, you can export to single jar file using the Eclipse export feature:
File -> Export -> Runnable Jar File

13.  And run the jar file with the same results as step 11 above:







 
 

No comments:

Post a Comment