Tomcat is a commonly used Java Web application server, and deploying WAR packages is a common practice for publishing and running Web applications in Tomcat. This article will introduce the detailed steps of deploying WAR packages under Tomcat and provide specific code examples.
1.1 Create a file named HelloWorld
folder and create the following directory structure under the folder:
|- HelloWorld |- WEB-INF |- classes |- lib |- web.xml |- index.html
1.2 Write a simple HTML page in the index.html
file. The content can be arbitrary.
1.3 Create a web.xml
file in the WEB-INF
directory, and configure Servlet mapping and other related information in it. The following is a simple example:
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"> <display-name>HelloWorld</display-name> <servlet> <servlet-name>HelloServlet</servlet-name> <servlet-class>com.example.HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloServlet</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> </web-app>
1.4 Write a Java class named HelloServlet
to implement a simple Servlet class. The following is an example:
package com.example; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; @WebServlet("/hello") public class HelloServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<body>"); out.println("<h1>Hello, World!</h1>"); out.println("</body>"); out.println("</html>"); } }
1.5 Compile the Java class file and compile the # The ##.class file is copied to the
WEB-INF/classes directory.
1.6 Copy all dependent jar packages to the
WEB-INF/lib directory.
HelloWorld.war.
directory of Tomcat.
2.2 Run the Tomcat server and wait for it to automatically decompress and deploy the WAR package. http://localhost:8080/HelloWorld/ in the browser to access the homepage of the application.
The above is the detailed content of Detailed guide to deploying WAR packages in Tomcat. For more information, please follow other related articles on the PHP Chinese website!