WEBX Study Notes (iii) WEBX Framework

Source: Internet
Author: User

Tasks for the WEBX framework

initialization of the system Responding to requests
Initializing the Spring container Enhance the Request/response/session function
Initializing the log system Provide pipeline process processing mechanism
Exception handling
Development model

1 Initialization of the WEBX

Initialize Spring container-/web-inf/web.xml<?xml version= "1.0" encoding= "UTF-8"? ><web-app version= "2.4" xmlns= "http:/ Java.sun.com/xml/ns/j2ee "    xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance "    xsi:schemalocation="        http://java.sun.com/xml/ns/j2ee  http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd    ">    ...    <listener>        <listener-class>com.alibaba.citrus.webx.context.webxcontextloaderlistener</ listener-class>     </listener>    ...</web-app>

The WEBX framework will automatically search /WEB-INF for the XML configuration file under the directory and create the following cascading spring container.

Figure 3.1. Cascading spring Containers

The WEBX framework breaks down a Web application into several small application modules:, app1 app2 of course, the name can be arbitrarily taken.

    • Each small application module has a single spring sub context child container. The beans between the two sub-containers cannot be injected into one another.

    • All small application modules share a spring root context root container. The beans in the root container can be injected into the bean of the child container, otherwise not.

It is a good development practice to decompose a large application into several small application modules and make their configuration files relatively independent. However, if your application is really simple and you do not want to divide your application into smaller application modules, then you need to configure at least one Small application module (sub-container).

//Initialize the log system-/web-inf/web.xml<?xml version= "1.0" encoding= "UTF-8"?>< Web-app version= "2.4" xmlns= "HTTP://JAVA.SUN.COM/XML/NS/J2EE" xmlns:xsi= "http://www.w3.org/2001/ Xmlschema-instance "xsi:schemalocation=" Http://java.sun.com/xml/ns/j2ee Http://java.sun.com/xml/ns/j2ee/web-ap P_2_4.xsd "> ... <listener> <listener-class>com.alibaba.citrus.logconfig.logconfiguratorlis Tener</listener-class> </listener> </web-app> 
    • Assuming your application relies on the Logback jar package, listener will look up /WEB-INF/logback.xml and use it to initialize the Logback;

    • If your app relies on log4j jar packages, listener will also be smart enough to look for /WEB-INF/log4j.xml configuration files.

    • If the above configuration file does not exist, listener will use the default configuration--print the logs on the console.

    • Listener supports the substitution of placeholders in the configuration file.

    • Listener supports simultaneous initialization of multiple log systems.

2. WEBX Response Request

Figure 3.2. How the WEBX framework responds to requests

When the WEBX framework receives a request from the web, it essentially does two things:

    1. First, it enhances the functionality of the request, response, and session, and packs them into easier-to-use RequestContext objects.

    2. Second, it invokes the pipeline of the corresponding sub-application and uses it for further processing.

    3. If an exception occurs in the above procedure, the WEBX framework process exception is triggered.

In addition, the WEBX framework provides a set of auxiliary development features, such as viewing environment variables, viewing schemas, and so on. These features are only active in the development mode and are automatically turned off in production mode.

Enhanced function of request, response, session

The WEBX framework provides a request contexts service. The request contexts service leverages HttpServletRequestWrapper and HttpServletResponseWrapper wraps the request and response objects to implement new functionality.

Configure the request contexts Service <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"/>    ...</services:request-contexts> <services:upload sizemax= "5M"/>

The available RequestContext extensions

name Description
<basic> Conduct security checks on input and output data to eliminate possible attacks. For example: XSS filter, CRLF line return filter, etc.
<buffered> Caches the data written in response to facilitate the implementation of nested pages.
<lazy-commit> Deferred submission of response to support cookie-based session.
<parser> Resolves user-submitted parameters, whether it is a normal request or a request to upload a file, such as Multipart/form-data.
<set-locale> Sets the region (locale) of the current request, the coded character set (charset).
<rewrite> Rewrite URLs and parameters, similar to the rewrite module in Apache HTTPD server.
<session> An enhanced session framework that saves objects in a session to a cookie, database, or other storage.

