Recall from Chapter 5 that the User -Agent request header designates the specific browser (or cell phone or other client) making the request. Recall further that most major browsers contain the string Mozilla in their User-Agent header, but only Microsoft Internet Explorer contains the string MSIE . Listing 6.1 shows a servlet that makes use of this fact to send Internet Explorer users to the Netscape home page, and all other users to the Microsoft home page. The servlet accomplishes this task by using the sendRedirect method to send a 302 status code and a Location response header to the browser. Figures 6-1 and 6-2 show results for Internet Explorer and Netscape, respectively. Listing 6.1 WrongDestination.javapackage coreservlets; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; /** Servlet that sends IE users to the Netscape home page and * Netscape (and all other) users to the Microsoft home page. */ public class WrongDestination extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String userAgent = request.getHeader("User-Agent"); if ((userAgent != null) && (userAgent.indexOf("MSIE") != -1)) { response.sendRedirect("http://home.netscape.com"); } else { response.sendRedirect("http://www.microsoft.com"); } } } Figure 6-1. Result of http: //host/ servlet/coreservlets.WrongDestination in Internet Explorer.
Figure 6-2. Result of http: //host/ servlet/coreservlets.WrongDestination in Netscape.
|