1. Setup
- First of you need to download Apache tomcat version 9.0 or above
- extract it to a convenient location
- go to tomcat/lib/servlet-api.jar and copy this file
servlet-api.jarinto 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
- 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>");
}}- 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
- Now first , compile the
ServletEx.javaservlet to WEB-INF/classes/ folder while including the classpath to theservlet-api.jar
javac -cp servlet-api.jar -d webapp/WEB-INF/classes src/ServletExample.java- after that change the directory to
/webapp - then package the webapp folder into a
.warfile
jar -cvf MyProject.war *- (JAR) → java archive
- -cvf → create verbose file
- filename.war
-
- → include all
5. Move to Tomcat folder
now,
- copy the MyProject.war file into
tomcat/webapps/ - go to tomcat/bin/ and open
startup.batbatch file on windows orstartup.shon linux/macOS - go to the browser at
localhost:8080/MyProject/hello(This should match the .war name and the url pattern in web.xml)