SetStatus in Servlet

SetStatus in Servlet


Posted in : Java Posted on : June 23, 2011 at 8:23 PM Comments : [ 0 ]

In this section we will discuss how can you set a response status in servlet.

SetStatus in Servlet

In this section we will discuss how can you set a response status in servlet.

In Servlet we can set a response status using Response status, which are defined in HttpServletResponse interface for example :- SC_NOT_FOUND, SC_REQUEST_TIMEOUT , SC_NOT_ACCEPTABLE , SC_NO_CONTENT  etc. These constants sent the status to the browser. The example is given below I used the doGet() method and set status on requesting of page "p" if the page did not find i.e. p= = null by the getParameter() it will show the page not found as set the status SC_NOT_FOUND else it will indicate the client to continue with the page "p".

Exmaple :

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SetStatus extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
String p = req.getParameter("p");
if (p == null) {
res.sendError(res.SC_NOT_FOUND, "Requested page {" + p
+ "} not found.");
} else {
res.sendError(res.SC_CONTINUE);
}
}
}

web.xml

<web-app version="2.4">
<servlet>
<servlet-name>SetStatus</servlet-name>
<servlet-class>SetStatus</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>SetStatus</servlet-name>
<url-pattern>/SetStatus</url-pattern>
</servlet-mapping>

</web-app>

Output : When you will execute this program you will find the following output.

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics