Java/Servlets/Request

Материал из Java эксперт
Версия от 18:01, 31 мая 2010; (обсуждение)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Browser detection

 
/*
 * Copyright 2005 Joe Walker
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import javax.servlet.http.HttpServletRequest;

/**
 * Various functions to do with working out what is at the other end of the
 * wire, and what it can do.
 * 
 * <h2>Version number documentation</h2>
 * 
 * <h3>Safari</h3>
 * <p>Quick summary:
 * <ul>
 * <li>Jaguar  = 10.2.x  = Safari 1.0.x = WebKit/85
 * <li>Panther = 10.3.0+ = Safari 1.1.x = WebKit/100
 * <li>Panther = 10.3.4+ = Safari 1.2.x = WebKit/125
 * <li>Panther = 10.3.9+ = Safari 1.3.x = WebKit/312
 * <li>Tiger   = 10.4.x  = Safari 2.0.x = WebKit/412-419
 * <li>Tiger   = 10.4.11 = Safari 3.0.x = WebKit/523
 * <li>Leopard = 10.5.x  = Safari 3.0.x = WebKit/523
 * <li>Windows           = Safari 3.0.x = WebKit/523
 * <li>Leopard = 10.5.x  = Safari 3.1.x = WebKit/525-526
 * </ul>
 * 
 * <p>For full information see the Safari and WebKit Version Information:
 * .</p>
 * @author Joe Walker [joe at getahead dot ltd dot uk]
 */
