Java/Servlets/Request

Материал из Java эксперт
Перейти к: навигация, поиск

Browser detection

   <source lang="java">

/*

* 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.
* 
*

Version number documentation

* 
*

Safari

*

Quick summary: *

    *
  • Jaguar = 10.2.x = Safari 1.0.x = WebKit/85 *
  • Panther = 10.3.0+ = Safari 1.1.x = WebKit/100 *
  • Panther = 10.3.4+ = Safari 1.2.x = WebKit/125 *
  • Panther = 10.3.9+ = Safari 1.3.x = WebKit/312 *
  • Tiger = 10.4.x = Safari 2.0.x = WebKit/412-419 *
  • Tiger = 10.4.11 = Safari 3.0.x = WebKit/523 *
  • Leopard = 10.5.x = Safari 3.0.x = WebKit/523 *
  • Windows = Safari 3.0.x = WebKit/523 *
  • Leopard = 10.5.x = Safari 3.1.x = WebKit/525-526 *
* 
* <p>For full information see the Safari and WebKit Version Information:
* .

* @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,

}

 </source>
   
  
 
  



Example servlet showing request headers

   <source lang="java">
 

/*

  • 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("

" + title + "

");
       Cookie[] cookies = request.getCookies();
       if ((cookies != null) && (cookies.length > 0)) {
           out.println(rb.getString("cookies.cookies") + "
"); for (int i = 0; i < cookies.length; i++) { Cookie cookie = cookies[i]; out.print("Cookie Name: " + HTMLFilter.filter(cookie.getName()) + "
"); out.println(" Cookie Value: " + HTMLFilter.filter(cookie.getValue()) + "

"); } } 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("

"); out.println(rb.getString("cookies.set") + "
"); out.print(rb.getString("cookies.name") + " " + HTMLFilter.filter(cookieName) + "
"); out.print(rb.getString("cookies.value") + " " + HTMLFilter.filter(cookieValue)); } out.println("<P>"); out.println(rb.getString("cookies.make-cookie") + "
"); out.print("<form action=\""); out.println("CookieExample\" method=POST>"); out.print(rb.getString("cookies.name") + " "); out.println("<input type=text length=20 name=cookiename>
"); out.print(rb.getString("cookies.value") + " "); out.println("<input type=text length=20 name=cookievalue>
"); 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); } } </source>

Get Cookie from Request

   <source lang="java">
  

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("

No Cookies found

");
   } else {
out.println("<center>

Cookies found

"); out.println(""); out.println("" + "");
     for (int i = 0; i < cookies.length; i++) {
       Cookie c = cookies[i];
out.println("");
     }
out.println("
NameValueCommentMax Age
" + c.getName() + "" + c.getValue() + "" + c.getComment() + "" + c.getMaxAge() + "
");
   }
   out.println("</body>");
   out.println("</html>");
   out.flush();
 }

}


 </source>
   
  
 
  



Get Locale Information from Request

   <source lang="java">
  

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("");
 }

}


 </source>
   
  
 
  



Get session from request

   <source lang="java">
  

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 " + session.getId());
   out.println(" and you have hit this page " + count
       + " 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();
 }

}


 </source>
   
  
 
  



javax.servlet.request.X509Certificate

   <source lang="java">
 

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");
     }
   }
 }

}


 </source>
   
  
 
  



Request handling utility class

   <source lang="java">
 

/*

* $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);
   }

}


 </source>
   
  
 
  



Returns any parameters and lists server properties.

   <source lang="java">
  

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("
"); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); java.util.Enumeration e = req.getParameterNames(); while (e.hasMoreElements()) { String name = (String) e.nextElement(); out.println(""); out.println(""); out.println(""); out.println(""); } out.println("
Method" + req.getMethod() + "
User" + req.getRemoteUser() + "
Client" + req.getRemoteHost() + "
Protocol" + req.getProtocol() + "
Parameter "" + name + """ + req.getParameter(name) + "



"); out.println("

"); out.println("Server Properties

");
   out.println("
");
out.println("
");
   java.util.Properties props = System.getProperties();
   e = props.propertyNames();
   while (e.hasMoreElements()) {
     String name = (String) e.nextElement();
out.println(""); out.println(""); out.println(""); out.println(""); } out.println("
" + name + "" + props.getProperty(name) + "
");
   out.println("</html>");
   out.flush();
 }
 public void init() throws ServletException {
   ServletConfig config = getServletConfig();
 }
 public void destroy() {
 }

}


 </source>
   
  
 
  



== Using Request Object Servlet ==