Post

Creating Your First Servlet in Eclipse



Introduction

Java Servlets are a powerful tool for building dynamic web applications. They allow developers to handle client requests, process data, and generate responses, all within the robust environment of the Java ecosystem. In this article, we’ll walk through the process of creating your first servlet, step by step, from setting up your development environment to deploying the servlet on a server.

Creating Your First Servlet

Prerequisites

Before we begin, ensure you have the following installed:

  • Java Development Kit (JDK)
    Make sure the JDK is installed on your machine. If not, follow this guide to do so.
  • Apache Tomcat
    Make sure the Apache Tomcat is installed on your machine. If not, follow this guide to do so.
  • Integrated Development Environment (IDE)
    To create servlets, you will need Eclipse IDE for Enterprise Java and Web Developers, as it includes built-in support for web development, servlets, and server configuration, simplifying the development process.

Step 1: Creating a Maven Project

  • Open Eclipse.
  • From the welcome screen, select File -> New -> Maven Project.
  • In the New Maven Project dialog that appears click Next.
  • In the next window, you’ll see a list of available archetypes. Select maven-archetype-webapp from the list and click Next.
  • In the next window, enter your project information:
    • Group Id: Enter a unique group identifier (e.g., com.example).
    • Artifact Id: Enter your project name (e.g., my-web-app).
    • Version: Default is 1.0.0-SNAPSHOT.
  • Click Finish.
  • When prompted in the console, type Y and press Enter to confirm the creation of the project.

Step 2: Open the Project

Once the Maven project is created, you should see the following project structure:

1
2
3
4
5
6
7
8
9
10
my-web-app
|-- src
|   |-- main
|   |   |-- java
|   |   |-- resources
|   |   |-- webapp
|   |       |-- WEB-INF
|   |           |-- web.xml
|   |       |-- index.jsp
|-- pom.xml

Step 3: Add Dependencies to pom.xml

Open the pom.xml file and add the necessary dependency for servlets:

1
2
3
4
5
6
7
8
<dependencies>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
        <scope>provided</scope>
    </dependency>
</dependencies>

After adding the dependency, it is recommended to right-click on the project in Eclipse, then select Maven -> Update Project... to ensure that Maven reloads the project and updates the dependencies correctly.

Step 4: Create a Servlet Class

  • In your project, create a new package under src/main/java (e.g., com.example).
  • Create a new Java class inside this package. Name it HelloServlet.
  • Make this class extend HttpServlet, which is provided by the Java Servlet API:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    
    package com.example;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    @WebServlet("/hello")
    public class HelloServlet extends HttpServlet {
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<h1>Hello, My First Servlet!</h1>");
        }
    }
    

    Explanation:

    • @WebServlet annotation maps the servlet to the /hello URL pattern. This means that when a user accesses http://localhost:8080/my-web-app/hello, this servlet will be invoked.
    • doGet() method handles HTTP GET requests. When a GET request is received, the servlet generates an HTML response with the text Hello, My First Servlet!.

Step 5: Configure web.xml (Optional)

In most modern Java EE applications, you can configure servlets using annotations like @WebServlet. However, if you prefer, you can also configure your servlet in the web.xml file, which is found in the WEB-INF directory of your project.

Here’s how you could define the HelloServlet in web.xml:

1
2
3
4
5
6
7
8
9
<servlet>
    <servlet-name>HelloServlet</servlet-name>
    <servlet-class>com.example.HelloServlet</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>HelloServlet</servlet-name>
    <url-pattern>/hello</url-pattern>
</servlet-mapping>

Step 6: Set Up Tomcat for Development

To run a web application in Eclipse, you have to configure Tomcat. Follow these steps to set it up:

  • You can add a Tomcat server by navigating to Window -> Show View -> Servers.
  • In the bottom panel of Eclipse, locate the Servers tab. If it’s not visible, you can enable it through Window -> Show View -> Servers. In the Servers tab, right-click and select New -> Server. Alternatively, if no servers are configured, you will see a blue link that says No servers are available. Click this link to create a new server... – click on it to proceed.
  • Choose Apache from the list, then select the version of Tomcat that you have installed (e.g., Tomcat v10.0 Server) and click Next.
  • For Windows:
    • In the window that opens, navigate to the location where Tomcat is installed (e.g., C:\).
    • Select the folder containing apache-tomcat-<version> and click Open.
  • For MacOS:
    • In the Finder window that opens, locate the dropdown with the name of the current folder you are in and click on it.
    • Select Macintosh HD to navigate to the root directory.
    • Press Cmd + Shift + . to reveal hidden files and folders.
    • Navigate to the location where Tomcat is installed (e.g., /usr/local/).
    • Select the folder containing apache-tomcat-<version> and click Open.
  • For Linux:
    • In the window that opens, navigate to the location where Tomcat is installed (e.g., /opt/).
    • Press Ctrl + L to open a path input field.
    • Type the path to the folder containing apache-tomcat-<version> and press Enter.
    • Select the folder and click Open.
  • Click Finish to add the server to Eclipse and start using it for your project.

Step 7: Deploying and Accessing Your Servlet

Now that the project is configured, right-click on your project in the Project Explorer and select Run As -> Run on Server. In the dialog that appears, select your installed Tomcat server from the list and click Finish to start Tomcat and deploy your web application.

Open a web browser and go to the following URL:

1
http://localhost:8080/my-web-app/hello

You will see the output generated by your servlet, displaying “Hello, My First Servlet!”.

Step 8: How to Stop Tomcat in Eclipse

To stop the Tomcat server in Eclipse, follow these steps:

  • Locate the Servers tab at the bottom of the Eclipse window. If it is not visible, you can open it by navigating to Window -> Show View -> Servers.
  • In the Servers tab, find your Tomcat server.
  • Right-click on the server and select Stop to shut down the server.

Conclusion

Congratulations! You have successfully created your first Java servlet, deployed it on Apache Tomcat, and accessed it through a web browser. Servlets form the backbone of Java web applications, allowing dynamic content generation and interaction with clients. Explore further by adding more functionality, handling form submissions, managing sessions, and integrating with databases to build robust web applications using Java servlets.

© 2024 Java Tutorial Online. All rights reserved.