User Agent Checks in JSP
So yesterday we needed to build a page that would redirect based on the device a user came from.
We needed to know if a user was coming from a Droid, iPad/iPhone, BlackBerry, or Desktop. I grabbed some user agents here, and went to town. Lemme know if you know a better way to tackle this, as I tried to make it as lean as possible.
Java
<%@ page import="java.util.*"%> <% Enumeration e; e = request.getHeaderNames(); String userAgent = request.getHeader("user-agent"); if(userAgent.matches(".*BlackBerry.*")) { out.print ("BlackBerries taste yummy."); } else if(userAgent.matches(".*Android.*")) { out.print ("These aren't the droids you're looking for."); } else if(userAgent.matches(".*iPhone.*") || userAgent.matches(".*iPad.*")) { out.print ("Pods or pads, doesn't matter."); } else { out.print ("I'm a PC."); } %>
Comments (4)
Leave a Reply
What do you do with the variable “e”? Seems like you could throw away the first two lines of Java code.
Link to commentInteresting. I’ll have to drop them out and test again, but I think you’re right Volt. Cheers!
Link to commentThank Thank Thank You have solve a my big broblem with your tip Thank again!!!!
Link to commentNo problem! Glad I could help.
Link to comment