Jetty introduction of Handler

Source: Internet
Author: User
Tags static class wrapper

Embedding a jetty service typically has the following steps, creating the server, loading the connectors, loading the handlers, loading the Servlets, starting service start, and finally joining the server join.

A jetty server can be seen as a few parts, where connector is responsible for receiving HTTP requests from clients, and the processing of requests is done by handler.


handler in the jetty is a very important thing, jetty internal implementation of some handler, can be divided into several categories:

1. Coordination handler: responsible for routing request to other handler handler (such as: Handlerconnection, Contexthandlerconnection)

2. Filter handler: Responsible for setting some parameters to the request, and then transferring the requests to other handler (e.g. Handlerwapper, Contexthandler, Sessionhandler)

3. Build handler: The content that is responsible for generating the response (for example: Resourcehandler, Servlethandler)
   browser access returns 404 when jetty serves only one service, without any handlers and connectors. It is easy to understand that there is a service, but the service does not return response, so it returns 404.

Java Code Collection Code

public static void Main (string[] args) throws Exception  
{  
    Server server = new server (8081);  
   Server.sethandler (New Hellohandler ());  

    Server.start ();  
    Server.join ();  

After the service starts, it returns 404 for all request because there are no operations for the service.

Then look at a simple hellohandler introduction and the parameters of the handle method:

Java Code Collection Code

    public class Hellohandler extends Abstracthandler  
    {public  
        void handle (String target,request baserequest, HttpServletRequest request,httpservletresponse response)   
            throws IOException, servletexception  
        {  
            Response.setcontenttype ("Text/html;charset=utf-8");  
            Response.setstatus (HTTPSERVLETRESPONSE.SC_OK);  
            Baserequest.sethandled (true);  
            Response.getwriter (). println ("

The target of the target--request can be a URL or an adapter.

Baserequest--jetty variable Request object, can not be encapsulated.

The request--immutable Request object can be encapsulated.

Response--response object, can be encapsulated

As above code handle set response status, contenttype and tag request is handled, etc... Complex processing can be used in combination with multiple handler to achieve complex processing results. Some of the handler that jetty can find in Org.eclipse.jetty.server.handler



is the powerful place where handler can set up several jetty for handler server, Each handler completes its own function, handler process is as follows:



handlerlist and Handlerconnection can set up several handler, handler in order one after another execution. For Handlerlist, the handler call ends as long as there is a handler that marks the request as handled or throws an exception. And Handlerconnection will not end, always call to the last handler.

Processing of multiple handler:
Java Code Collection Code

public static void Main (string[] args) throws Exception  
{  
    Server server = new server (8081);  
    Server.sethandler (New Hellohandler ());//Invalid  
    Server.sethandler (new Hellohandler ());//two times SetHandler it only works later.  
    Server.start ();  
    Server.join ();  
}  

Server called two times SetHandler, but only the last sethandler valid, so the above code is not.

Treatment for multiple handler, such as the bottom is the right path:

1, Handlercollection will execute each handler in order, and put the results together to response, return. As follows:
Java Code Collection Code

public static void Main (string[] args) throws Exception  
{  
    Server server = new server (8081);  
    Handlercollection HC =new handlercollection ();  
    Hc.sethandlers (New Handler[]{new Hellohandler (), New Hellohandlerscond ()});  
    Server.sethandler (hc);  
    Server.start ();  
    Server.join ();  
}  

2, Handlerlist order to execute handler, if the error is thrown to execute the next handler, otherwise not executed. Such as:
Java Code Collection Code

public static void Main (string[] args) throws Exception  
{  
    Server server = new server ();  
    Selectchannelconnector connector = new Selectchannelconnector ();  
    Connector.setport (8080);  
    Server.addconnector (connector);  

    Resourcehandler Resource_handler = new Resourcehandler ();  
    Resource_handler.setdirectorieslisted (true);  
    Resource_handler.setwelcomefiles (New string[]{"index.html"});  

    Resource_handler.setresourcebase (".");  

    Handlerlist handlers = new Handlerlist ();  
    Handlers.sethandlers (new handler[] {resource_handler, New DefaultHandler ()});  
    Server.sethandler (handlers);  

    Server.start ();  
    Server.join ();  
}  

Here's a concrete example to note that you need to pay attention to the difference between handlerlist and handlerconnection, with comments in the code:

Java Code Collection Code

Package hb.jetty;  
Import Java.io.File;  
Import java.io.IOException;  

Import Java.util.Map;  
Import javax.servlet.ServletException;  
Import Javax.servlet.http.HttpServletRequest;  

Import Javax.servlet.http.HttpServletResponse;  
Import Org.eclipse.jetty.server.NCSARequestLog;  
Import Org.eclipse.jetty.server.Request;  
Import Org.eclipse.jetty.server.Handler;  
Import Org.eclipse.jetty.server.Server;  
Import Org.eclipse.jetty.server.handler.AbstractHandler;  
Import Org.eclipse.jetty.server.handler.DefaultHandler;  
Import org.eclipse.jetty.server.handler.HandlerCollection;  
Import org.eclipse.jetty.server.handler.HandlerList;  
Import Org.eclipse.jetty.server.handler.HandlerWrapper;  

Import Org.eclipse.jetty.server.handler.RequestLogHandler; public class Manyhandlers {public static void main (string[] args) throws Exception {Server server = new  

        Server (8080);  
        Create the handlers Handler param = new Paramhandler (); HandlErwrapper wrapper = new Handlerwrapper () {@Override public void handle (String target, Request Baserequest, HttpServletRequest request, httpservletresponse response) throws IOException, Servlete  
                xception {Request.setattribute ("Welcome", "Wylazy");  
            Super.handle (target, baserequest, request, response);  

        }  
        };  
        Handler Hello = new Hellohandler ();  
        Wrapper.sethandler (hello);  

Handler DFT = new DefaultHandler ();  
        Handlerlist will call each handler in turn until a handler marks the request as handled, that is, sethandled (true);  
        Handlerlist list = new Handlerlist ();  
        List.sethandlers (new handler[] {param, wrapper, DFT});  

        Server.sethandler (list);  
        Requestloghandler log = new Requestloghandler ();  

        Log.setrequestlog (New Ncsarequestlog (File.createtempfile ("demo", "Log"). GetAbsolutePath ()); Handlercollection will call each handler in turn, even if the request has been processed/HAndlercollection handlers = new Handlercollection ();  
Handlers.sethandlers (new handler[] {list, log});  

        Server.sethandler (handlers);  
        Server.start ();  
    Server.join (); public static class Paramhandler extends Abstracthandler {public void handle (String target, Request Ba Serequest, HttpServletRequest request, httpservletresponse response) throws IOException, Servletexceptio  
            n {Map params = Request.getparametermap ();  
                if (params.size () > 0) {response.setcontenttype ("Text/plain");  
                Response.getwriter (). println (params);  
            Baserequest.sethandled (TRUE);  
        }//Baserequest.sethandled (TRUE); } public static class Hellohandler extends Abstracthandler {public void handle (String target,    
         Request Baserequest, HttpServletRequest request, httpservletresponse response)       Throws IOException, servletexception {response.setcontenttype ("text/html;charset=utf-8");    
            Response.setstatus (HTTPSERVLETRESPONSE.SC_OK);    
            Baserequest.sethandled (TRUE);    
            Response.getwriter (). println ("

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.