tomcat中解析url中的参数或者post中的请求内容





package javax.servlet.http;

import javax.servlet.ServletInputStream;
import java.util.Hashtable;
import java.util.ResourceBundle;
import java.util.StringTokenizer;
import java.io.IOException;

/**
 * @deprecated		As of Java(tm) Servlet API 2.3. 
 *			These methods were only useful
 *			with the default encoding and have been moved
 *			to the request interfaces.
 *
*/

public class HttpUtils {

    private static final String LSTRING_FILE =
	"javax.servlet.http.LocalStrings";
    private static ResourceBundle lStrings =
	ResourceBundle.getBundle(LSTRING_FILE);
   
    /**
     * Constructs an empty <code>HttpUtils</code> object.
     *
     */

    public HttpUtils() {}

    /**
     *
     * Parses a query string passed from the client to the
     * server and builds a <code>HashTable</code> object
     * with key-value pairs. 
     * The query string should be in the form of a string
     * packaged by the GET or POST method, that is, it
     * should have key-value pairs in the form <i>key=value</i>,
     * with each pair separated from the next by a & character.
     *
     * <p>A key can appear more than once in the query string
     * with different values. However, the key appears only once in 
     * the hashtable, with its value being
     * an array of strings containing the multiple values sent
     * by the query string.
     * 
     * <p>The keys and values in the hashtable are stored in their
     * decoded form, so任何加号被转换成空格,以16进制符号发送的字符(如%xx)被转换成ascii码
     * any + characters are converted to spaces, and characters
     * sent in hexadecimal notation (like <i>%xx</i>) are
     * converted to ASCII characters.
     *
     * @param s		a string containing the query to be parsed
     *
     * @return		a <code>HashTable</code> object built
     * 			from the parsed key-value pairs
     *
     * @exception IllegalArgumentException	if the query string 
     *						is invalid
     *  解析url中的参数,比如  http://www.baidu.com/s?word=JFinal架构&tn=93153871_hao_pg&ie=utf-8
     *  word=JFinal架构       tn=93153871_hao_pg     ie=utf-8
     */
    
    static public Hashtable parseQueryString(String s) {
	
		String valArray[] = null;
		
		if (s == null) {
		    throw new IllegalArgumentException();
		}
		//这里用Hashtable,而不用Hashmap,是因为同一个key,可能会有多个value,而Hashmap只能存放一个value 
		Hashtable ht = new Hashtable(); 
		StringBuffer sb = new StringBuffer();
		StringTokenizer st = new StringTokenizer(s, "&");
		while (st.hasMoreTokens()) {
		    String pair = (String)st.nextToken();
		    int pos = pair.indexOf('=');
		    if (pos == -1) {
				// XXX
				// should give more detail about the illegal argument
				throw new IllegalArgumentException();
		    }
		    //解析key和value
		    String key = parseName(pair.substring(0, pos), sb);
		    String val = parseName(pair.substring(pos+1, pair.length()), sb);
		    if (ht.containsKey(key)) {//已经有此关键字名称了,多一个值
				String oldVals[] = (String []) ht.get(key);
				valArray = new String[oldVals.length + 1];
				for (int i = 0; i < oldVals.length; i++) 
	    			valArray[i] = oldVals[i];
				valArray[oldVals.length] = val;
		    } 
		    else {
				valArray = new String[1];
				valArray[0] = val;
		    }
		    ht.put(key, valArray);
		}
		return ht;
    }

    /**
     *
     * Parses data from an HTML form that the client sends to 
     * the server using the HTTP POST method and the 
     * <i>application/x-www-form-urlencoded</i> MIME type.
     *
     * <p>The data sent by the POST method contains key-value
     * pairs. A key can appear more than once in the POST data
     * with different values. However, the key appears only once in 
     * the hashtable, with its value being
     * an array of strings containing the multiple values sent
     * by the POST method.
     *
     * <p>The keys and values in the hashtable are stored in their
     * decoded form, so
     * any + characters are converted to spaces, and characters
     * sent in hexadecimal notation (like <i>%xx</i>) are
     * converted to ASCII characters.
     *
     *
     *
     * @param len	an integer specifying the length,
     *			in characters, of the 
     *			<code>ServletInputStream</code>
     *			object that is also passed to this
     *			method
     *
     * @param in	the <code>ServletInputStream</code>
     *			object that contains the data sent
     *			from the client
     * 
     * @return		a <code>HashTable</code> object built
     *			from the parsed key-value pairs
     *
     *
     * @exception IllegalArgumentException	if the data
     *			sent by the POST method is invalid
     *
     */
 
