Jetty introduction Handler

Article reference

http://ipjmc.iteye.com/blog /1839999

http://blog.csdn.net/huangmin2050/article/details/7487922

Embedding a jetty service generally involves the following steps , Create Server, load Connectors, load handlers, load Servlets, etc., start service start, and finally join server join.

A Jetty Server can be regarded as composed of the following parts, The Connector is responsible for receiving the HTTP request from the client, and the processing of the request is done by the Handler /span>.

Handler is a very important thing in Jetty, Jetty Some Handlers are implemented internally, which can be divided into the following categories:

1. Coordination Handler: Handler responsible for routing requests to other Handlers (such as: HandlerConnection, ContextHandlerConnection)

2. Filtering Handler: Responsible for setting some parameters in the request, and then forwarding the request to other Handlers (such as: HandlerWapper, ContextHandler, SessionHandler)

3. Generate Handler: responsible for generating the content of the response (such as: ResourceHandler, ServletHandler)

When jetty only serves one service without any handlers and Connectors, the browser visits will return 404. It is easy to understand that there is a service, but the service does not return a response, so it will return 404.

public static void main(String[] args) throws Exception
{
Server server = new Server(8081);
   // server.setHandler(new HelloHandler());
 
server.start();
server.join();
}

After the service is started, since there is no operation for the service, 404 will be returned to all requests.

Look at the introduction of a simple HelloHandler and the parameter introduction of the handle method:

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("

Hello World2

"); } }

target——The target of the request, which can be a URL or an adapter.

baseRequest-jetty variable request object, you don’t need to encapsulate it.

request-an immutable request object that can be encapsulated.

response——response object, which can be encapsulated

The above code handle sets the status of the response, ContentType, and mark whether the request is processed, etc. . Complex processing can be used in combination with multiple Handlers to achieve complex processing results. Some of jetty’s handlers can be found in org.eclipse.jetty.server.handler

The powerful place of Handler is Several Handlers can be set for Jetty Server, each Handler completes its own function, the processing process of Handler is as follows:

HandlerList and HandlerConnection can set up several Handlers, Handlers are executed one after another in order. For HandlerList, as long as a Handler marks the request as processed, or throws an exception, the call of the Handler ends here. The HandlerConnection will not end, it will call until the last Handler.

Processing of multiple handlers:

public static void main(String[] args) throws Exception
{
Server server = new Server(8081);
server.setHandler(new HelloHandler());//Invalid
server.setHandler(new HelloHandler());//Twice setHandler is only useful this time
server.start();
server.join();
}

The server calls setHandler twice, but only the last setHandler is valid, so the above code does not work.

For multiple handlers, the following is the right way:

1. HandlerCollection will execute each handler in order, put the results together into response, and return. As follows:

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 executes the handlers in order, if an error is thrown, the next handler is executed, otherwise it is not executed. Such as:

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();
}

The following is a specific example to illustrate, you need to pay attention to the difference between HandlerList and HandlerConnection, there are comments in the 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, ServletException {
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 processed, 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 baseRequest, HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
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("

Hello World1

"); response.getWriter().println("Request url: "+ target); } } }

Remarks: After running the code directly to process the handler, it will not continue to run. If you want to test that all handlers are running, use HandlerCollection here.

Article reference

http://ipjmc.iteye.com/blog/1839999

http:/ /blog.csdn.net/huangmin2050/article/details/7487922

Embedding a jetty service generally involves the following steps, Create Server, load Connectors, load handlers, load Servlets, etc., start service start, and finally join server join.

A Jetty Server can be regarded as composed of the following parts, The Connector is responsible for receiving the HTTP request from the client, and the processing of the request is done by the Handler /span>.

Handler is a very important thing in Jetty, Jetty Some Handlers are implemented internally, which can be divided into the following categories:

1. Coordination Handler: Handler responsible for routing requests to other Handlers (such as: HandlerConnection, ContextHandlerConnection)

2. Filtering Handler: Responsible for setting some parameters to the request, and then forwarding the request to other Handlers (such as: HandlerWapper, ContextHandler, SessionHandler)

3. Generate Handler: responsible for generating the content of the response (such as: ResourceHandler, ServletHandler)

When jetty only serves one service without any handlers and Connectors, the browser visits will return 404. It is easy to understand that there is a service, but the service does not return a response, so it will return 404.

public static void main(String[] args) throws Exception
{
Server server = new Server(8081);
   // server.setHandler(new HelloHandler());
 
server.start();
server.join();
}

After the service is started, since there is no operation for the service, 404 will be returned to all requests.

Look at the introduction of a simple HelloHandler and the parameter introduction of the handle method:

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("

Hello World2

"); } }

target——The target of the request, which can be a URL or an adapter.

baseRequest-jetty variable request object, you don’t need to encapsulate it.

request-an immutable request object that can be encapsulated.

response——response object, which can be encapsulated

The above code handle sets the status of the response, ContentType, and mark whether the request is processed, etc. . Complex processing can be used in combination with multiple Handlers to achieve complex processing results. Some of jetty’s handlers can be found in org.eclipse.jetty.server.handler

The powerful place of Handler is Several Handlers can be set for Jetty Server, each Handler completes its own function, the processing process of Handler is as follows:

HandlerList and HandlerConnection can set up several Handlers, Handlers are executed one after another in order. For HandlerList, as long as a Handler marks the request as processed, or throws an exception, the call of the Handler ends here. The HandlerConnection will not end, it will call until the last Handler.

Processing of multiple handlers:

public static void main(String[] args) throws Exception
{
Server server = new Server(8081);
server.setHandler(new HelloHandler());//Invalid
server.setHandler(new HelloHandler());//Twice setHandler is only useful this time
server.start();
server.join();
}

The server calls setHandler twice, but only the last setHandler is valid, so the above code does not work.

For multiple handlers, the following is the right way:

1. HandlerCollection will execute each handler in order, put the results together into response, and return. As follows:

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 executes the handlers in order, if an error is thrown, the next handler is executed, otherwise it is not executed. Such as:

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();
}

The following is a specific example to illustrate, you need to pay attention to the difference between HandlerList and HandlerConnection, there are comments in the 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, ServletException {
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 processed, 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 baseRequest, HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
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("

Hello World1

"); response.getWriter().println("Request url: "+ target); } } }

Remarks: After running the code directly to process the handler, it will not continue to run. If you want to test that all handlers are running, use HandlerCollection here.

Leave a Comment

Your email address will not be published.