Tuesday, 5 February 2013

Request and Response | Java J2EE Tutorial pdf

Request and Response

Request
One of the main motivations for building Web pages dynamically is so that the result can be based upon user input. javax.servlet.ServletRequest and javax.servlet.http.HttpServletRequest interface provides different methods to access user input.
Reading Form Data from Servlets:-
One of the nice features of servlets is that all of this form parsing is handled automatically. We simply call the getParameter method of the HttpServletRequest, supplying the case-sensitive parameter name as an argument. We use getParameter exactly the same way when the data is sent by GET as we do when it is sent by POST. The servlet knows which request method was used and automatically does the right thing behind the scenes. The return value is a String corresponding to the URL-decoded value of the first occurrence of that parameter name. An empty String is returned if the parameter exists but has no value, and null is returned if there was no such parameter. If the parameter could potentially have more than one value, we should call getParameterValues (which returns an array of strings) instead of getParameter (which returns a single string). The return value of getParameterValues is null for nonexistent parameter names and is a one-element array when the parameter has only a single value. Parameter names are case sensitive so, for example, request.getParameter("Param1") and request.getParameter("param1") are not interchangeable. Finally, although most real servlets look for a specific set of parameter names, for debugging purposes it is sometimes useful to get a full list. Use getParameterNames to get this list in the form of an Enumeration, each entry of which can be cast to a String and used in a getParameter or get ParameterValues call. Just note that the HttpServletRequest API does not specify the order in which the names appear within that Enumeration.
A simple servlet called ThreeParams that reads form data parameters named param1, param2, and param3 and print their values:-
ThreeParamsForm.html
<HTML>
<HEAD>
<TITLE>Collecting Three Parameters</TITLE>
</HEAD>
<BODY >
<H1 ALIGN="CENTER">Collecting Three Parameters</H1>
<FORM ACTION="ThreeParams">
First Parameter: <INPUT TYPE="TEXT" NAME="param1"><BR>
Second Parameter: <INPUT TYPE="TEXT" NAME="param2"><BR>
Third Parameter: <INPUT TYPE="TEXT" NAME="param3"><BR>
<CENTER>
<INPUT TYPE="SUBMIT">
</CENTER>
</FORM>
</BODY>
</HTML>

Output:-


ThreeParams.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ThreeParams extends HttpServlet {
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Reading Three Request Parameters";
out.println(ServletUtilities.headWithTitle(title) +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=CENTER>" + title + "</H1>\n" +
"<UL>\n" +
" <LI><B>param1</B>: "
+ request.getParameter("param1") + "\n" +
" <LI><B>param2</B>: "
+ request.getParameter("param2") + "\n" +
" <LI><B>param3</B>: "
+ request.getParameter("param3") + "\n" +
"</UL>\n" +
"</BODY></HTML>");
}
}

Output:-

One of the keys to creating effective servlets is understanding how to manipulate the HyperText Transfer Protocol (HTTP). We need to discuss HTTP information that is sent from the browser to the server in the form of request headers. Note that HTTP request headers are distinct from the form data discussed in the previous chapter. Form data results directly from user input and is sent as part of the URL for GET requests and on a separate line for POST requests. Request headers, on the other hand, are indirectly set by the browser.

Reading Request Headers from Servlets:-

Reading headers is straightforward; just call the getHeader method of HttpServletRequest, which returns a String if the specified header was supplied on this request, null otherwise. Header names are not case sensitive. So, for example, request.getHeader("Connection") and request.getHeader("connection") are interchangeable. There are a couple of headers that are so commonly used that they have special access methods in HttpServletRequest.
=> getCookies
The getCookies method returns the contents of the Cookien header, parsed and stored in an array
of Cookie objects.
=> getContentLength
The getContentLength method returns the value of the Content-Length header (as an int).
=> getContentType
The getContentType method returns the value of the Content-Type header (as a String).
=> getHeaderNames
Rather than looking up one particular header, we can use the getHeaderNames method to get an Enumeration of all header names received on this particular request.
=> getMethod
The getMethod method returns the main request method (normally GET or POST, but things like HEAD, PUT, and DELETE are possible).
=> getRequestURI
The getRequestURI method returns the part of the URL that comes after the host and port but before the form data. For example, for a URL of http://randomhost.com/servlet/search.BookSearch, getRequestURI would return /servlet/search.BookSearch.
Next example shows a servlet that simply creates a table of all the headers it receives, along with their associated values.
ShowRequestHeaders.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
/** Shows all the request headers sent on this
* particular request.
*/
public class ShowRequestHeaders extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Servlet Example: Showing Request Headers";
out.println(ServletUtilities.headWithTitle(title) +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=CENTER>" + title + "</H1>\n" +
"<B>Request Method: </B>" +
request.getMethod() + "<BR>\n" +
"<B>Request URI: </B>" +
request.getRequestURI() + "<BR>\n" +
"<B>Request Protocol: </B>" +
request.getProtocol() + "<BR><BR>\n" +
"<TABLE BORDER=1 ALIGN=CENTER>\n" +
"<TR BGCOLOR=\"#FFAD00\">\n" +
"<TH>Header Name<TH>Header Value");
Enumeration headerNames = request.getHeaderNames();
while(headerNames.hasMoreElements()) {
String headerName = (String)headerNames.nextElement();
out.println("<TR><TD>" + headerName);
out.println(" <TD>" + request.getHeader(headerName));
}
out.println("</TABLE>\n</BODY></HTML>");
}
/** Let the same servlet handle both GET and POST. */
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}

Output:-

Response
Response is an object to assist a servlet in sending a response to the client.
javax.servlet.ServletRequest and javax.servlet.http.HttpServletRequest provides different methods to add data in response object.
Common method of javax.servlet.ServletRequest are:-
void flushBuffer()
Forces any content in the buffer to be written to the client.
int getBufferSize()
Returns the actual buffer size used for the response.
String getContentType()
Returns the content type used for the MIME body sent in this response.
ServletOutputStream getOutputStream()
Returns a ServletOutputStream suitable for writing binary data in the response.
PrintWriter getWriter()
Returns a PrintWriter object that can send character text to the client.
void reset()
Clears any data that exists in the buffer as well as the status code and headers.
void setBufferSize(int size)
Sets the preferred buffer size for the body of the response.
void setContentLength(int len)
Sets the length of the content body in the response In HTTP servlets, this method sets the HTTP Content-Length header.
void setContentType(String type)
Sets the content type of the response being sent to the client, if the response has not been committed yet.
Next example send response in the form of Microsoft Excel file format. For this content type should be “application/vnd.ms-excel”.
ContentTypeDemo.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ContentTypeDemo extends HttpServlet {
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("application/vnd.ms-excel");
PrintWriter out=res.getWriter();
Enumeration e=req.getHeaderNames();
out.println("\tName\tCity\tAdd");
out.println("\tsandeep1\tbang1\tbang1");
out.println("\tsandeep2\tbang2\tbang2");
}
}

Output:


Common method of javax.servlet.http.HttpServletRequest are:-
void addCookie(Cookie cookie)
Adds the specified cookie to the response.
void addHeader(String name, String value)
Adds a response header with the given name and value.
String encodeURL(String url)
Encodes the specified URL by including the session ID in it, or, if encoding is not needed, returns the URL unchanged.
void sendError(int sc)
Sends an error response to the client using the specified status code and clearing the buffer.
void sendRedirect(String location)
Sends a temporary redirect response to the client using the specified redirect location URL.
void setHeader(String name, String value)
Sets a response header with the given name and value.
In next example sendError() is used to send 500(Internal Server Error) using program code--
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class errordemo extends HttpServlet {
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
response.sendError(500);
}
}

Output:

No comments: