Pr.Pg Next Pg

Methods to Set HTTP Status Code tutorials

  • There are following methods which can be used to set HTTP Status Code in your servlet program. These method are available with HttpServletResponse object.

S.N.

Method

Description

1

public void setStatus(int statusCode)

 

This method sets an arbitrary status code. The setStatus method takes an int (the status code) as an argument. If your response includes a special status code and a document, be sure to call setStatus before actually returning any of the content with the PrintWriter.

2

public void sendRedirect(String url)

 

This method generates a 302 response along with a Location header giving the URL of the new document.

3

public void sendError(int code, String message)

 

This method sends a status code (usually 404) along with a short message that is automatically formatted inside an HTML document and sent to the client.

 


 

Example: Servlet program a servlet for showing error status code 407

Sam Sir

//Program name statuscodedemo.java

// Program a servlet for showing error status code 407

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

import java.util.*;

public class statuscodedemo extends HttpServlet {

 

public void doGet(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException

{

response.sendError(407, "Need authentication!!!");

}

public void doPost(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException {

doGet(request, response);

}

}

Output

Status code demo

Pr.Pg border                                              Next Pg