The following code shows a Program to create a servlet that displays the welcome message. Basically, in the following program, we create an HTTP Servlet. So we define the doGet() method that executes on the GET request. Accordingly, this method takes the request and response parameters of the type HttpServletRequest, and HttpServletResponse respectively.

As can be seen in the code, first we call the setContentType() method with a parameter of “text/html”. It will set the content type of the response that this servlet generates. After that, we create an object of the type PrintWrite. It creates an output stream for the response.

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
@WebServlet("/MyServlet")
public class MyServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    public MyServlet() {
        super();
          }
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html");
		PrintWriter out=response.getWriter();
		out.print("<html><head>My First Servlet</head><body>");
		out.print("<center><h2>");
		out.print("Welcome to HTTP Servlets</h2></center>");
		out.print("<p>doGet() Method is executing....</p>");
		out.print("</body></html>");
	}
}

Output

Output of the Program to create a servlet that displays the welcome message
Output of the Program to create a servlet that displays the welcome message