WEBX Frame: RequestContext Detailed

Source: Internet
Author: User

RequestContext

RequestContext can be seen as a combination of request and response. Multiple RequestContext can also be strung together, just like the filter chain. Each outer requestcontext adds functionality based on the inner RequestContext. This is called an adorner in design mode.


RequestContext species have Basic/buffered/lazy-commit/parser/rewrite/session/set-locale function. The following will be described in detail.


Here are the configuration methods:

<services:request-contexts xmlns= "http://www.alibaba.com/schema/services/request-contexts" ><basic/> <buffered/><lazy-commit/><parser/><set-locale defaultlocale= "Zh_CN" defaultCharset= "UTF-8"/ ><!--Optional-<session/><rewrite/>--></services:request-contexts>


There is a dependency between requestcontext, for example, the session relies on basic. The framework automatically sorts requestcontext based on dependencies, so it can be developed without regard to order.


Access to specific RequestContext. What if you want to get the uploaded file information via Parserrequestcontext? File information can be obtained through findrequestcontext.

Parserrequestcontext Parserrequestcontext =requestcontextutil.findrequestcontext (Request, Parserrequestcontext.class); Parameterparser params = Parserrequestcontext.getparameters (); Fileitem myfile = Params.getfileitem ("myfile"); String filename = Myfile.getname (); InputStream istream = Myfile.getinputstream ();


RequestContext species

Basicrequestcontext. Base RC, which can contain multiple interceptors. The configuration method is as follows.

<basic><request-contexts:interceptorsxmlns= "http://www.alibaba.com/schema/services/request-contexts/ Basic/interceptors "><interceptor class=" ... Interceptor1 "/><interceptor class=" ... Interceptor2 "/></request-contexts:interceptors></basic>


BASICRC always enables a default interceptor, whether or not it is declared. The default interceptor is primarily a security check that avoids the presence of Crlf,status message in HTTP Header value to increase the HTML escape, limiting the total size of the cookie. The following example adds parameters to the default interceptor.

<request-contexts:interceptorsxmlns= "http://www.alibaba.com/schema/services/request-contexts/basic/ Interceptors "><response-header-security-filter maxsetcookiesize=" 5K "/></request-contexts: Interceptors>


Set-locale will save the default locale and the default character set in Threadlocal, The stringescapeutils.escapeurl,templateservice provided by the calling framework are automatically encoded and decoded according to the locale and character set of the current thread. Templateservice will find the corresponding template file according to locale, such as TESTPAGE_ZH_CN.VM.


Set-locale Parameters:

<set-locale defaultlocale= "..." defaultcharset= "..." inputcharsetparam= "_input_charset" outputCharsetParam= "_ Output_charset "paramkey=" _lang "persistent locale and character set's query parameter name sessionkey=" _lang "/> Persistent locale and character set session name


The parser is used to parse the request. It is often sufficient to use the following configuration.

<services:request-contexts xmlns= "http://www.alibaba.com/schema/services/request-contexts" ><parser/ >...</services:request-contexts><services:upload sizemax= "5M" filesizemax= "2M"/>


The above code can handle all requests including get requests, post requests, File upload post requests.


Access via Parserrequestcontext.

@AutowiredParserRequestContext parser; String s = parser.getparameters (). getString ("Myparam");p arser.getparameters (). Getboolean ("Myparam"); Parser.getparameters (). getString ("Myparam", "Default_value");p arser.getparameters (). Getfileitem ("myfile");


Access cookies.

Parser.getcookies (). getString ("MyCookie");


The parameters of the upload tag.

<services:upload sizemax= "5M" filesizemax= "2M" repository= "/tmp" sizethreshold= "10K" keepformfieldinmemory= "true "/>


Repository Upload File Temp folder, is the Resourceloader mount path instead of the physical path.

Sizethreshold, files smaller than this size will be saved in memory.

Keepformfieldinmemory, whether the fields in the form are saved in memory. The default is False.


Manually resolve requests to upload files. Turn off automatic parsing first.

<parser autoupload= "false" >

Then call Parseupload when needed.

Parser.getparameters (). Parseupload ();

You can also specify a different parameter.

Uploadparameters params = new Uploadparameters ();p arams.applydefaultvalues ();p Arams.setsizemax (new Humanreadablesize ("10M"));p Arams.setfilesizemax (New Humanreadablesize ("1M"));p Arams.setrepository (The New File (" Mydir "));p arser.getparameters (). Parseupload (params);


It is very flexible to get the parameters in parser, see the example below, all in order to get the Myproductid.

Request.getparameter ("Myproductid"); Request.getparameter ("Myproductid"); Request.getparameter ("my_product_id"); Request.getparameter ("my_product_id"); Request.getparameter ("My_productid");

If this flexibility is not required, you can turn it off in the configuration:

<parser casefolding= "None" >


Trim By default, parser will trim all parameters and, if this is not required, can be switched off in the configuration.

<parser trimming= "false" >


Entity encoding. By default, if the framework finds that the current charset cannot represent the characters in the request, it replaces the parameter with the entity encoding, such as & #20320;& #22909;

You can close it by using the following code:

<parser unescapeparameters= "false" >


Gets the parameter value for the custom type.

MyEnum MyEnum = Params.getobjectoftype ("Myparam", Myenum.class);


If you need to get the date parameter, add the following code to the configuration:

<parser><property-editor-registrarclass= " Com.alibaba.citrus.service.configuration.support.CustomDateRegistrar "p:format=" Yyyy-mm-dd "p:locale=" ZH_CN "P: Timezone= "Gmt+8"/></parser>


If there is a type conversion error, there are two ways of handling it, one being quiet and the other throwing an exception.

