Preview:
java 
Copy code 
import javax.servlet.*; 
import java.io.IOException; 
import java.io.PrintWriter; 
public class MyServlet implements Servlet { 
public void init(ServletConfig config) throws ServletException {} 
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { 
PrintWriter out = res.getWriter(); 
out.println("Hello Servlet Lifecycle!"); 
} 
public void destroy() {} 
public ServletConfig getServletConfig() { return null; } 
public String getServletInfo() { return null; } 
} 
Step 1: Install Apache Tomcat 
Download and install Apache Tomcat. 
Set up Tomcat by configuring the environment variables (CATALINA_HOME and JAVA_HOME), if necessary. 
Step 2: Save Your Java Code 
Save your servlet code in a file named MyServlet.java. 
Ensure that this file is located in the WEB-INF/classes directory within your web application directory 
structure. For example: 
Copy code 
your-webapp ├── WEB-INF │   ├── classes │   │   └── MyServlet.java │   └── web.xml  
Step 3: Compile the Servlet 
Open a terminal or command prompt and navigate to the WEB-INF/classes directory. 
Compile the servlet: 
bash 
Copy code 
javac -classpath <path-to-servlet-api.jar> MyServlet.java  
Replace <path-to-servlet-api.jar> with the path to the servlet-api.jar file in your Tomcat installation, typically 
located in the lib folder. 
Step 4: Configure web.xml 
In the WEB-INF folder, create or update the web.xml file with the following content: 
xml 
Copy code 
<web-app>     <servlet>         
class>     
<servlet-name>MyServlet</servlet-name>         
</servlet>     <servlet-mapping>         
<servlet-class>MyServlet</servlet
<servlet-name>MyServlet</servlet-name>         
pattern>/myservlet</url-pattern>     </servlet-mapping> </web-app>  
This configuration maps the servlet to the URL path /myservlet. 
Step 5: Deploy and Run 
<url
Copy your web application folder (your-webapp) into the webapps directory of your Tomcat installation. 
Start Tomcat by running the startup.sh (Linux/Mac) or startup.bat (Windows) file located in the bin directory 
of your Tomcat installation. 
Open a web browser and navigate to http://localhost:8080/your-webapp/myservlet. 
Expected Output 
If the servlet is configured and deployed correctly, you should see: 
plaintext 
Copy code 
Hello Servlet Lifecycle!  
If there’s an error, the Tomcat logs (located in the logs directory of your Tomcat installation) will contain 
information to help you debug. 
downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter