⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 pi3httpservletrequest.java

📁 mini http server,可以集成嵌入到程序中,实现简单的web功能
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
/*____________________________________________________________________________*\
 *

 Copyright (c) 1997-2003 John Roy, Holger Zimmermann. All rights reserved.

 These sources, libraries and applications are
 FREE FOR COMMERCIAL AND NON-COMMERCIAL USE
 as long as the following conditions are adhered to.

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions
 are met:

 1. Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer. 

 2. Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in
    the documentation and/or other materials provided with the
    distribution.

 3. The name of the author may not be used to endorse or promote products
    derived from this software without specific prior written permission. 

 THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 IN NO EVENT SHALL THE AUTHORS OR ITS CONTRIBUTORS BE LIABLE FOR ANY
 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 OF THE POSSIBILITY OF SUCH DAMAGE.

 *____________________________________________________________________________*|
 *
 * $Source: /cvsroot/pi3web/Pi3Web_200/Source/Servlet/org/pi3/servlet/core/Pi3HttpServletRequest.java,v $
 * $Date: 2003/05/13 18:42:21 $
 *
 Description:
	Implementation of both servlet API ServletRequest, HttpServletRequest interfaces.

\*____________________________________________________________________________*/

package org.pi3.servlet.core;

import java.io.IOException;
import java.io.BufferedReader;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Locale;
import java.util.StringTokenizer;
import java.security.Principal;
import org.pi3.servlet.core.Pi3Reader;
import org.pi3.servlet.util.Pi3ServletUtils;

/**
 *
 * Implements both the <code>javax.servlet.ServletRequest</code> and
 * <code>javax.servlet.http.HttpServletRequest</code> interfaces to
 * provide request information for HTTP servlets.
 *
 * <p>The servlet container (Pi3Web) creates an <code>
 * Pi3HttpServletRequest</code> object and passes it as an
 * argument of type <code>ServletRequest</code> to the servlet's
 * service methods (<code>doGet</code>, <code>doPost</code>, etc).
 *
 *
 * @author 	Holger Zimmermann [zimpel@pi3.org]
 * @version	$Revision: 1.8 $
 *
 *
 */

final public class Pi3HttpServletRequest implements ServletRequest, HttpServletRequest {

    private int hobj;
    private int hsrv;
	private Pi3ServletUtils su;
	private Hashtable att;
    private Hashtable hdr;
	private Hashtable par;
    private Hashtable sessions = null;
	private boolean usedIS = false;
	private boolean usedBR = false;
	private Pi3ServletInputStream sin;
	private BufferedReader br;
    private String SID = null;
    private boolean bSidFromCookie = false;
    private boolean bSidFromUrl = false;
    private HttpSession session = null;



	/** This constructor is used by the native side */
    protected Pi3HttpServletRequest(int pihttp, int hservlet, Pi3ServletUtils sutils, Hashtable sessionpool) {
        hobj = pihttp;
        hsrv = hservlet;
		sessions = sessionpool; 

		sin = new Pi3ServletInputStream(hobj, hsrv);
        br  = new BufferedReader(new Pi3Reader(hobj, hsrv));

		su = sutils;
		att = new Hashtable();
		hdr = new Hashtable();
        su.getRequestVariables(hdr);

		SID = SidFromCookie();
        if (SID != null) {
		    bSidFromCookie = true;
		} else {
            SID = SidFromUrl();
            if (SID != null) bSidFromUrl = true;
		};

		if (SID != null) session = (HttpSession)sessions.get(SID);
		if (session != null) ((Pi3HttpSession)session).touch();
    }




    /** The method to get the PiHttp object from the native side */
    protected int getPiHttp() {
        return hobj;
    }




    /** The method to get the Servlet handler object from the native side */
    protected int getServletHandler() {
        return hsrv;
    }




    private String SidFromUrl() {
        String uri = getRequestURI();
	    int index = uri.indexOf(Constants.SESSION_PARAMETER_NAME);
		if (index == -1) return null;
		uri = uri.substring(index);
		index = uri.indexOf('=');
		return index > 0 ? uri.substring(index + 1) : null;
	}




    private String SidFromCookie() {
	    String key = Constants.SESSION_COOKIE_NAME;
	    Cookie[] Cookies = getCookies();
		if (Cookies == null) return null;
		for (int i = 0; i < Cookies.length; i++) {
		    if (Cookies[i].getName().equalsIgnoreCase(key)) {
			    return Cookies[i].getValue();
			};
		};
	    return null;
	}



    private void parseParams() {
		if (par != null) return;
		if (getMethod().equals("GET")) {
			par = HttpUtils.parseQueryString(getQueryString());
		} else {
			par = HttpUtils.parsePostData(getContentLength(), sin);
		}
	}

    private native HttpSession createSession();




    /**
     *
     * Returns the value of the named attribute as an <code>Object</code>,
     * or <code>null</code> if no attribute of the given name exists. 
     *
     * <p> Attributes can be set two ways.  The servlet container may set
     * attributes to make available custom information about a request.
     * For example, for requests made using HTTPS, the attribute
     * <code>javax.servlet.request.X509Certificate</code> can be used to
     * retrieve information on the certificate of the client.  Attributes
     * can also be set programatically using 
     * {@link ServletRequest#setAttribute}.  This allows information to be
     * embedded into a request before a {@link RequestDispatcher} call.
     *
     * <p>Attribute names should follow the same conventions as package
     * names. This specification reserves names matching <code>java.*</code>,
     * <code>javax.*</code>, and <code>sun.*</code>. 
     *
     * @param name	a <code>String</code> specifying the name of 
     *			the attribute
     *
     * @return		an <code>Object</code> containing the value 
     *			of the attribute, or <code>null</code> if
     *			the attribute does not exist
     *
     */

