Use Jetty Test Webapp to implement a simple test of Java library
Use Jetty Test Webapp to implement a simple test of Java library
1. Environmental configuration:
First of all, we need to ensure that the Java Development Kit (JDK) and Maven have been installed.Then, follow the steps below:
a. Create a Maven project file called pom.xml in the root directory of the project.
b. Add jetty plug -in dependencies to pom.xml file:
<build>
<plugins>
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.4.43.v20210629</version>
</plugin>
</plugins>
</build>
c. Save and turn off the pom.xml file.
2. Write test code:
Create a Java class called WebapPTESTER.JAVA in the src/main/java directory, and write the following simple test code:
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;
public class WebAppTester {
public static void main(String[] args) throws Exception {
// Create an instance of the Jetty server and specify the port number
Server server = new Server(8080);
// Create web application context
WebAppContext context = new WebAppContext();
context.setResourceBase("src/main/webapp");
context.setContextPath("/");
// Add web application context to the server
server.setHandler(context);
// Start the server
server.start();
// Wait until the server is terminated
server.join();
}
}
The above code creates an Jetty server instance and adds the context of Web application to the server.We use the default web application context path "/" and set the basic path of Web resources to src/main/webapp.Finally, we started the server and waited until it ended.
3. Write a simple HTML page:
Create a HTML file called Index.html in the src/main/webapp directory, and write the following simple page content:
html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Jetty Test Webapp</title>
</head>
<body>
<h1>Hello, Jetty!</h1>
</body>
</html>
The above code simply shows "Hello, Jetty!" In the page.
4. Run test:
In the terminal, enter the root directory of the project and execute the following commands to run the Jetty server and test code:
$ mvn jetty:run
If everything goes well, you will see the log output of some Jetty servers in the terminal, and the server will run on port 8080.
5. Test results:
Open the browser and enter "http: // localhost: 8080" in the address bar, and then press Enter.You will see a page containing the word "Hello, Jetty!" In the browser.This shows that you have successfully run Jetty Test Webapp.
Through the above steps, you have successfully used the JAVA class library to test the simple test of the Java class library.The strong performance and flexibility of Jetty make it one of the tools of developers love, especially suitable for fast construction, debugging and testing web applications.Hope this article will help you!