Create a Jetty project using Eclipse

Introduction

Overview

Development environment

Development environment construction ①: OpenJDK 11 installation

JRE (Java Runtime Environment) is required to run Java Servlet, Eclipse, and Jetty. Here, download OpenJDK to get the JRE. If you do not have JRE installed, you will get an error when starting Eclipse, so you need to do it before installing Eclipse.

  1. Go to the official OpenJDK website below and click the jdk.java.net/14 link in the Download section. (The link for jdk.java.net/14 changes every time OpenJDK is upgraded.) https://openjdk.java.net/

  2. Click Java SE 11 in the list of links on the left. (If you want to download the latest version of OpenJDK, you can download OpenJDK from this site.) https://jdk.java.net/14/

  3. Click Windows / x64 Java Development Kit. https://jdk.java.net/java-se-ri/11

  4. "openjdk-11 + 28_windows-x64_bin.zip" will be downloaded.

  5. When the download is complete, unzip it to any folder and add the absolute path of "jdk-11 \ bin" to your system environment variables. (Here, I unzipped it to C: \ openjdk and added "C: \ openjdk \ jdk-11 \ bin" to the system environment variables.)

  6. Start a command prompt and check the Java version. (If it is openjdk 11, it is OK.)

    >java --version
    openjdk 11 2018-09-25
    OpenJDK Runtime Environment 18.9 (build 11+28)
    OpenJDK 64-Bit Server VM 18.9 (build 11+28, mixed mode)
    

Development environment construction (2): Eclipse installation

After the OpneJDK installation is complete, install Eclipse.

  1. Go to the Eclipse package installer download site and click "Windows 64-bit" in the "Eclipse IDE for Java Developers". https://www.eclipse.org/downloads/packages/

  2. When you are on the download page, click the Download button.

  3. eclipse-java-2020-06-R-win32-x86_64.zip will be downloaded.

  4. When the download is complete, unzip it to any folder and double-click "eclipse.exe". (You will be required to enter the workspace folder path at startup, but leave the default settings.)

Development environment construction ③: Jetty acquisition

Get Jetty from the following site.

  1. From the following site, click ".zip" of "Eclipse Jetty Downloads". ⇒ jetty-distribution-9.4.31.v20200723.zip will be downloaded. https://www.eclipse.org/jetty/download.html

  2. When the download is complete, unzip it to any folder.

Eclipse initial settings

Initialize Eclipse before creating a project. If you set it once at the beginning, you do not need to set it from the next time.

  1. Execute the main menu "Window"> "Preferences" to launch the "Preferences" dialog.

  2. Select Java> Installed JREs from the tree on the left and make sure the OpenJDK 11 path is set.

  3. Set the character code. Here, we will change it for Linux assuming that it will also work on Linux. Select "General"> "Workspace" from the tree on the left, check "Other" in "Text file encoding", and select "UTF-8". Also, check "Other" in "New text file line delimiter", select "Unix", and press the "Apply" button.

  4. Change the font to prevent garbled characters. Select "General"> "Appearance"> "Colors and Fonts" from the tree on the left, select "Java Editor Text-Font", and press the "Edit" button to launch the "Fonts" dialog. Change the font in the "Font" dialog and press the "Apply" button. (Here, I changed to MS Gothic. Depending on the font you select, the characters may be garbled, so select a font that does not garble.)

  5. Press the Apply and Close button.

Project creation

First, create a project.

  1. Click File> New> Java Project on the main menu to launch the New Java Project dialog.

  2. Enter the project name in the "Project name" field and press the "Finish" button. (Here, the project name is "sample" and other settings are left as default.)

  3. When the "New module-info.java" dialog is launched, press the "Don't Create" button.

  4. Confirm that the sample project tree has been generated on "Package Explorer".

Add Jetty library