    public Object getAttribute(String name) {
		synchronized(att) {
			return att.get(name);
		}
    };
    

    

    /**
     * Returns an <code>Enumeration</code> containing the
     * names of the attributes available to this request. 
     * This method returns an empty <code>Enumeration</code>
     * if the request has no attributes available to it.
     * 
     *
     * @return		an <code>Enumeration</code> of strings 
     *			containing the names 
     * 			of the request's attributes
     *
     */

    public Enumeration getAttributeNames() {
        synchronized(att) {
			return att.keys();
		}
    };
    
    
    
    
    /**
     * Returns the name of the character encoding used in the body of this
     * request. This method returns <code>null</code> if the request
     * does not specify a character encoding
     * 
     *
     * @return		a <code>String</code> containing the name of 
     *			the chararacter encoding, or <code>null</code>
     *			if the request does not specify a character encoding
     *
     */

    public String getCharacterEncoding() {
		String ct = su.getRequestVariable("Content-Type");
        if (ct != null) {
            StringTokenizer st = new StringTokenizer(ct,";");
			String to;
            while (st.hasMoreTokens()) {
                to = st.nextToken();
				if (to.trim().toUpperCase().startsWith("CHARSET=")) {
				    return to.substring(to.indexOf("=") + 1);
				}
            }
        }
        return null;
    };    
    

    
    
    /**
     * Returns the length, in bytes, of the request body 
     * and made available by the input stream, or -1 if the
     * length is not known. For HTTP servlets, same as the value
     * of the CGI variable CONTENT_LENGTH.
     *
     * @return		an integer containing the length of the 
     * 			request body or -1 if the length is not known
     *
     */

    public int getContentLength() {
        String s = su.getRequestVariable("Content-Length");
		if (s != null) {
            Integer i = new Integer(s);
			return i.intValue();
		};
	    return -1;
    };
    
    
    

    /**
     * Returns the MIME type of the body of the request, or 
     * <code>null</code> if the type is not known. For HTTP servlets, 
     * same as the value of the CGI variable CONTENT_TYPE.
     *
     * @return		a <code>String</code> containing the name 
     *			of the MIME type of 
     * 			the request, or -1 if the type is not known
     *
     */

    public String getContentType() {
        return su.getRequestVariable("Content-Type");
    };
    
    
    

    /**
     * Retrieves the body of the request as binary data using
     * a {@link ServletInputStream}.  Either this method or 
     * {@link #getReader} may be called to read the body, not both.
     *
     * @return			a {@link ServletInputStream} object containing
     * 				the body of the request
     *
     * @exception IllegalStateException  if the {@link #getReader} method
     * 					 has already been called for this request
     *
     * @exception IOException    	if an input or output exception occurred
     *
     */

    public ServletInputStream getInputStream() throws IOException {
	    if (usedBR) {
            IllegalStateException e = new IllegalStateException();
			throw e;
		}
	    usedIS = true;
        return sin;
    }; 
     
    
    

    /**
     * Returns the value of a request parameter as a <code>String</code>,
     * or <code>null</code> if the parameter does not exist. Request parameters
     * are extra information sent with the request.  For HTTP servlets,
     * parameters are contained in the query string or posted form data.
     *
     * <p>You should only use this method when you are sure the
     * parameter has only one value. If the parameter might have
     * more than one value, use {@link #getParameterValues}.
     *
     * <p>If you use this method with a multivalued
     * parameter, the value returned is equal to the first value
     * in the array returned by <code>getParameterValues</code>.
     *
     * <p>If the parameter data was sent in the request body, such as occurs
     * with an HTTP POST request, then reading the body directly via {@link
     * #getInputStream} or {@link #getReader} can interfere
     * with the execution of this method.
     *
     * @param name 	a <code>String</code> specifying the 
     *			name of the parameter
     *
     * @return		a <code>String</code> representing the 
     *			single value of the parameter
     *
     * @see 		#getParameterValues
     *
     */

    public String getParameter(String name) {
	    parseParams();
        String[] param = (String[])par.get(name);
		return (param != null) ? param[0] : null;
    };
    
    
    

    /**
     *
     * Returns an <code>Enumeration</code> of <code>String</code>
     * objects containing the names of the parameters contained
     * in this request. If the request has 
     * no parameters, the method returns an 
     * empty <code>Enumeration</code>. 
     *
     * @return		an <code>Enumeration</code> of <code>String</code>
     *			objects, each <code>String</code> containing
     * 			the name of a request parameter; or an 
     *			empty <code>Enumeration</code> if the
     *			request has no parameters
     *
     */
     
    public Enumeration getParameterNames() {
	    parseParams();
		return par.keys();
    };
    
    
    

    /**
     * Returns an array of <code>String</code> objects containing 
     * all of the values the given request parameter has, or 
     * <code>null</code> if the parameter does not exist.
     *
     * <p>If the parameter has a single value, the array has a length
     * of 1.
     *
     * @param name	a <code>String</code> containing the name of 
     *			the parameter whose value is requested
     *
     * @return		an array of <code>String</code> objects 
     *			containing the parameter's values
     *
     * @see		#getParameter
     *
     */

    public String[] getParameterValues(String name) {
	    parseParams();
	    return (String[])par.get(name);
    }
    
    
    

    /**
     * Returns the name and version of the protocol the request uses
     * in the form <i>protocol/majorVersion.minorVersion</i>, for 
     * example, HTTP/1.1. For HTTP servlets, the value
     * returned is the same as the value of the CGI variable 
     * <code>SERVER_PROTOCOL</code>.
     *
     * @return		a <code>String</code> containing the protocol 
     *			name and version number
     *
     */
    
    public String getProtocol() {
        return su.getRequestVariable("Protocol");
    };
    
    
    

    /**

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -