? Copyright Marcus Green 2007
1.3) Using the HttpServletResponse interface, write code to set an HTTP response header, set the content type of the response, acquire a text stream for the response, acquire a binary stream for the response, redirect an HTTP request to another URL, or add cookies to the response.
Headers are meta data sent with HTTP requests, and as such are not displayed within the browser.
“The information, in the form of a text record, that a user’s browser sends to a Web server containing the details of what the browser wants and will accept back from the server. The request header also contains the type, version and capabilities of the browser that is making the request so that server returns compatible data.”
http://isp.webopedia.com/TERM/H/HTTP_request_header.html
A common example of a header is If-modified-Since. The server will only return the file if it has been changed since a certain date and time. This can be of benefit in that it saves on bandwidth, as it may not be necessary to retrieve a file.
The HttpServletResponse interface supports two methods for setting headers. They are
void addHeader(String name, String value) void setHeader(String name, String value)
The key difference between these two methods is that setHeader will overwrite an existing value and addHeader will add an additional value. A typical example of using these methods is to set the content type, thus both of the following are valid calls.
setHeader(”content-type”,”text/html”); addHeader(“content-type”,”text/html”);
Note that these calls are the equivalent of using the setContentType method and you could use any valid MIME type as the value.
The HttpServletResponse class provides the method getWriter that returns an instance of the PrintWriter class that allows a servlet to write back to the browser. As you have seen in the HelloWorldServlet this is commonly used to output HTML. The signature of the method is as follows.
PrintWriter getWriter() throws java.IOException
This is a little like using the default output with a Java application where you can simply write using System.out. Note how the stream is flushed to close it once you have finished using it. Because Servlets may be used by many people at once it is important to let go of any resources once you have finished with them. The following code is a typical way of using getWriter. If you compile this Servlet and request it, “Hello World” should appear in your browser.
/**
**@author Marcus Green
* SCWCD Objective 1.3
*Aquiring a text stream
**/
package com.examulator;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class TextStreamServlet extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response){
try{
PrintWriter out = response.getWriter();
out.print("<h1>Hello world </h1>");
}catch(IOException ioe){/* do something such as logging */}
}
}Although the content of most HTTP responses will be a page of HTML there are times when you may want to send a binary file of some other type. For example you might have a process that zips up a log file and sends that binary file to the browser. The browser needs to be told the type of file it is receiving so it can deal with it appropriately. There is little point in a browser rendering a zip file simply as a page of the characters it contains. It makes sense if it brings up the helper application that knows how to unzip the file.
The HTTPServletResponse interface supplies a method definition called
void setContentType(String)
which takes a string parameter that represents the MIME type of the response. MIME stands for Multi-purpose Internet Mail Extensions and were originally designed as a way to indicate the content of files that were attached to emails. Now they are a generalised way of describing the type of a file or stream. The ServletResponse interface supplies the getOutputStream method for getting hold of a stream. As the HttpServletResponse interface passed to the doGet method implements ServletResponse, it is available as in the following code which sends a zip file to a browser
/*
* BinaryStreamServlet.java
*
* Created on 16 May 2007, 19:37
*/
package com.examulator;
import java.io.*;
import java.net.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class BinaryStreamServlet extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
response.setContentType("application/zip"); /* set the MIME type */
File f= new File("myzip.zip");
byte[] arBytes = new byte[(int) f.length()];
FileInputStream is= new FileInputStream(f);
is.read(arBytes);
OutputStream os = response.getOutputStream();
os.write(arBytes);
os.flush();
}
}
To make this code work you will have to find out where your servlet container treats as its root for looking at files. This will not be the same as the web root of your web application.
HttpServletResponse provides a method called sendRedirect that will redirect the browser to a different URL. The servlet can inspect the content of a request and then depending on the content redirect the browser to a different URL. There are two important points to be aware of with sendRedirect. The sendRedirect method is not transparent to the web browser, the browser “sees” the redirect. The other point is that you cannot perform a redirect on the response has been committed. A response is committed as soon as the servlet starts to write anything to the output stream. If you attempt a re-direct after the response is committed you will receive an IllegalStateException error. The sendRedirect method can accept a relative or absolute URL.
|
|
The sendRedirect method can accept a relative or absolute URL |
The following servlet will look at the incoming request and redirect the browser to whatever URL is passed via the query string to the parameter url.
/**
**@author Marcus Green
* SCWCD Objective 1.3
* using sendRedirect
**/
package com.examulator;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class myservlet extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response){
String url = request.getParameter("url");
try{
PrintWriter out = response.getWriter();
response.sendRedirect(url);
out.print("This will not appear in the browser");
}catch(IOException ioe){/* log error */ }
}
}
Calling this servlet with the querystring
myservlet?url=http:/www.javaranch.com
Will cause the browser to move towards that Cowboy/Java haven known as JavaRanch.
Cookies are name/value pairs that are used to maintain a link between an individual browsing a web site and the web server. They were designed to help overcome the problem that HTTP is essentially a “stateless” protocol, i.e. after each request the web server “forgets” about that client. They are the mechanism through which when you go to a site like Google it can “remember” what your preferred language is, or when you visit Amazon it can remember details of the books you tend to search on. Simple name/value pair cookies are a relatively old fashioned way of maintaining state that for many purposes has been replaced by the concept of a “session”, which usually uses the underlying cookie technology but in a more sophisticated way.
|
|
Cookies are used by adding an instance of Cookie though the addCookie method of HttpServletResponse |
For the purpose of the exam you need to know how to add a cookie to your HTTP response. The following code will add a cookie to your system with a name of language and a value of English
package com.examulator;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class CookieDemo extends HttpServlet {
public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{
Cookie langCookie = new Cookie("language", "English");
res.addCookie(langCookie);
PrintWriter pw = res.getWriter();
pw.println("<html>");
pw.println("<h1> Cookie added</h1>");
pw.println("</html>");
}
}To test this code you will, of course need to configure it in your deployment descriptor (WEB.XML).
You can check that the cookie has been added after executing this servlet. If you are using Mozilla FireFox by going to the Tools/Options/Privacy screen and selecting view cookies. The cookie will come under the domain localhost. If you have not checked this screen before you may be surprised to see just how many cookies you gather in everyday browsing. If you are using Microsoft Internet Explorer you can find cookies by looking in Tools/Internet Options/Temporary Internet Files/Settings/View Files
Other sources
API docs for the HttpServletResponse interface
http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/HttpServletResponse.html
MIME types explained
http://www.ltsw.se/knbase/internet/mime.htp
This objective according to Mikalai Zaikin
http://java.boot.by/wcd-guide/ch01s03.html