Home Servlets Send a Response Status in servlet

Related Tutorials


 
 

Share on Google+Share on Google+

Send a Response Status in servlet

Advertisement
All Response status is defined in HttpServletResponse Class. You can then use constants (response.SC_OK,response.SC_NOT_FOUND etc..) values to return process status to the browser.

Send a Response Status in servlet

     

This section illustrates you how to send response status in servlet.

All Response status is defined in HttpServletResponse Class. You can then use constants (response.SC_OK,response.SC_NOT_FOUND etc..) values to return process status to the browser. In the given example, two methods are defined doGet(), doPost. Constants value request and response are used to return status to browser. The setContentType() method of ServletResponse  set the content type of response.

Here the Servlet requests for page name loginForm. So if the request not found, it will show error Not found. Otherwise, it will show OK.

Here is the code of SetResponseStatus.java

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
 
public class SetResponseStatus extends HttpServlet {
 protected void doGet(HttpServletRequest request,
 HttpServletResponse response) throws ServletException, 
   IOException {
 
   doPost(request, response);
  
  }
 protected void doPost(HttpServletRequest request,
  HttpServletResponse response)
 
throws ServletException, IOException {
  response.setContentType("text/html");
 String page = request.getParameter("page");
  if (page != null && page.equals("loginForm")) {
 response.setStatus(response.SC_OK);
  else {
  response.sendError(response.SC_NOT_FOUND,
   
"The requested page ["+ page + "] not found.");
  }
  }
}
 

Above example shows how a response has been send from the servlet. If the requested page (loginForm) is not found Output will be displayed like this:

Download Source Code

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: July 17, 2008

Related Tutorials

Discuss: Send a Response Status in servlet   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com