6.3 A Servlet That Redirects Users to Browser-Specific Pages

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.java
 package 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.

graphics/06fig01.jpg

Figure 6-2. Result of http: //host/ servlet/coreservlets.WrongDestination in Netscape.

graphics/06fig02.jpg



Core Servlets and JavaServer Pages (Vol. 1.Core Technologies)
Core Servlets and Javaserver Pages: Core Technologies, Vol. 1 (2nd Edition)
ISBN: 0130092290
EAN: 2147483647
Year: 2002
Pages: 194

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net