Request contexts all functions are configurable and extensible-it is a springext-based extension mechanism.

The added functionality of Request contexts is transparent to all applications that are based on the standard Servlet API-these applications do not need to know the existence of these extensions at all. For example, if you have an enhanced session framework configured in the request contexts service, all applications that get session through the standard Servlet API will get new functionality:

Gets the enhanced Session object HttpSession session = Request.getsession ();

For example, as long as you configure the upload service, the following calls will also apply to multipart/form-data types of requests (the Servlet API itself is not supported for upload forms):

Gets the parameter of the upload form string value = Request.getparameter ("Myparam");
WEBX can be injected with request, response, Sessionpublic class Loginaction {    @Autowired    private HttpServletRequest Request ;    @Autowired    Private httpservletresponse response;    @Autowired    Private HttpSession session;    ...}

In this example, the LoginAction class can be a singleton. In general, you cannot inject the object of the request scope into the singleton scope object. But you can HttpServletRequest inject, HttpServletResponse and HttpSession object into the Singleton object. Why is it? It turns out that the Request contexts service specifically handles these common objects and transforms them into singleton objects.

Pipeline process mechanism

The WEBX framework gives developers great freedom to customize the process of processing requests. This mechanism is pipeline. The pipeline means that there are many valves in the pipeline and the valve can control the flow of water. The pipeline in the WEBX framework can control the direction of the process that processes requests.

Figure 3.3. Pipeline working principle schematic

The WEBX framework does not specify the content of the pipeline, however the WEBX Framework provides a series of generic valves that you can use:

category Valves Description
Cycle <while> Conditional loops
<loop> Unconditional loop
Select Branch <if> Single Branch
<choose><when><otherwise> Multi-Branch
Interrupt <break> Unconditional interruption

<break-if>

<break-unless>

Conditional interrupts
<exit> Unconditionally exit the entire pipeline (end all nesting levels)
Exception capture <try-catch-finally> Try-catch-finally structure similar to Java
Nesting <sub-pipeline> Creates a nested child pipeline.

The WEBX framework can handle these exceptions when an application exception occurs.

conditions processing
Development model Displays detailed error messages.
Production mode If there is exception pipeline Using exception pipeline to deal with anomalies;
Does not exist exception pipeline Displays the default error page defined in Web. Xml.

Development Mode Tools

The WEBX framework provides a switch that allows the application to run in " production mode" (Production mode)or " development Model (development)".

<services:webx-configuration>    <services:productionmode>${productionmode:true}</services: Productionmode> </services:webx-configuration>
Using this line of configuration and specifying the parameter "" When starting the application server -DproductionMode=false will cause WEBX to start in development mode.

The WEBX framework provides an interface: ProductionModeAware . In Spring context, if this interface is implemented, it is possible to perceive the operating mode of the current system, thus choosing different behaviors according to different patterns-for example, opening the cache in production mode and beans the cache in development mode.