Jetty can configure the server in XML and start the server using "start.jar", or you can import the library and implement the server configuration in Java. In this case, we will implement it in the latter way, so we will add the library to the project.

  1. Select the top node of the tree on Package Explorer, right-click and click the pop-up menu Properties to open the Properties dialog.

  2. Select "Java Build Path" in the tree on the left, open the "Libraries" tab, select the "Classpath" node, press the "Add External JARs" button, select the Jetty library below, and select " Press the "Finish" button.

[Additional library] ・ Jetty-http-9.4.31.v20200723.jar ・ Jetty-io-9.4.31.v20200723.jar ・ Jetty-security-9.4.31.v20200723.jar ・ Jetty-server-9.4.31.v20200723.jar ・ Jetty-servlet-9.4.31.v20200723.jar ・ Jetty-util-9.4.31.v20200723.jar ・ Jetty-webapp-9.4.31.v20200723.jar ・ Servlet-api-3.1.jar ~~~

Create main class

Next, create the main class (the class that contains the main method). Implement the WEB server settings in the main class.

  1. Select the top node of the tree on "Package Explorer", right-click and click the pop-up menu "New"> "Class" to launch the "New Java Class" dialog.

  2. Enter the class name in the "Name" field, check "public static void main (String [] args)", and click the "Finish" button. (Here, enter "SampleMain" in the "Name" field.)

  3. The "sample"> "src"> "sample"> "SampleMain.java" node is added to the tree on "Package Explorer".

  4. The source code of SampleMain.java is generated as follows.

    package sample;
    
    public class SampleMain {
    
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    	}
    
    }
    
  5. Add the following import process to SampleMain.java.

    package sample;
    
    

// ↓ Add from here import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.handler.HandlerList; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; // ↑ Add up to here

public class SampleMain {
~~~
  1. Add the following implementation to main () in SampleMain.java. Here, add "/" to the URI so that the path of the HTML file placed on the project is the URI. Also, set the WEB server to start using port 8080.

public static void main (String [] args) throws Exception {// Add throws Exception // TODO Auto-generated method stub // Comment out // ↓ Add from here // Add "/" to URI (add to handler) ServletHolder holder = new ServletHolder(new SampleServlet()); ServletContextHandler handler = new ServletContextHandler(); handler.addServlet(holder, "/");

// Set the handler in the handler list HandlerList handlerList = new HandlerList(); handlerList.setHandlers(new Handler[] {handler});

// Create server Server server = new Server (8080); // Instantiate a server using the 8080 port server.setHandler (handlerList); // Set the handler list to the server instance server.start (); // Start the server // ↑ Add up to here } ~~~

Servlet creation

Create a Servlet. After creating the class, add doGet () and doPost () using Eclipse's automatic method generation feature. doGet () works when it receives a GET method. The GET method operates when the WEB server is accessed from the client's WEB browser. Also, doPost () works when it receives a POST method. The POST method works when data is sent from the client's web browser form to the web server.

  1. Select the top node of the tree on "Package Explorer", right-click and click the pop-up menu "New"> "Class".

  2. Enter the class name in the "Name" field and "javax.servlet.http.HttpServlet" in the "Superclass" field and press the "Finish" button. (Here, enter "SampleServlet" in the "Name" field.)

  3. The "sample"> "src"> "sample"> "SampleServlet.java" node is added to the tree on "Package Explorer".

  4. Select the tree node "SampleServlet.java" on the "Package Explorer" and click "Source"> "Override / Inplement Methods" in the main menu to open the "Override / Inplement Methods" dialog.

  5. Check "HttpServlet", "doGet" and "doPost" and click "OK" button to generate doGet method and doPost method.

    package sample;
    
    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 SampleServlet extends HttpServlet {
    
    	@Override
    	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    		// TODO Auto-generated method stub
    		super.doGet(req, resp);
    	}
    
    	@Override
    	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    		// TODO Auto-generated method stub
    		super.doPost(req, resp);
    	}
    
    }
    
  6. Add the following import process to SampleServlet.java.

    package sample;
    
    import java.io.IOException;
    

import java.io.BufferedReader; // Add import java.io.OutputStream; // add import java.io.FileReader; // add

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

@SuppressWarnings ("serial") // Added public class SampleServlet extends HttpServlet { ~~~

  1. Change doGet () in SampleServlet.java to the following implementation. When the WEB server is accessed from the WEB browser, the HTML file of the WEB page is read and this is set in the response body so that it responds.

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    	// TODO Auto-generated method stub
    

//super.doGet (req, resp); // Comment out

// ↓ Add from here // Character encoding (measures against garbled Japanese characters) req.setCharacterEncoding("UTF-8"); resp.setContentType("text/html; charset=UTF-8");

	String page = "";
	String line;

// Read HTML file @SuppressWarnings("resource") BufferedReader buf = new BufferedReader(new FileReader("." + req.getRequestURI().toString())); while((line = buf.readLine()) != null){ page += line; }

// Create response body OutputStream msgbody = resp.getOutputStream(); msgbody.write(page.getBytes()); msgbody.close(); // ↑ Add up to here } ~~~

  1. Change doPost () in SampleServlet.java to the following implementation. When data is sent from the form of the web browser to the web server, the request parameter (data sent from the client) is acquired and set in the response body to respond.

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    	// TODO Auto-generated method stub
    

//super.doPost (req, resp); // Comment out

// ↓ Add from here // Character encoding (measures against garbled Japanese characters) req.setCharacterEncoding("UTF-8"); resp.setContentType("text/html; charset=UTF-8");

String result = "The following message was written

\ n";

// Get request parameters if(req.getParameter("send").equalsIgnoreCase("write")){ result += req.getParameter("name"); }

// Create response body OutputStream msgbody = resp.getOutputStream(); msgbody.write(result.getBytes()); msgbody.close(); // ↑ Add up to here } ~~~

WEB page creation

Create a web page to display on the client's web browser. You can embed HTML statements in the source code of the Servlet, but if you create a file, you can create another web page just by replacing the file.

  1. Select the top node of the tree on "Package Explorer", right-click and click the pop-up menu "New"> "Folder" to launch the "New Folder" dialog.

  2. Enter the folder name (here "content") in the "Foler name" field and press the "Finish" button to add the tree node "content".

  3. Select the tree node "content", right-click and click the pop-up menu "New"> "File" to launch the "Create New File" dialog.

  4. Enter the file name (here "index.html") in the "Foler name" field and press the "Finish" button to add the tree node "index.html". The configuration of "Package Explorer" is as follows.

  5. Open the tree node "index.html" and add the following HTML.

    <html>
    	<head>
    		<title>sample</title>
    	</head>
    	<body>
    

Enter text here

~~~

Build

For builds, enable automatic builds so that they build automatically.

  1. Select the top node of the tree on "Package Explorer", right-click and click the pop-up menu "Reflesh" to automatically update the file structure of the tree on "Package Explorer" to the current state. ..

  2. Check "Project"> "Build Automatically" in the main menu to enable automatic build. (If the build is not executed, click "Project"> "Clean" in the main menu.)

Run

Run it when you have a build. First, use Eclipse to start a web server on Windows and access it from a web browser.

  1. Click Run> Run Configurations on the main menu.

  2. Select Java Application> Sample Main from the tree in the Run Configurations dialog.

  3. Open the "Main" tab, enter the project name in the "Project" field and the class name including the main method in the "Main class" field, and press the "Apply" button.

  4. Press the Run button in the Run Configurations dialog, or press the Run button on the icon.

  5. When you start a web browser and access the following URL, the client sends a GET method to the server and the following web page is displayed. http://localhost:8080/sample

  6. Enter the text and press the "write" button, the client will send the POST method to the server and a web page like the one below will be displayed.

JAR file creation