In case of silence, the default value is used if the type goes wrong.

The following configuration is intended to throw an exception if there is an error in the conversion.

<parser converterquiet= "false" >


The Chinese parameter in the GET request. The standard specifies that Chinese characters in URLs must be encoded using UTF8, but not all vendors follow this rule.

Parser uses Input_charset to decode the parameters in the URL.

In addition to this default decoding method, additional alternatives are provided.


Use the servlet's original decoding mechanism.

<parser useservletengineparser= "true"/>

The servlet's original decoding mechanism does not follow the encoding specified in Set-locale, but rather uses the encoding specified in the Web container's configuration file.


Use a fixed decoding method.

<parser uriencoding= "UTF-8" usebodyencodingforuri= "false"/>


Filter request parameters. For example, the following code restricts the extension of the uploaded file.

<parser><filters><parser-filters:uploaded-file-whitelist extensions= "jpg, GIF, PNG"/></ Filters></parser>


Buffered In WEBX, there are screen, control, layout, which represent the output page. Layout can nest screens and control,screen can be nested Control,control can nest additional control. At the time of nesting, the content of the inner page render will be in memory, and then output to its own page when the outer page needs it. There is a buffer stack in the WEBX, and each component adds a new buffer to the stack before rendering, and the rendered content is stored in the top buffer, and the buffer stack pops up after rendering is complete.


When committing, the framework checks if there is only one buffer in the buffer stack, and if not, an error.


Buffered Configuration method:

<buffered/>

No parameters are required.


Operation Bufferedrequestcontext, the following example demonstrates push and pop two operations.

@AutowiredBufferedRequestContext buffered; @AutowiredHttpServletResponse response; PrintWriter out = Response.getwriter (); Buffered.pushbuffer (); Create a new buffer and press it into the top of the stack Out.print ("World"); Writes string content = Buffered.popcharbuffer () in the new buffer; Pop-up top-level bufferout.print ("Hello,"); Out.print (content); Write buffer to lower layer


If Getwriter is called to get the content through Popcharbuffer, if Getoutputstream is called, the content will be obtained through Popbytebuffer.


Close the buffer mechanism. Generally do not need to close, but sometimes need to generate a large file such as PDF, Excel, etc., and the generation consumes a long time, if there is buffer, then the user needs to wait until the file is completed before the download, this delay is certainly unacceptable. If there are no nested components inside the site, then buffer can also be turned off to improve performance.


Lazy-commit intercepts certain methods in the response object, preventing the rendered content from being automatically submitted. When the request processing is complete, submit again. It works better with buffered. If there is no buffered then the content in the buffer will be automatically committed when it reaches 8K.


Lazy-commit configuration method, without any parameters.

<lazy-commit/>


Lazycommitrequestcontext provides some interfaces to get current requests for errors, redirects, status codes


Rewrite Very similar to the mod_rewrite in Apache. It is intended to map the requested URL to an internal URL.


Rewrite is a web app, so the URL that is matched is Servletpath + pathInfo.


Rewrite execution procedure is to check whether the pattern matches, if match, then each check condition is satisfied, if not satisfied, check the next rule. If all is satisfied, execute substitution and handler.


Servletpath and PathInfo. For example a servlet hangs on/test/abc URL, then a url/test/abc/ddd Servletpath is/test/abc,pathinfo is/ddd.


Regular expressions are used when rules are matched, and there are special books that are not introduced here.


The following is an example of rewite configuration. Rule indicates that a matching url,condition is required to indicate a condition to be checked after a match, substitution represents a substitution rule, and handler means more flexibility in replacing the URL with a custom method.

<services:request-contexts xmlns= "Http://www.alibaba.com/schema/services/request-contexts" ><rewrite ><!--Rule 1--><rule pattern= "..." ><condition test= "..." pattern= "flags=" ... "/>< Condition test= "..." pattern= "..." "flags=" ... "/><substitution uri=" ... "flags=" ... "><parameter key=" ... " Value= "..."/><parameter key= "..." "value=" ... "/><parameter key=" ... "value=" ... "/></substitution >


Condition usage examples. The Pattern property also uses regular expressions.

<condition test= "%{server_name}:%{server_port}" pattern= "www. (\w+). com:8080 "/><condition test="%{query:x} "pattern="! 1 "/><condition test="%{query:y} "pattern=" 2 "/ >


substitution example.

<substitution uri= "/%1/new_$1\.htm"/>
$ $ represents the Regex group in rule in which the Regex group,%1 represents the last matching condition.


The replacement parameter. After the substitution, the other parameters are deleted .

<substitution><parameter key= "ext" value= "$"/><parameter key= "host" value= "%1"/><parameter Key= "Count" ><value>1</value><value>2</value><value>3</value></ Parameter></substitution>


After a rule rule is replaced, the following rule is continued by default, and the match is continued with the URL and parameters that have been replaced.


The flag in the substitution can be the following parameter:

    • L Last: Stop matching
    • C chain: String rule, which is the default behavior
    • QSA Qsappend: Retain the original request parameters
    • r=301: Permanent Redirection
    • r=302: Temporary redirection


301 Jump for SEO.


Multiple parameters are separated with commas.


redirect example:

<substitution uri= "/new_hello.htm" flags= "L,R,QSA"/><substitution uri= "Http://www.other-site.com/new_ Hello.htm "flags=" L,r "/>


Handler Used to compensate for the lack of regular expressions. Regular only performs a simple substitution, and handler is required for more complex functions.

The WEBX framework provides URL-normalized handler.

<rewrite-handlers:handlerclass= "Com.alibaba.citrus.service.requestcontext.rewrite.support.UrlNormalizer"/ >

WEBX Frame: RequestContext Detailed

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.