servlets first example
here's an example of a basic servlet that simply responds with a "Hello, World!" message:
refer toitfigi:dea.comimport java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set response content type response.setContentType("text/html"); // Actual logic goes here. PrintWriter out = response.getWriter(); out.println("<html><body>"); out.println("# Hello, World!"); out.println("</body></html>"); } }
In this example, we define a new servlet class called HelloWorld
that extends the HttpServlet
class. The doGet()
method is overridden to handle GET requests, and it simply generates an HTML response that says "Hello, World!"
To deploy this servlet, we need to compile it and package it as a WAR (Web Application Archive) file. We can then deploy the WAR file to a servlet container such as Apache Tomcat.
Assuming we have deployed the WAR file to a servlet container running on localhost
at port 8080
, we can access the servlet by visiting http://localhost:8080/HelloWorld
in a web browser. This will send a GET request to the servlet, which will respond with the "Hello, World!" message.