Jetty Development Guide: handlers

Source: Internet
Author: User
Rewrite Handler

Rewritehandler matches a request based on a set of rules, and then modifies the request according to the matching rules. The most common is to rewrite the request URI, but not limited to this: the rule can be configured as a redirect response, set a cookie or response code, modify the header, and so on.

Quick Start

The standard jetty release contains jetty-Rewrite module jar, in lib/jetty-rewrite-*. jar, and an example configuration file in the ETC/jetty-rewrite.xml. To activate the rewrite module, run the following command to start jetty:

$ java -jar start.jar OPTIONS=default,rewrite etc/jetty.xml etc/jetty-rewrite.xml 

Note: If you are using the test webapp to run the standard jetty release, there is a demo of the rewrite module in http: // localhost: 8080/Rewrite /.

Configure rules

Rules is configured by using Jetty. xml. The following example shows how to add a rewrite handler to the server:

<Configure id="Server" class="org.eclipse.jetty.server.Server">    <!-- create and configure the rewrite handler -->    <New id="Rewrite" class="org.eclipse.jetty.rewrite.handler.RewriteHandler">      <Set name="rewriteRequestURI">true</Set>      <Set name="rewritePathInfo">false</Set>      <Set name="originalPathAttribute">requestedPath</Set>        <!-- redirect the response. This is a redirect which is visible to the browser.           After the redirect, the browser address bar will show /redirected -->      <Call name="addRule">        <Arg>          <New class="org.eclipse.jetty.rewrite.handler.RedirectPatternRule">            <Set name="pattern">/redirect/*</Set>            <Set name="replacement">/redirected</Set>          </New>        </Arg>      </Call>        <!-- rewrite the request URI. This is an internal rewrite, visible to server,           but the browser will still show /some/old/context -->      <Call name="addRule">        <Arg>          <New class="org.eclipse.jetty.rewrite.handler.RewritePatternRule">            <Set name="pattern">/some/old/context</Set>            <Set name="replacement">/some/new/context</Set>          </New>        </Arg>      </Call>        <!-- reverse the order of the path sections. Internal rewrite -->      <Call name="addRule">        <Arg>          <New class="org.eclipse.jetty.rewrite.handler.RewriteRegexRule">            <Set name="regex">/reverse/([^/]*)/(.*)</Set>            <Set name="replacement">/reverse/$2/$1</Set>          </New>        </Arg>      </Call>    </New>       <!-- add the rewrite handler to the server -->    <Set name="handler"><Ref id="Rewrite" /></Set></Configure>

For more configuration examples, see ETC/jetty-rewrite.xml.

Embedded example

The following is an example of embedding jetty, which is the same as the preceding configuration file:

Server server = new Server(); RewriteHandler rewrite = new RewriteHandler();rewrite.setRewriteRequestURI(true);rewrite.setRewritePathInfo(false);rewrite.originalPathAttribute("requestedPath"); RedirectPatternRule redirect = new RedirectPatternRule();redirect.setPattern("/redirect/*");redirect.setReplacement("/redirected");  rewrite.addRule(redirect); RewritePatternRule oldToNew = new RewritePatternRule();oldToNew.setPattern("/some/old/context");oldToNew.setReplacement("/some/new/context");rewrite.addRule(oldToNew); RewriteRegexRule reverse = new RewriteRegexRule();reverse.setRegex("/reverse/([^/]*)/(.*)");reverse.setReplacement("/reverse/$2/$1");rewrite.addRule(reverse); server.setHandler(rewrite);
Rules

There are several different types of rules.

Patternrule

Use the servlet mode syntax to match the requested URI.

Cookiepatternrule

Add a cookie to the response.

Headerpatternrule

Add/modify the header in the response.

Redirectpatternrule

Redirect response.

Responsepatternrule

Send a response code (status or error ).

Rewritepatternrule

Rewrite Uri.

Regexrule

Use a regular expression to match the request URI.

Redirectregexrule

Redirect response.

Rewriteregexrule

Rewrite URI

Headerrule

Match the request headers. Match or in a header name + specific value, or in a header existence (add any value ).

Forwardedschemaheaderrule

Set the request plan (the default is https ).

Others

Other odd rules.

Msiesslrule

Disable SSL for ie5 and IE6 to stay active.

Legacyrule

Implements the legacy API of rewritehandler.

Rulecontainer

Organize rules together.

Virtualhostrulecontainer

The contained rules is only applied to a specific virtual host or a set of virtual hosts.

Write custom handlers

Handler is the jetty component used to process requests.
Some jetty users never need to write jetty handler, but use servlet API (http://download.eclipse.org/jetty/stable-9/xref/org/eclipse/jetty/servlet/package-summary.html ). You can reuse existing jetty handlers for context, security, sessions, and servlets without any extensions. However, some users may have special requirements or worry about footprint issues and disable the complete servlet API. Implementing a jetty handler for them is a straightforward method that provides dynamic web content with minimal changes.

Handler API

The handler interface provides the core of jetty content generation and processing. Classes that implement this interface are used to coordinate requests, filter requests, and generate content.
The core API of the handler interface is:

public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)    throws IOException, ServletException

The implementation of this method can process one request, pass the request to another handler (or servlet), or it can modify and/or wrap the request, and then pass it. There are three types of handler:
1) Coordinate handlers: transfer requests to other handlers (handlercollection, contexthandlercollection );
2) filter handlers: enlarge a request and pass it to other handlers (handlerwrapper, contexthandler, sessionhandler );
3) generate handlers: generate content (resourcehandler and servlethandler ).

Target

The target of a handler is the resource identifier that processes the request. This is usually the URI from an HTTP request. However, in the following two environments, the target can be different from the requested URI:
1) if a request is distributed to a command resource, such as a named servlet, the target is the name of the resource;
2) If the request is through the request scheduler, the target is the uri of the contained resource, which is different from the URI of the actual request.

Requests and responses

The request and response objects used in the signature of the processing method are Servlet request and Servlet response. These are standard APIs. More often, Jetty implementations of these classes are required: request and response. However, since requests and responses can be encapsulated by handlers, filters, and servlets, it is impossible to directly pass the implementation. The following method is used to obtain the core implementation objects of any wrapper:

Request base_request = request instanceof Request ? (Request)request : HttpConnection.getCurrentConnection().getRequest();Response base_response = response instanceof Response ? (Response)response : HttpConnection.getCurrentConnection().getResponse();

Note: If a handler transmits a request to another handler, it should use the request/response object instead of the basic object. This is to keep the encapsulation made by upstream handlers.

Distribution

The distribution parameter shows the call processing status, which can be:
1) Request = 1: the original request received from a connector;
2) Forward = 2: Request forwarded by a requestdispatcher;
3) include = 4: request included by a requestdispatcher;
4) error = 8: The request is forwarded to an error handler by the container.
These are interesting for most servlets and related handlers. For example, the security handler only authenticates and authorizes the request distribution application.

Process requests

A handler can process a request through:
1) generate a response;
2) filter requests and/or responses;
3) send the request and response to another handler.
The following is a detailed description.

Generate a response

Onehandler shows how to generate a response.

You can use the usual servlet response API, usually set some status, content headers, and then output content:

response.setContentType("text/html");response.setStatus(HttpServletResponse.SC_OK);response.getWriter().println("

Handler needs to mark that it has processed the request, and the request should not be passed to other handlers:

Request base_request = (request instanceof Request) ? (Request)request:HttpConnection.getCurrentConnection().getRequest();base_request.setHandled(true);
Filter requests and/or responses

Once the basic request or response object is obtained, you can modify it. Generally, you will make modifications to complete the process:
1) split the URI to the contextpath, servletpath, and pathinfo components;
2) Associate requests with resources for static content;
3) Associate requests with sessions;
4) Associate requests with security subjects;
5) change the URI and path when the request is distributed to another resource.
You can also update the request context:
1) set the context class loader of the current thread;
2) set local variables of the thread to indicate the current servletcontext.
In general, Jetty passes a modified request to another handler and can only restore the modification in the Finally block:

try{   base_request.setSession(a_session);   next_handler.handle(target,request,response,dispatch);}finally{   base_request.setSession(old_session);}

The classes that implement the handlerwrapper class are typical handler filters of this type.

Send requests and responses to another handler

A handler can simply inspect the request, and then use the target, request URI or other information to select another handler as the handler for processing the next request. These handlers generally implement the handlercontainer interface.
Examples include:

Class handler collection

Handlerlist

Contexthandlercollection

More handlers Information

Check jetty latest source xref and jetty latest javadoc to get detailed information about every jetty handler.

 

For more jetty information, see jetty overview.

Jetty Development Guide: handlers

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.