    static public Hashtable parsePostData(int len, 
					  ServletInputStream in)
    {
		// XXX
		// should a length of 0 be an IllegalArgumentException
		
		if (len <=0)
		    return new Hashtable(); // cheap hack to return an empty hash
	
		if (in == null) {
		    throw new IllegalArgumentException();
		}
		
		//
		// Make sure we read the entire POSTed body.
		//
        byte[] postedBytes = new byte [len];
        try {
            int offset = 0;
       
		    do {
			int inputLen = in.read (postedBytes, offset, len - offset);
			if (inputLen <= 0) {
			    String msg = lStrings.getString("err.io.short_read");
			    throw new IllegalArgumentException (msg);
			}
			offset += inputLen;
		    } while ((len - offset) > 0);

		} catch (IOException e) {
		    throw new IllegalArgumentException(e.getMessage());
		}

        // XXX we shouldn't assume that the only kind of POST body
        // is FORM data encoded using ASCII or ISO Latin/1 ... or
        // that the body should always be treated as FORM data.
        //

        try {
            String postedBody = new String(postedBytes, 0, len, "8859_1");
            return parseQueryString(postedBody);
        } catch (java.io.UnsupportedEncodingException e) {
            // XXX function should accept an encoding parameter & throw this
            // exception.  Otherwise throw something expected.
            throw new IllegalArgumentException(e.getMessage());
        }
    }

    /*
     * Parse a name in the query string.
     */
    static private String parseName(String s, StringBuffer sb) {
		sb.setLength(0);
		for (int i = 0; i < s.length(); i++) {
		    char c = s.charAt(i); 
		    switch (c) {
			    case '+'://加号转换成空格
			    	sb.append(' ');
			    	break;
			    case '%'://%xx后面的 16进制xx 转换成 10进制的数字,然后再转换成char型(即ascii码)
					try {
					    sb.append((char) Integer.parseInt(s.substring(i+1, i+3), 
									      16));
					    i += 2;
					} catch (NumberFormatException e) {
					    // XXX
					    // need to be more specific about illegal arg
					    throw new IllegalArgumentException();
					} catch (StringIndexOutOfBoundsException e) {
					    String rest  = s.substring(i);
					    sb.append(rest);
					    if (rest.length()==2)
						i++;
					}
					
					break;
			    default:
					sb.append(c);
					break;
		    }
		}
		return sb.toString();
    }
   
    /**
     *
     * Reconstructs the URL the client used to make the request,
     * using information in the <code>HttpServletRequest</code> object.
     * The returned URL contains a protocol, server name, port
     * number, and server path, but it does not include query
     * string parameters.
     * 
     * <p>Because this method returns a <code>StringBuffer</code>,
     * not a string, you can modify the URL easily, for example,
     * to append query parameters.
     *
     * <p>This method is useful for creating redirect messages
     * and for reporting errors.
     * 这个方法对创建重定向信息和报告错误非常有用
     * @param req	a <code>HttpServletRequest</code> object
     *			containing the client's request
     * 
     * @return		a <code>StringBuffer</code> object containing
     *			the reconstructed URL
     *
     */
    public static StringBuffer getRequestURL (HttpServletRequest req) {
    	
		StringBuffer url = new StringBuffer ();
		String scheme = req.getScheme ();
		int port = req.getServerPort ();
		String urlPath = req.getRequestURI();
	
		//String		servletPath = req.getServletPath ();
		//String		pathInfo = req.getPathInfo ();
	
		url.append (scheme);		// http, https
		url.append ("://");
		url.append (req.getServerName ());
		if ((scheme.equals ("http") && port != 80)
			|| (scheme.equals ("https") && port != 443)) {
		    url.append (':');
		    url.append (req.getServerPort ());
		}
		//if (servletPath != null)
		//    url.append (servletPath);
		//if (pathInfo != null)
		//    url.append (pathInfo);
		url.append(urlPath);
		return url;
    }
}




评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值