public class BrowserDetect
{
    /**
     * How many connections can this browser open simultaneously?
     * @param request The request so we can get at the user-agent header
     * @return The number of connections that we think this browser can take
     */
    public static int getConnectionLimit(HttpServletRequest request)
    {
        if (atLeast(request, UserAgent.IE, 8))
        {
            return 6;
        }
        else if (atLeast(request, UserAgent.AppleWebKit, 8))
        {
            return 4;
        }
        else if (atLeast(request, UserAgent.Opera, 9))
        {
            return 4;
        }
        else
        {
            return 2;
        }
    }
    /**
     * Does this web browser support comet?
     * @param request The request so we can get at the user-agent header
     * @return True if long lived HTTP connections are supported
     */
    public static boolean supportsComet(HttpServletRequest request)
    {
        String userAgent = request.getHeader("user-agent");
        // None of the non-iPhone mobile browsers that I"ve tested support comet
        if (userAgent.contains("Symbian"))
        {
            return false;
        }
        // We need to test for other failing browsers here
        return true;
    }
    /**
     * Check that the user-agent string indicates some minimum browser level
     * @param request The browsers request
     * @param requiredUserAgent The UA required
     * @return true iff the browser matches the spec.
     */
    public static boolean atLeast(HttpServletRequest request, UserAgent requiredUserAgent)
    {
        return atLeast(request, requiredUserAgent, -1);
    }
    /**
     * Check that the user-agent string indicates some minimum browser level
     * @param request The browsers request
     * @param requiredUserAgent The UA required. Currently this is major version only
     * @param requiredVersion The version required, or -1 if versions are not important
     * @return true iff the browser matches the spec.
     */
    public static boolean atLeast(HttpServletRequest request, UserAgent requiredUserAgent, int requiredVersion)
    {
        String userAgent = request.getHeader("user-agent");
        int realVersion;
        switch (requiredUserAgent)
        {
        case IE:
            realVersion = getMajorVersionAssumingIE(userAgent);
            break;
        case Gecko:
            realVersion = getMajorVersionAssumingGecko(userAgent);
            break;
        case Opera:
            realVersion = getMajorVersionAssumingOpera(userAgent);
            break;
        case AppleWebKit:
            realVersion = getMajorVersionAssumingAppleWebKit(userAgent);
            break;
        default:
            throw new UnsupportedOperationException("Detection of " + requiredUserAgent + " is not supported yet.");
        }
        return realVersion >= requiredVersion;
    }
    /**
     * Check {@link #atLeast(HttpServletRequest, UserAgent)} for
     * {@link UserAgent#AppleWebKit}
     */
    private static int getMajorVersionAssumingAppleWebKit(String userAgent)
    {
        int webKitPos = userAgent.indexOf("AppleWebKit");
        if (webKitPos == -1)
        {
            return -1;
        }
        return parseNumberAtStart(userAgent.substring(webKitPos + 12));
    }
    /**
     * Check {@link #atLeast(HttpServletRequest, UserAgent)} for
     * {@link UserAgent#Opera}
     */
    private static int getMajorVersionAssumingOpera(String userAgent)
    {
        int operaPos = userAgent.indexOf("Opera");
        if (operaPos == -1)
        {
            return -1;
        }
        return parseNumberAtStart(userAgent.substring(operaPos + 6));
    }
    /**
     * Check {@link #atLeast(HttpServletRequest, UserAgent)} for
     * {@link UserAgent#Gecko}
     */
    private static int getMajorVersionAssumingGecko(String userAgent)
    {
        int geckoPos = userAgent.indexOf(" Gecko/20");
        if (geckoPos == -1 || userAgent.contains("WebKit/"))
        {
            return -1;
        }
        return parseNumberAtStart(userAgent.substring(geckoPos + 7));
    }
    /**
     * Check {@link #atLeast(HttpServletRequest, UserAgent)} for
     * {@link UserAgent#IE}
     */
    private static int getMajorVersionAssumingIE(String userAgent)
    {
        int msiePos = userAgent.indexOf("MSIE ");
        if (msiePos == -1 || userAgent.contains("Opera"))
        {
            return -1;
        }
        return parseNumberAtStart(userAgent.substring(msiePos + 5));
    }
    /**
     * We"ve found the start of a sequence of numbers, what is it as an int?
     */
    private static int parseNumberAtStart(String numberString)
    {
        if (numberString == null || numberString.length() == 0)
        {
            return -1;
        }
        int endOfNumbers = 0;
        while (Character.isDigit(numberString.charAt(endOfNumbers)))
        {
            endOfNumbers++;
        }
        try
        {
            return Integer.parseInt(numberString.substring(0, endOfNumbers));
        }
        catch (NumberFormatException ex)
        {
            return -1;
        }
    }
    /**
     * This method is for debugging only
     */
    public static String getUserAgentDebugString(HttpServletRequest request)
    {
        String userAgent = request.getHeader("user-agent");
        int version = getMajorVersionAssumingIE(userAgent);
        if (version != -1)
        {
            return "IE/" + version;
        }
        version = getMajorVersionAssumingGecko(userAgent);
        if (version != -1)
        {
            return "Gecko/" + version;
        }
        version = getMajorVersionAssumingAppleWebKit(userAgent);
        if (version != -1)
        {
            return "WebKit/" + version;
        }
        version = getMajorVersionAssumingOpera(userAgent);
        if (version != -1)
        {
            return "Opera/" + version;
        }
        return "Unknown: (" + userAgent + ")";
    }

}
/*
 * Copyright 2005 Joe Walker
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * @author Joe Walker [joe at getahead dot ltd dot uk]
 */
enum UserAgent
{
    IE,
    Opera,
    Gecko,
    AppleWebKit,
}





Example servlet showing request headers

  
/*
* Copyright 2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* $Id: CookieExample.java,v 1.3 2004/03/18 16:40:33 jfarcand Exp $
 *
 */
import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
/**
 * Example servlet showing request headers
 *
 * @author James Duncan Davidson <duncan@eng.sun.ru>
 */
public class CookieExample extends HttpServlet {
    ResourceBundle rb = ResourceBundle.getBundle("LocalStrings");
    
    public void doGet(HttpServletRequest request,
                      HttpServletResponse response)
        throws IOException, ServletException
    {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<body bgcolor=\"white\">");
        out.println("<head>");
        String title = rb.getString("cookies.title");
        out.println("<title>" + title + "</title>");
        out.println("</head>");
        out.println("<body>");
  // relative links
        // XXX
        // making these absolute till we work out the
        // addition of a PathInfo issue 
  
        out.println("");
        out.println("<h3>" + title + "</h3>");
        Cookie[] cookies = request.getCookies();
        if ((cookies != null) && (cookies.length > 0)) {
            out.println(rb.getString("cookies.cookies") + "<br>");
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                out.print("Cookie Name: " + HTMLFilter.filter(cookie.getName())
                          + "<br>");
                out.println("  Cookie Value: " 
                            + HTMLFilter.filter(cookie.getValue())
                            + "<br><br>");
            }
        } else {
            out.println(rb.getString("cookies.no-cookies"));
        }
        String cookieName = request.getParameter("cookiename");
        String cookieValue = request.getParameter("cookievalue");
        if (cookieName != null && cookieValue != null) {
            Cookie cookie = new Cookie(cookieName, cookieValue);
            response.addCookie(cookie);
            out.println("<P>");
            out.println(rb.getString("cookies.set") + "<br>");
            out.print(rb.getString("cookies.name") + "  " 
                      + HTMLFilter.filter(cookieName) + "<br>");
            out.print(rb.getString("cookies.value") + "  " 
                      + HTMLFilter.filter(cookieValue));
        }
        
        out.println("<P>");
        out.println(rb.getString("cookies.make-cookie") + "<br>");
        out.print("<form action=\"");
        out.println("CookieExample\" method=POST>");
        out.print(rb.getString("cookies.name") + "  ");
        out.println("<input type=text length=20 name=cookiename><br>");
        out.print(rb.getString("cookies.value") + "  ");
        out.println("<input type=text length=20 name=cookievalue><br>");
        out.println("<input type=submit></form>");
            
            
        out.println("</body>");
        out.println("</html>");
    }
    public void doPost(HttpServletRequest request,
                      HttpServletResponse response)
        throws IOException, ServletException
    {
        doGet(request, response);
    }
}





Get Cookie from Request

   
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Cookies extends HttpServlet {
  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
      IOException {
    resp.setContentType("text/html");
    req.getSession();
    PrintWriter out = resp.getWriter();
    Cookie cookies[] = req.getCookies();
    out.println("<html>");
    out.println("<head>");
    out.println("<title>Servlet Cookie Information</title>");
    out.println("</head>");
    out.println("<body>");
    if ((cookies == null) || (cookies.length == 0)) {
      out.println("<center><h1>No Cookies found</h1>");
    } else {
      out.println("<center><h1>Cookies found</h1>");
      out.println("<table border>");
      out.println("<tr><th>Name</th><th>Value</th>" + "<th>Comment</th><th>Max Age</th></tr>");
      for (int i = 0; i < cookies.length; i++) {
        Cookie c = cookies[i];
        out.println("<tr><td>" + c.getName() + "</td><td>" + c.getValue() + "</td><td>"
            + c.getComment() + "</td><td>" + c.getMaxAge() + "</td></tr>");
      }
      out.println("</table></center>");
    }
    out.println("</body>");
    out.println("</html>");
    out.flush();
  }
}





Get Locale Information from Request

   
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.Locale;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LocaleInformationServlet extends HttpServlet {
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException,
      ServletException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    Locale userPreferredLocale = request.getLocale();
    Enumeration userPreferredLocales = request.getLocales();
    out.println("Preferred Locale: " + userPreferredLocale.toString());
    out.println("");
    out.print("Preferred Locales: ");
    while (userPreferredLocales.hasMoreElements()) {
      userPreferredLocale = (Locale) userPreferredLocales.nextElement();
      out.print(userPreferredLocale.toString() + ", ");
    }
    out.println();
    out.println("");
  }
}





Get session from request

   

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class Counter extends HttpServlet {
  static final String COUNTER_KEY = "Counter.count";
  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
      IOException {
    HttpSession session = req.getSession(true);
    resp.setContentType("text/html");
    PrintWriter out = resp.getWriter();
    int count = 1;
    Integer i = (Integer) session.getAttribute(COUNTER_KEY);
    if (i != null) {
      count = i.intValue() + 1;
    }
    session.setAttribute(COUNTER_KEY, new Integer(count));
    out.println("<html>");
    out.println("<head>");
    out.println("<title>Session Counter</title>");
    out.println("</head>");
    out.println("<body>");
    out.println("Your session ID is <b>" + session.getId());
    out.println("</b> and you have hit this page <b>" + count
        + "</b> time(s) during this browser session");
    out.println("<form method=GET action=\"" + req.getRequestURI() + "\">");
    out.println("<input type=submit " + "value=\"Hit page again\">");
    out.println("</form>");
    out.println("</body>");
    out.println("</html>");
    out.flush();
  }
}





