Servlet Tutorial
Let's create a basic example of a Java Servlet.
In this example, we'll create a simple "Hello, World!" Servlet. This Servlet will respond to HTTP GET requests by sending back a message saying "Hello, World!"
1. Create a new Servlet class
First, you need to create a new class that extends HttpServlet
:
import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class HelloWorldServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set the response content type response.setContentType("text/html"); // Get the printwriter object from response to write the required html in the response PrintWriter out = response.getWriter(); out.println("<h1>" + "Hello, World!" + "</h1>"); } }
In this Servlet, the doGet()
method is overridden to handle HTTP GET requests. The response.setContentType("text/html")
call sets the response content type to be HTML, and response.getWriter()
gets a PrintWriter
that can be used to send output to the client. Finally, out.println("<h1>" + "Hello, World!" + "</h1>");
writes an HTML heading with the text "Hello, World!" to the response.
2. Configure the Servlet
Next, you need to configure your Servlet. This can be done using annotations or by modifying the web.xml
deployment descriptor.
Using annotations:
import javax.servlet.annotation.WebServlet; //... @WebServlet("/hello") public class HelloWorldServlet extends HttpServlet { //... }
In this example, @WebServlet("/hello")
specifies that this Servlet should handle requests to the "/hello" URL.
Using web.xml
:
<web-app> <servlet> <servlet-name>HelloWorldServlet</servlet-name> <servlet-class>com.example.HelloWorldServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloWorldServlet</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> </web-app>
In this example, a <servlet>
element is used to declare the Servlet, and a <servlet-mapping>
element is used to map the Servlet to the "/hello" URL.
3. Run the Servlet
Finally, you need to compile your Servlet and run it in a Servlet container, such as Apache Tomcat or Jetty.
Once your Servlet is running, you should be able to visit http://localhost:8080/hello
(assuming your Servlet container is running on port 8080) in your web browser and see "Hello, World!" displayed on the page.