Handling HTTP requests and responses in Java servlets

1. Handling HTTP GET Request

In this example, the servlet responds to a GET request by sending a simple HTML page.

Java




import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
  
public class MyGetServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
          
        // Set the response content type to HTML
        response.setContentType("text/html");
  
        // Get the PrintWriter object to write HTML response
        PrintWriter out = response.getWriter();
  
        // Write the HTML response
        out.println("<html><body>");
        out.println("<h2>Hello from MyGetServlet!</h2>");
        out.println("</body></html>");
    }
}


2. Handling HTTP POST Request

In this example, the servlet responds to a POST request by reading form data and sending a customized response.

Java




import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
  
public class MyPostServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
          
        // Response content type set to HTML
        response.setContentType("text/html");
  
        // Get the PrintWriter object to write HTML response
        PrintWriter out = response.getWriter();
  
        // Read form data from the request
        String name = request.getParameter("name");
  
        // Write the customized HTML response
        out.println("<html><body>");
        out.println("<h2>Hello, " + name + "!</h2>");
        out.println("</body></html>");
    }
}


3. Handling Both GET and POST Requests

A servlet can handle both GET and POST requests by implementing both doGet and doPost methods.

Java




import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
  
public class MyServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
          
        // Response content type set to HTML
        response.setContentType("text/html");
  
        // Get the PrintWriter object to write HTML response
        PrintWriter out = response.getWriter();
  
        // Write the HTML response for GET request
        out.println("<html><body>");
        out.println("<h2>Hello from MyServlet (GET)!</h2>");
        out.println("</body></html>");
    }
  
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
          
        // Response content type set to HTML
        response.setContentType("text/html");
  
        // Get the PrintWriter object to write HTML response
        PrintWriter out = response.getWriter();
  
        // Read the Form data from the request
        String name = request.getParameter("name");
  
        // Write the customized HTML response for POST request
        out.println("<html><body>");
        out.println("<h2>Hello, " + name + "!</h2>");
        out.println("</body></html>");
    }
}


Commonly Used Databases

  • MySQL:
    MySQL is really good at storing structured data in tables like your structured bookshelf where each database table is like a shelf, and each row on the database is a record containing specific information. MySQL is widely used and plays well with Java.
  • PostgreSQL:
    PostgreSQL is a bit like MySQL, but it’s known for handling complex queries and large datasets effectively.
  • SQLite:
    It’s lightweight and perfect for smaller projects somewhat like a portable notebook which you can carry around.
  • MongoDB:
    MongoDB is a NoSQL database, meaning it’s not restricted to tables like MySQL. It’s great for handling diverse types of data somewhat resembling a drawer where you can place any object.

Interaction with Java Code

Now, let’s talk about how these databases interact with Java code.

  • JDBC (Java Database Connectivity)
    • JDBC acts like a translator between Java and databases. It helps Java code communicate with databases seamlessly.
    • It is like a person who knows multiple languages and communicates between two persons who are not able to communicate directly because of language barrier.
  • Using JDBC in Java Code
    • To interact with a database, you can use JDBC in your Java code. You can specify the database, the connection details and use JDBC methods to send queries to the database and get results back.

Example:

Here’s a simplified Java code snippet using JDBC to connect to a MySQL database and retrieve data.

Java




import java.sql.*;
  
public class DatabaseExample {
    public static void main(String[] args) {
        try {
            // Connect to the database
            Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "username", "password");
  
            // Create a statement
            Statement statement = connection.createStatement();
  
            // Execute a query
            ResultSet resultSet = statement.executeQuery("SELECT * FROM My-Table");
  
            // Process the results
            while (resultSet.next()) {
                System.out.println(resultSet.getString("column1") + " " + resultSet.getString("column2"));
            }
  
            // Close the connection
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}


Real-world Example:

Let’s build a simple servlet which handles users’ login functionality. The servlet should receive the basic credentials such as username and the password from a HTML form. It will validate the credentials and provide with a successful message when the credentials are validated. Below is the servlet code.

Java




import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
  
// Servlet class to handle user login
public class GFG extends HttpServlet {
  
    // Method to handle HTTP POST requests
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
          
        // Response content type set to HTML
        response.setContentType("text/html");
  
        // Get the PrintWriter object to write HTML response
        PrintWriter out = response.getWriter();
  
        // User input retrieved from the HTML form
        String username = request.getParameter("username");
        String password = request.getParameter("password");
  
        // Validate user credentials (For simplicity, using hardcoded values)
        if ("user123".equals(username) && "pass123".equals(password)) {
            // Display welcome message for successful login
            out.println("<html><body>");
            out.println("<h2>Welcome, " + username + "!</h2>");
            out.println("</body></html>");
        } else {
            // Display an error message for unsuccessful login
            out.println("<html><body>");
            out.println("<h2>Login failed. Please check your username and password.</h2>");
            out.println("</body></html>");
        }
    }
}


Explanation of the above Program:

The LoginServlet class indicates that it is a servlet. The doPost method handles the HTTP POST requests which typically is used in case of form submission. The request.getParameter method retrieves the user input from the HTML form which are then validated against some static string value. This can be fetched from the database as an object and can be matched against the usernames and passwords in real case. Depending upon the validation results, it will display the required result.

HTML Form (index.html):

Consider an HTML form (index.html) that sends a POST request to the servlet when the user enters the credentials.

HTML




<!DOCTYPE html>
<html>
    <head>
        <title>Login Form</title>
    </head>
  
  <body>
        <h2>Login Form</h2>
        <form action="/your-web-app/login" method="post">
            Username: <input type="text" name="username"><br>
            Password: <input type="password" name="password"><br>
            <input type="submit" value="Login">
        </form>
    </body>
  
</html>


Output:

  • When a user submits the form with valid credentials (username=”user123″ and password=”pass123″), the servlet responds with a welcome message.
  • When the credentials are incorrect, the servlet responds with an error message.

Advanced Java – Getting Started to Web Application

A Web Application is software that executes on the web browser. It links the customers and the service providers as a medium of exchange. For example, Amazon provides a marketplace where sellers and buyers can coexist. It provides a mechanism to exchange services and perform operations seamlessly.

Similar Reads

Understanding Web Clients and Servers

For any operation to be performed, a service provider and a service consumer need. The same relies on web applications. The one which provides the service is the web server and the one which requires it is the web client. The web client requests the client, in return for which the client responds. This is usually done through HTTP protocol and that’s the reason, why sometimes a web server is also known as an HTTP server....

Client-Server Communication

Client-server communication is usually done through TCP/IP protocol. TCP covers part of transport and the sessions layer in a typical OSI model. TCP being a connection-oriented protocol makes sure that the connection remains in place till the messages are exchanges at the very end of the queue....

Introduction to Servlets

...

Web Application Architecture

Servlets acts as the server-side heroes that processes the requests from the users’ web browser and sends back the response after the required manipulation is completed. Imagine it to be a communication channel between your server and users’ web browsers....

Java Web Frameworks

...

Handling HTTP requests and responses in Java servlets

1. Monolithic Architecture...

When to Choose a Framework

Java web frameworks acts like toolkits for building web applications. These frameworks provide you with a set of rules to make your job easier, you are being the master for the application. Two popular ones are Spring MVC and its close friend, Hibernate....