javax.servlet.request.X509Certificate

  
import java.io.IOException;
import java.io.PrintWriter;
import java.security.cert.X509Certificate;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class X509Snoop extends HttpServlet {
  public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
      IOException {
    res.setContentType("text/plain");
    PrintWriter out = res.getWriter();
    X509Certificate[] certs = (X509Certificate[]) req
        .getAttribute("javax.servlet.request.X509Certificate");
    if (certs != null) {
      for (int i = 0; i < certs.length; i++) {
        out.println("Client Certificate [" + i + "] = " + certs[i].toString());
      }
    } else {
      if ("https".equals(req.getScheme())) {
        out.println("This was an HTTPS request, " + "but no client certificate is available");
      } else {
        out.println("This was not an HTTPS request, " + "so no client certificate is available");
      }
    }
  }
}





Request handling utility class

  
/*
 * $Id: RequestUtils.java 651946 2008-04-27 13:41:38Z apetrelli $
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

import javax.servlet.http.HttpServletRequest;

/**
 * Request handling utility class.
 */
public class RequestUtils {
    /**
     * Retrieves the current request servlet path.
     * Deals with differences between servlet specs (2.2 vs 2.3+)
     *
     * @param request the request
     * @return the servlet path
     */
    public static String getServletPath(HttpServletRequest request) {
        String servletPath = request.getServletPath();
        
        String requestUri = request.getRequestURI();
        // Detecting other characters that the servlet container cut off (like anything after ";")
        if (requestUri != null && servletPath != null && !requestUri.endsWith(servletPath)) {
            int pos = requestUri.indexOf(servletPath);
            if (pos > -1) {
                servletPath = requestUri.substring(requestUri.indexOf(servletPath));
            }
        }
        
        if (null != servletPath && !"".equals(servletPath)) {
            return servletPath;
        }
        
        int startIndex = request.getContextPath().equals("") ? 0 : request.getContextPath().length();
        int endIndex = request.getPathInfo() == null ? requestUri.length() : requestUri.lastIndexOf(request.getPathInfo());
        if (startIndex > endIndex) { // this should not happen
            endIndex = startIndex;
        }
        return requestUri.substring(startIndex, endIndex);
    }
}





Returns any parameters and lists server properties.

   
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Properties extends HttpServlet {
  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
      IOException {
    PrintWriter out = resp.getWriter();
    out.println("<html>");
    out.println("<center><table>");
    out.println("<tr>");
    out.println("<td>Method</td>");
    out.println("<td>" + req.getMethod() + "</td>");
    out.println("</tr>");
    out.println("<tr>");
    out.println("<td>User</td>");
    out.println("<td>" + req.getRemoteUser() + "</td>");
    out.println("</tr>");
    out.println("<tr>");
    out.println("<td>Client</td>");
    out.println("<td>" + req.getRemoteHost() + "</td>");
    out.println("</tr>");
    out.println("<tr>");
    out.println("<td>Protocol</td>");
    out.println("<td>" + req.getProtocol() + "</td>");
    out.println("</tr>");
    java.util.Enumeration e = req.getParameterNames();
    while (e.hasMoreElements()) {
      String name = (String) e.nextElement();
      out.println("<tr>");
      out.println("<td>Parameter "" + name + ""</td>");
      out.println("<td>" + req.getParameter(name) + "</td>");
      out.println("</tr>");
    }
    out.println("</table></center><br><hr><br>");
    out.println("<h2><center>");
    out.println("Server Properties</center></h2>");
    out.println("<br>");
    out.println("<center><table>");
    java.util.Properties props = System.getProperties();
    e = props.propertyNames();
    while (e.hasMoreElements()) {
      String name = (String) e.nextElement();
      out.println("<tr>");
      out.println("<td>" + name + "</td>");
      out.println("<td>" + props.getProperty(name) + "</td>");
      out.println("</tr>");
    }
    out.println("</table></center>");
    out.println("</html>");
    out.flush();
  }
  public void init() throws ServletException {
    ServletConfig config = getServletConfig();
  }
  public void destroy() {
  }
}





Using Request Object Servlet