Detecting Browser Types
Now that we have successfully built an XML document as well as XSL templates for HTML and WML, and have seen how to apply templates in a language like Java, the final step for our multiple-device functionality is to dynamically test clients to determine which type of content they should receive. Standard web browsers (such as Netscape Navigator and Microsoft Internet Explorer) should receive HTML content, while WAP phones should only receive WML. To do this, we need to examine the browser's HTTP_USER_AGENT environment variable to determine the browser type. (An excellent listing of valid browser agents is available at http://www.siteware.ch/webresources/useragents/db.html.) To detect a browser type using Java servlets and the HttpServletRequest object, use the following code snippet:
String user_agent = request.getHeader("User-Agent");
Our example is fortunate because both IE and Netscape's User-Agent string start with "Mozilla". If we find this string, we apply the HTML template and send back HTML. If we don't, we can assume (for this example) that it's a WAP client. Therefore, the WML template will be applied.