How tomcat resolves request parameters for URLs (trace httpservletrequest parsing process for request parameters)

Source: Internet
Author: User
Tags exception handling

Thinking about the first two months colleagues asked me: "I sent a request if there is" a=f&a=g ", then in the servlet to get the value of a is a string" f,g ", this is how it happened.
At that time I guess is springmvc do the processing, and then started a test project, and the debug tracking, the final query to the Tomcat source, found incredibly is it to do the analysis.
Now want to write a blog to record, but found that they can not find traces of the then tracking ... So look up the information, once again found that there are two sets of programs.
Resources:
In Tomcat, parse the parameter in the URL or the request content in the Post
Resolve the% problem in the URL parameter scenario one:

Before Servlet API 2.3, Tomcat uses Avax.servlet.http.HttpUtils to parse the parameters. The code is as follows:

/** * This method uses the Hashtable<string,string[]> data structure to store the key value of the request parameter, which is stored with the value array for the same key value pair, that is, a key corresponds to a value array.
Hashtable has the advantage of thread safety relative to HashMap.

        * */public static hashtable<string,string[]> parsequerystring (string s) {string valarray[] = null;
        if (s = = null) {throw new illegalargumentexception ();
        } hashtable<string,string[]> HT = new hashtable<string,string[]> ();
        StringBuilder sb = new StringBuilder ();
        StringTokenizer st = new StringTokenizer (S, "&");
            while (St.hasmoretokens ()) {String pair = St.nexttoken ();
            int pos = pair.indexof (' = ');
                if (pos = = 1) {//XXX//should give more detail about the illegal argument
            throw new IllegalArgumentException ();
            String key = ParseName (pair.substring (0, POS), SB);
            String val = parsename (pair.substring (pos+1, Pair.length ()), SB); if (Ht.containskEY (key)) {String oldvals[] = 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; }
Programme II:

To put the parsing method in the Org.apache.catalina.connector.Request (Tomcat implementation Class), let's look at the parsing process of the tomcat request parameter: Set up an identity bit:

    /**
     * Request parameters parsed flag.
     * *
    protected Boolean parametersparsed = false;

It identifies whether the parameter requested by the current request has been parsed and, if it has already been parsed, can use the Parameters property of the real object "Org.apache.coyote.Request" of requests, otherwise You need to parse the parameters and initialize the Parameters property.
As follows:

    @Override public
    String getparameter (string name) {

        if (!parametersparsed) {
            parseparameters ();
        }

        Return Coyoterequest.getparameters (). GetParameter (name);

    
Resolves the request parameter for the first time and initializes the Parameters property:
    /** * Parse request parameters.
        */protected void Parseparameters () {parametersparsed = true;
        Get the Parameters attribute of the real object and then initialize the Parameters Parameters = Coyoterequest.getparameters ();
        Boolean success = false;
                try {//Omit Front action code byte[] formData = null; if (Len < Cached_post_len) {if (postdata = = null) {postdata = new Byte[ca
                    Ched_post_len];
                } formData = PostData;
                else {formData = new Byte[len];
            ///Get FormData later call parameters method for parametric parsing parameters.processparameters (formData, 0, Len);
                else if ("chunked". Equalsignorecase (Coyoterequest.getheader ("transfer-encoding")) {
                byte[] FormData = null;
     try {formData = Readchunkedpostbody ();           } if (FormData!= null) {parameters.processparameters (formData, 0, Formda
                Ta.length);
        }//Omit exception handling Code success = TRUE; }
    }
The ProcessParameters method of the Parameters class:
    public void ProcessParameters (byte bytes[], int start, int len) {processparameters (bytes, start, Len, ge
       Tcharset (encoding));  private void ProcessParameters (byte bytes[], int start, int len, Charset Charset)
                {//omit the predecessor code, mainly converts the byte to a string, and splits the &, = and other characters try {addparameter (name, value); catch (IllegalStateException ise) {//Omit exception handling code}/** *parameters class use Linkedh
            Ashmap<string,arraylist<string>> () to store key-value pairs/public void Addparameter (string key, String value)
        Throws IllegalStateException {if (key==null) {return;
        } Parametercount + +; if (Limit >-1 && parametercount > Limit) {//processing this parameter'll push us over the L Imit. ISE is//What Request.parseparts () uses for requests this are too big parsefailed = true;
        throw new IllegalStateException (sm.getstring ("Parameters.maxcountfail", integer.valueof (limit));
        } arraylist<string> values = Paramhashvalues.get (key);
            if (values = = null) {values = new arraylist<string> (1);
        Paramhashvalues.put (key, values);
    } values.add (value); }
At this point, the requested parameter has been parsed and stored in the parameters object of the request, calling Getpathparameter (String name) or Getparametervalues ( method, such as String name, is obtained directly from the parameters class.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.