通过检测HTTP请求时CGI环境变量,可以获取客户端浏览器请求的一些环境信息
通过调用下面程序中的outputAllCGI方法,可以在控制台输出部分CGI环境变量。
其中包含一个User-Agent变量,包含了请求的操作系统信息,浏览器信息及版本等内容
通过对这些信息的分析,判断请求的客户端是否为手机客户端,自动返回相应的页面
public class UserAgentsUtil { private static String[] phoneBrowersKey = new String[]{ "user-agent","noki","eric","wapi","nc21","aur","r380","up.b", "winw","upg1","upsi","qwap","jigs","java","alca","nits", "not-","my s","wapj","fetc","alav","wapa","ucweb","blackberry", "j2me","android","oper","dopod","symbian","iphone","android", "mobile","wap","netfront","java","opera mobi","opera mini", "ucweb","windows ce","symbian","series","webos","sony", "blackberry","dopod","nokia","samsung","palmsource","xda", "pieplus","meizu","midp","cldc","motorola","foma","docomo", "up.browser","up.link","blazer","helio","hosin","huawei","novarra", "coolpad","techfaith","palmsource","alcatel","amoi","ktouch", "nexian","ericsson","philips","sagem","wellcom","bunjalloo", "maui","smartphone","iemobile","bird","zte-","longcos","pantech", "gionee","portalmmm","jig browser","hiptop","benq","haier","^lct", "mqqbrowser","320x320","240x320","176x220" }; private static String phoneBrowerUrl = "wap/index.jsp"; private static String computerBrowerUrl = "web/index.jsp"; public static void redirectByUserAgents(HttpServletRequest request, HttpServletResponse response) throws IOException { String userAgent=request.getHeader("user-agent"); if (userAgent == null) { return ; } userAgent = userAgent.toLowerCase(); for (int i=0; i<phoneBrowersKey.length; i++) { if (userAgent.indexOf(phoneBrowersKey[i]) != -1) { response.sendRedirect(phoneBrowerUrl); return; } } response.sendRedirect(computerBrowerUrl); } public static void outputAllCGI(HttpServletRequest request, HttpServletResponse response, HttpServlet servlet) { String strEnvs[][] = { { "CONTENT_LENGTH ", String.valueOf(request.getContentLength()) }, { "CONTENT_TYPE ", request.getContentType() }, { "SERVER_PROTOCOL ", request.getProtocol() }, { "SERVER_SOFTWARE ", servlet.getServletContext().getServerInfo() }, { "REMOTE_ADDR ", request.getRemoteAddr() }, { "REMOTE_HOST ", request.getRemoteHost() }, { "REMOTE_USER ", request.getRemoteUser() }, { "SERVER_NAME ", request.getServerName() }, { "SERVER_PORT ", String.valueOf(request.getServerPort()) }, { "AUTH_TYPE ", request.getAuthType() }, { "REQUEST_METHOD ", request.getMethod() }, { "PATH_INFO ", request.getPathInfo() }, { "PATH_TRANSLATED ", request.getPathTranslated() }, { "QUERY_STRING ", request.getQueryString() }, { "REQUEST_URI ", request.getRequestURI() }, { "SCRIPT_NAME ", request.getServletPath() }, { "DOCUMENT_ROOT ", servlet.getServletContext().getRealPath("/ ") } }; Enumeration enumNames = request.getHeaderNames(); while (enumNames.hasMoreElements()) { String strName = (String) enumNames.nextElement(); String strValue = request.getHeader(strName); System.out.println(strName + " : " + strValue); } for (int i=0; i<strEnvs.length; i++) { System.out.println(strEnvs[i][0] + " : " + strEnvs[i][1]); } } }