Post

Creating Your First Servlet in Intellij IDEA



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 IntelliJ IDEA Ultimate, as it provides built-in support for web development and server configuration, making the process straightforward and efficient.

Step 1: Creating a Maven Project

  • Open IntelliJ IDEA.
  • From the welcome screen, click New Project, or if you already have a project open, go to File -> New -> Project....
  • In the New Project dialog, select Maven Archetype on the left panel under New Project.
  • In the Name field, enter a name for your project(e.g., my-web-app).
  • From the Archetype dropdown, select org.apache.maven.archetypes:maven-archetype-webapp.
  • In the Advanced Settings dropdown, specify the following:
    • GroupId: Enter a unique group identifier (e.g., com.example).
    • ArtifactId: Enter the project name (e.g., my-web-app).
    • Version: Default is 1.0-SNAPSHOT, but you can set it to 1.0.0-SNAPSHOT if needed.
  • Click Create to create the project.

Step 2: Open the Project

Once the Maven project is created, IntelliJ IDEA will open it. 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’s recommended to click the Refresh button in the Maven tool window 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 IntelliJ IDEA, you have to configure Tomcat. Follow these steps to set it up:

  • Navigate to Run -> Edit Configurations, then clicking the + sign and selecting Tomcat Server -> Local.
  • Provide a descriptive name for your configuration, such as Tomcat Local.
  • Click Configure next to the Application Server field, then select the path to your local Tomcat installation (e.g., C:\apache-tomcat-<version> on Windows or /usr/local/apache-tomcat-<version> on macOS or /opt/apache-tomcat-<version> on Linux).
  • In the Deployment tab, click the + sign to add your project’s artifact (e.g., select war-exploded), which will be deployed to the Tomcat server.
  • In the Application Context field, enter the context path for your web application (e.g., /my-web-app). This context will be part of the URL used to access your application (e.g., http://localhost:8080/my-web-app).

By configuring Tomcat, you’ll be able to deploy and run your web applications directly from IntelliJ IDEA.

Step 7: Deploying and Accessing Your Servlet

Now that the project is configured, click the green play button in the top right corner of IntelliJ IDEA 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!”.

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.