set different status code in HTTP
In Java, when developing web services using frameworks like JAX-RS or Servlets, you often need to set different HTTP status codes in the response to indicate the outcome of the request. HTTP status codes range from informational responses (1xx) to successful (2xx), redirection (3xx), client error (4xx), and server error (5xx). Here’s how you can set different status codes programmatically.

Table of Contents
Explanation
- 1. Â HTTP Status Codes :
- HTTP status codes are standardized response codes that indicate the result of an HTTP request.
- They are part of the HTTP protocol and provide information about the request’s success, failure, or redirection.
- 2. Â Setting Status Codes in Java :
- In Java web applications, you can set status codes using APIs provided by the web framework you are using (e.g., Servlets API or JAX-RS API).
- This is typically done by accessing the response object and calling appropriate methods to set the status code and optionally set additional headers or response content.
Example in Java
Here’s an example using Servlets to set different HTTP status codes based on certain conditions:
Syntax
java
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("/status-example")
public class StatusExampleServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Example: Set HTTP status code 200 (OK)
response.setStatus(HttpServletResponse.SC_OK);
// Example: Set HTTP status code 404 (Not Found)
// response.setStatus(HttpServletResponse.SC_NOT_FOUND);
// Example: Set HTTP status code 500 (Internal Server Error)
// response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
// You can also use custom status codes if needed
// response.setStatus(451); // Custom status code: Unavailable For Legal Reasons
// Optionally, set response content or headers
// response.setContentType("text/plain");
// response.getWriter().println("Response content here");
}
}
Explanation of the Example
- Servlet Example : The StatusExampleServlet demonstrates setting different HTTP status codes (SC_OK, SC_NOT_FOUND, SC_INTERNAL_SERVER_ERROR) using HttpServletResponse’s setStatus method.
- Custom Status Code : You can set custom status codes (like 451 in the example) if needed, although it’s typically better to use standard HTTP status codes for interoperability.
- Response Content : Optionally, you can set the content type and write response content using setContentType and getWriter methods.