1. Setup

  1. First of you need to download Apache tomcat version 9.0 or above
  2. extract it to a convenient location
  3. go to tomcat/lib/servlet-api.jar and copy this file servlet-api.jar into your web project

2. Directory structure

In IntellijIdea community edition, create a new project with intellijIdea build System

MyProject
	src/
		ServletEx.java
	webapp/
		WEB-INF/
			classes/
			web.xml
	servlet-api.jar

3. Code

  1. ServletEx.java
import javax.servlet.ServletException;  
import javax.servlet.http.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
import java.io.IOException;  
  
public class ServletEx extends HttpServlet {  
    public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {  
        res.setContentType("text/html");  
        res.getWriter().println("<h1>It worked!!!</h1>");  
    }}
  1. web.xml
<web-app xmlns="http://jakarta.ee/xml/ns/jakartaee"  
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       xsi:schemaLocation="http://jakarta.ee/xml/ns/jakartaee
     http://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
     version="5.0">  
  
    <servlet>  
          <servlet-name>ServletEx</servlet-name>  
          <servlet-class>ServletEx</servlet-class>  
    </servlet>  
    
    <servlet-mapping> 
           <servlet-name>ServletEx</servlet-name>  
		 <url-pattern>/hello</url-pattern>  
    </servlet-mapping>
 
</web-app>

4. Compile and package

  1. Now first , compile the ServletEx.java servlet to WEB-INF/classes/ folder while including the classpath to the servlet-api.jar
javac -cp servlet-api.jar -d webapp/WEB-INF/classes src/ServletExample.java
  1. after that change the directory to /webapp
  2. then package the webapp folder into a .war file
jar -cvf MyProject.war *
  • (JAR) java archive
  • -cvf create verbose file
  • filename.war
    • include all

5. Move to Tomcat folder

now,

  1. copy the MyProject.war file into tomcat/webapps/
  2. go to tomcat/bin/ and open startup.bat batch file on windows or startup.sh on linux/macOS
  3. go to the browser at localhost:8080/MyProject/hello (This should match the .war name and the url pattern in web.xml)