The User -Agent header identifies the specific browser that is making the request. Although use of this header appears straightforward at first glance, a few subtleties are involved:
Listing 5.4 shows a servlet that sends browser-specific insults to users. For the sake of simplicity, it assumes that Internet Explorer and Netscape are the only two browsers being used. Specifically, it assumes that any browser whose User-Agent contains "MSIE" is Internet Explorer and any whose User-Agent does not is Netscape. Figures 5-4 and 5-5 show the results. Listing 5.4 BrowserInsult.javapackage coreservlets; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; /** Servlet that gives browser-specific insult. * Illustrates how to use the User-Agent * header to tell browsers apart. */ public class BrowserInsult extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title, message; // Assume for simplicity that Netscape and IE are // the only two browsers. String userAgent = request.getHeader("User-Agent"); if ((userAgent != null) && (userAgent.indexOf("MSIE") != -1)) { title = "Microsoft Minion"; message = "Welcome, O spineless slave to the " + "mighty empire."; } else { title = "Hopeless Netscape Rebel"; message = "Enjoy it while you can. " + "You <I>will</I> be assimilated!"; } String docType = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " + "Transitional//EN\">\n"; out.println(docType + "<HTML>\n" + "<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" + "<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1 ALIGN=CENTER>" + title + "</H1>\n" + message + "\n" + "</BODY></HTML>"); } } Figure 5-4. The BrowserInsult servlet as viewed by a Netscape user.
Figure 5-5. The BrowserInsult servlet as viewed by an Internet Explorer user.
|