java
Copy code
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
public class HelloServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
PrintWriter out = response.getWriter();
out.println("Hello from HttpServlet!");
}
}
Step 1: Install Apache Tomcat
Download and install Apache Tomcat.
Set up Tomcat by configuring environment variables (CATALINA_HOME and JAVA_HOME), if needed.
Step 2: Save and Structure Your Servlet
Save the servlet code in a file named HelloServlet.java.
Organize it within the WEB-INF/classes directory inside your web application folder. For example:
Copy code
your-webapp
├── WEB-INF
│ ├── classes
│ │ └── HelloServlet.java
│ └── web.xml
Step 3: Compile the Servlet
Open a terminal or command prompt, navigate to WEB-INF/classes, and compile:
bash
Copy code
javac -classpath <path-to-servlet-api.jar> HelloServlet.java
Replace <path-to-servlet-api.jar> with the path to servlet-api.jar in the lib folder of your Tomcat installation.
Step 4: Configure web.xml
In the WEB-INF folder, create or update web.xml with the servlet mapping:
xml
Copy code
<web-app>
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
Step 5: Deploy and Start Tomcat
Place the your-webapp folder in Tomcat’s webapps directory.
Start Tomcat by running startup.sh (Linux/Mac) or startup.bat (Windows) in the bin folder.
Step 6: Access the Servlet
Open a browser and navigate to: http://localhost:8080/your-webapp/hello
Expected Output
If everything is set up correctly, you should see:
plaintext
Copy code
Hello from HttpServlet!
Preview:
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