Java Servlet is a program that generates dynamic web pages in a web application implemented in Java. The WEB application is a server / client system, and as shown in the figure below, the client sends a request to the server, and the server returns a response to the client to operate.
Java Servlet does not work alone, but with software called a Servlet container. Jetty corresponds to this Servlet container. Jetty is lightweight and easy to install. When you send a request from your web browser to your web server, Jetty receives this request. The Servlet generates a dynamic web page according to the type of request, and Jetty sends this dynamic web page as a response to the web browser. The web browser displays this dynamic web page.
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.
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/
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/
Click Windows / x64 Java Development Kit. https://jdk.java.net/java-se-ri/11
"openjdk-11 + 28_windows-x64_bin.zip" will be downloaded.
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.)
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)
After the OpneJDK installation is complete, install Eclipse.
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/
When you are on the download page, click the Download button.
eclipse-java-2020-06-R-win32-x86_64.zip will be downloaded.
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.)
Get Jetty from the following site.
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
When the download is complete, unzip it to any folder.
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.
Execute the main menu "Window"> "Preferences" to launch the "Preferences" dialog.
Select Java> Installed JREs from the tree on the left and make sure the OpenJDK 11 path is set.
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.
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.)
Press the Apply and Close button.
First, create a project.
Click File> New> Java Project on the main menu to launch the New Java Project dialog.
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.)
When the "New module-info.java" dialog is launched, press the "Don't Create" button.
Confirm that the sample project tree has been generated on "Package Explorer".
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.
Select the top node of the tree on Package Explorer, right-click and click the pop-up menu Properties to open the Properties dialog.
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 ~~~
Next, create the main class (the class that contains the main method). Implement the WEB server settings in the main class.
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.
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.)
The "sample"> "src"> "sample"> "SampleMain.java" node is added to the tree on "Package Explorer".
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
}
}
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 {
~~~
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 } ~~~
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.
Select the top node of the tree on "Package Explorer", right-click and click the pop-up menu "New"> "Class".
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.)
The "sample"> "src"> "sample"> "SampleServlet.java" node is added to the tree on "Package Explorer".
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.
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);
}
}
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 { ~~~
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 } ~~~
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 } ~~~
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.
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.
Enter the folder name (here "content") in the "Foler name" field and press the "Finish" button to add the tree node "content".
Select the tree node "content", right-click and click the pop-up menu "New"> "File" to launch the "Create New File" dialog.
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.
Open the tree node "index.html" and add the following HTML.
<html>
<head>
<title>sample</title>
</head>
<body>
Enter text here p>