Use the Productionmodeaware interface to sense the operating mode and automatically switch Cachepublic class Moduleloaderserviceimpl implements Productionmodeaware { Public      void Setproductionmode (Boolean productionmode) {         this.productionmode = Productionmode;    }    @Override    protected void init () {        ...        if (cacheenabled = = null) {            cacheenabled = Productionmode;         }        ...    }

More details on responding and processing requests

      When an HTTP request arrives, the request is first taken over by Webxframeworkfilter:

<?xml version= "1.0" encoding= "UTF-8"? ><web-app version= "2.4" xmlns= "Http://java.sun.com/xml/ns/j2ee" xmlns : xsi= "http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation= "Http://java.sun.com/xml/ns/j2ee http://ja Va.sun.com/xml/ns/j2ee/web-app_2_4.xsd "> ... <filter> <filter-name>webx</filter-name&gt        ;            <filter-class>com.alibaba.citrus.webx.servlet.WebxFrameworkFilter</filter-class> <init-param> <param-name>excludes</param-name> <param-value><!--need to be "excluded" URL paths, separated by commas, prefixed with! "means" contains ”。            such as/static, *.jpg,!/uploads/*.jpg--></param-value> </init-param> <init-param> <param-name>passthru</param-name> <param-value><!--need to be "skipped" URL path, comma-delimited, prefixed! means "do not skip."        such as/myservlet, *.jsp--></param-value> </init-param> </filter> <filter-mapping> <filter-name>webx</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </we B-app>

Why use filter instead of servlet? The controller of the traditional web framework is generally implemented with Servlets. The reasons are:

    • Filter can "return control"-the above configuration file directly maps "/*" to the WEBX filter, which means that WEBX takes over all requests for the application. What about static pages and resources? It doesn't matter if WEBX finds that the request should not be handled by WEBX, it will "return" the control to the original controller-perhaps another filter, servlet, or back to the servlet engine, which is handled in the default manner. The servlet is not a mechanism of "return control".

    • Servlet/filter Mapping Limitations--the standard servlet engine that maps URLs to a Filter or servlet, only supports prefix mapping and suffix mapping, which is very limited. And the reality is often much more complicated. WEBX recommends mapping all requests to WEBX for more flexible mapping of WEBX requests.

If you have some other servlet mappings in your Web. XML, you can add these mapping or parameters in order to avoid conflicts with WEBX URLs excludes passthru . In this way, Webxframeworkfilter will exclude or skip the specified URL.

The passthru difference between "Skip" and " excludes exclude" is that if a servlet or filter passthru takes over a WEBX request, they can still access part of the service to WEBX, for a passthru requested The behavior of WEBX is more like a normal filter. While "exclude" is different, if a request is "excluded", WEBX will immediately discard the control and return the request to the server. The servlet or filter that takes over control will not be able to access all WEBX services.

Is the process of webxframeworkfilter processing a Web request.

WebxFrameworkFilterafter the request is received, it is called WebxRootController into the world of spring-all subsequent objects:,,, and so on, WebxRootController WebxController RequestContext Pipeline  are all configured in spring context through Springext.

     WebxRootControllerobject exists in root context and is shared by all child applications. It creates RequestContext instances-enhancing the functionality of the request, response, and session. Next, the WebxController object is called.

     WebxControllerobjects are exclusive to each sub-application, app1 and app2 can have different WebxController implementations. The default implementation will call pipeline.

Pipeline is also configured by each sub-application itself. If pipeline encounters a request that cannot be processed, such as a static page, picture, etc., pipeline should perform <exit/> valve forced exit. It then WebxRootController "gives up control"-which means that the request will be returned to the /WEB-INF/web.xml servlet, filter, or back to the servlet engine itself for processing.

3. Customizing the WEBX Framework

Webxrootcontroller is a logic that is shared by all sub-applications. <webx-configuration xmlns= "Http://www.alibaba.com/schema/services" >    <components>        < Rootcontroller class= "Com.myframework.MyRootController"/>     </components></webx-configuration>

Create your own WebxRootController . The easiest way to do this is to extend it AbstractWebxRootController without creating servlet/filter, initializing spring containers, handling request, response and more, and fully supporting all Springext functions, including error handling, All the conveniences in the WEBX framework, such as the development model.

WebxControlleris used to control sub-applications. Each sub-app can have a different WebxController implementation.

The default for the WEBX framework WebxController is to call pipeline. If you don't want to use pipeline and want to implement your own logic for sub-applications, the simplest way is to implement your own WebxController or extend AbstractWebxController .

Webxcontroller is used to control sub-applications. Each sub-app can have a different webxcontroller implementation. <webx-configuration xmlns= "Http://www.alibaba.com/schema/services" >    <components defaultcontrollerclass= "Com.myframework.MyController" >//Specifies the default WebxController implementation class.        <component name= "App1" >            <controller class= "Com.myframework.MyController"/>//explicitly specified WebxController for specific sub-applications The implementation class.        </component>    </components></webx-configuration>

The WEBX framework provides a scalable, extensible basic framework for processing Web requests. The basic functionality it provides is in fact a requirement for every web framework.

 

WEBX Study Notes (iii) WEBX Framework

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.