Programmingempire
In this article on Creating a Simple HTTP Servlet, I will explain writing the code of your first servlet using the Eclipse IDE. Basically, a servlet is nothing but a java class that serves the purpose of extending the capabilities of a server. Furthermore, a servlet handles the request and response operations.
Steps for Creating a Simple HTTP Servlet
The following steps should be followed for Creating a Simple HTTP Servlet.
At first, create a Dynamic Web Project in Eclipse as shown below.

After that, provide a name to the project, and click on the Finish button.

Now that, we have created our project, right-click on Java Resources -> New -> Servlet

Now provide a name to the servlet and click on Next.

Similarly, again click on Next and then select the checkbox for the doGet() method. Further, click on the Finish button.

Since now our servlet is created, we need to add the corresponding jar file. Therefore find the Project name and right-click on it to select the Build Path option. Further, select the Configure Build Path option.

Under the Libraries tab click on the Add External JARs button.

Now we need to find and select a specific jar file. It is called the servlet-api.jar file. As can be seen, we find the specific jar file from the lib folder as shown below.

Now you can see the servlet-api.jar file under the Libraries tab. Finally, click on the OK button.

Once, we have added the necessary libraries for our servlet, we can write the code for the servlet to display a simple web page. So, first import the java.io.* package as shown below.

In order to display a simple web page, call the setContentType() method using the implicit response object and pass “text/html” as the parameter. After that, create an object of the PrintWriter class. Further, call the write() method to enclose the HTML tags. Look at the following code.
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 {
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>");
}
}
Now run the servlet to get the following output.

- Angular
- ASP.NET
- C
- C#
- C++
- CSS
- Dot Net Framework
- HTML
- IoT
- Java
- JavaScript
- Kotlin
- PHP
- Power Bi
- Python
- Scratch 3.0
- TypeScript
- VB.NET
