Servlet HTTP Status Codes

HTTP status codes are issued by a server in response to a client's request made to the server. It includes codes from IETF Request for Comments (RFCs), other specifications, and some additional codes used in some common applications of the HTTP.

In this tutorial, we'll learn how to handle HTTP status codes in a Servlet.

Step 1: Create a new dynamic web project

Just like in previous tutorials, create a new dynamic web project in your IDE.

Step 2: Create a new Servlet

Create a new servlet in your project. We'll name it "StatusCodeServlet" for this tutorial.

Step 3: Write the Servlet code

In the created servlet, write the following code:

package com.example;

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;

@WebServlet("/StatusCodeServlet")
public class StatusCodeServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String statusCode = request.getParameter("status");

        if(statusCode != null){
            switch(statusCode){
                case "200":
                    response.setStatus(HttpServletResponse.SC_OK);
                    response.getWriter().println("<h1>Status 200: OK</h1>");
                    break;
                case "400":
                    response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Bad request!");
                    break;
                case "404":
                    response.sendError(HttpServletResponse.SC_NOT_FOUND, "Resource not found!");
                    break;
                case "500":
                    response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error!");
                    break;
                default:
                    response.setStatus(HttpServletResponse.SC_OK);
                    response.getWriter().println("<h1>Status 200: OK</h1>");
            }
        } else {
            response.setStatus(HttpServletResponse.SC_OK);
            response.getWriter().println("<h1>Status 200: OK</h1>");
        }
    }
}

In this servlet, we get a status code from the request parameters. Depending on the provided code, we set the response status using the setStatus or sendError methods of the HttpServletResponse object. The sendError method is used when we want to send an error along with a short description.

Step 4: Running the Servlet

Run the servlet on your server.

You should now be able to see different HTTP status codes in response to different requests. For example, if the server is running on your local machine, you can access your servlet at http://localhost:8080/StatusCodeServlet/StatusCodeServlet?status=400 to simulate a "Bad Request" error.

This is a basic example. In a real-world application, the status code would be determined by the logic of your application (e.g., whether a requested resource exists, whether provided data is valid, etc.).

  1. Setting HTTP status codes in Servlet: Set the HTTP status code in a Servlet response.

    response.setStatus(HttpServletResponse.SC_OK); // 200 OK
    
  2. Custom HTTP status codes in Servlet: Define and use custom HTTP status codes.

    response.setStatus(450); // Custom status code
    
  3. Servlet HTTP 404 error handling: Handle HTTP 404 errors in a Servlet.

    • Redirect or display a custom error page.
    response.setStatus(HttpServletResponse.SC_NOT_FOUND); // 404 Not Found
    
  4. Handling different HTTP status codes in Servlet: Implement different behaviors based on HTTP status codes.

    if (response.getStatus() == HttpServletResponse.SC_OK) {
        // Handle success
    } else if (response.getStatus() == HttpServletResponse.SC_NOT_FOUND) {
        // Handle 404
    }
    
  5. Servlet response redirection and status codes: Redirect to another URL and set the appropriate status code.

    response.sendRedirect("/new-page");
    
  6. Servlet sendError method for status codes: Use sendError method to send an error response with a specific status code.

    response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access Denied");
    
  7. Servlet response.setStatus method: Set the HTTP status code using response.setStatus().

    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); // 500 Internal Server Error
    
  8. Servlet HTTP 500 internal server error: Handle internal server errors in a Servlet.

    • Log the error and display a friendly error page.
    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    
  9. HTTP status code constants in Servlet: Use constants like HttpServletResponse.SC_OK for common status codes.

    response.setStatus(HttpServletResponse.SC_OK);
    
  10. Handling 302 and other redirect status codes in Servlet: Handle different redirect status codes (e.g., 302 for temporary redirect).

    • Use HttpServletResponse.SC_MOVED_TEMPORARILY for a 302 redirect.
    response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
    
  11. Servlet response headers and status codes: Combine status codes with response headers.

    • Set headers before setting the status code.
    response.setHeader("Content-Type", "text/html");
    response.setStatus(HttpServletResponse.SC_OK);