Create a JAR file (a collection of files necessary for the operation of the WEB application) to deploy (make it available).

  1. Select the top node of the tree on Package Explorer, right-click and click the pop-up menu Export to open the Export dialog.

  2. Select the tree node "Java"> "Runnable JARfile" and press the "Next" button.

  3. Select the tree node "Tomcat", set the main class in the "Launch configuration" field, and press the "Browser" button to open the "Save As" dialog.

  4. Enter the JAR file name to save in the "File name" field and click the "Save" button.

  5. When the path of the JAR file to be saved is reflected in the "Export destination" field, click the "Finish" button.

  6. The JAR file will be generated in the path set in the "Export destination" field.

Deployment environment

From here, prepare for deployment. Here, we will deploy to Raspberri Pi.

Deployment environment construction: OpenJDK 11 installation

First, install Java.

  1. Install OpenJDK 11 used for development on Raspberri Pi.

    $ sudo apt-get install openjdk-11-jdk
    

Deploy

When the deployment environment is ready, deploy it.

  1. Place the JAR file and content folder anywhere on the machine where you can run Java.

  2. Start the WEB server.

    $ java -jar -Dfile.encoding=UTF-8 sample.jar
    
  3. When you start a web browser and access the following URL, the client sends the GET method to the server and the following web page is displayed. http: // {IP address of Raspberry Pi}: 8080 / sample

  4. Enter the text and press the "write" button, the client will send the POST method to the server and the following web page will be displayed.

Recommended Posts

Create a Jetty project using Eclipse
Create a tomcat project using Eclipse
Create a Java project using Eclipse
Create a tomcat project using Eclipse Pleiades All in One
Create a fortune using Ruby
Create a base for your batch processing project in Eclipse.
Create a filtering function using acts-as-taggable-on
Create a Servlet program in Eclipse
Create a Maven project with a command
Create a memo app with Tomcat + JSP + Servlet + MySQL using Eclipse
Create a web environment quickly using Docker
Create a RESTful API service using Grape
Deploy a Tomcat-based Eclipse project on Heroku
Create a prefectural select bar using active_hash
Create a login function using Swift's Optional
Create Maven Project
[Android] Create a sliding menu without using NavigationView
Create a Privoxy + Tor environment instantly using Docker
Let's create a REST API using WildFly Swarm.
[Rails] How to create a graph using lazy_high_charts
Create a simple batch processing framework in Eclipse.
Create a Spring Boot application using IntelliJ IDEA
[1st] How to create a Spring-MVC framework project
Create a portfolio app using Java and Spring Boot
Create a Java development environment using jenv on Mac
Eclipse ~ Java project creation ~
[Java] Create a filter
[CentOS, Eclipse] Load a library file in a C project
How to create a Spring Boot project in IntelliJ
[Spring Boot] How to create a project (for beginners)
A memorandum when trying to create a GUI using JavaFX
Create Maven Web Project
Create a login authentication screen using the session function
Programmatically import a Maven project from your own Eclipse plugin
Create a Hello World web app with Spring framework + Jetty
Create a MOB using the Minecraft Java Mythicmobs plugin | Preparation 1
[Rails] Launch a new project
Creating a calendar using Ruby
Create a java method [Memo] [java11]
[Java] Create a temporary file
Create a VS Code Plugin.
Create a playground with Xcode 12
Using Amateurs UML in Eclipse
Make a rhombus using Java
How to create a method
Create a name input function
How to create a jar file or war file using the jar command
How to make a hinadan for a Spring Boot project using SPRING INITIALIZR
[Rails 6] How to create a dynamic form input screen using cocoon
Create a static file that expands variables using the ERB class
[Implementation procedure] Create a user authentication function using sorcery in Rails
[Swift] Create a project with Xcode (ver 12.1) and display "Hello, World!"
How to create a new Gradle + Java + Jar project in Intellij 2016.03
Easy way to create a mapping class when using the API
Oracle Cloud [OCI]: Create a CentOS Stream instance using Compute's cloud-init