Skip to main content

Notice: this Wiki will be going read only early in 2024 and edits will no longer be possible. Please see: https://gitlab.eclipse.org/eclipsefdn/helpdesk/-/wikis/Wiki-shutdown-plan for the plan.

Jump to: navigation, search

Difference between revisions of "Jetty/Howto/Write Jetty Handler"

< Jetty‎ | Howto
(New page: Many users of Jetty will not ever need to write a Jetty Handler, but instead will simply use the Servlet API. The existing jetty handlers for context, security, sessions and servlets can b...)
 
 
(16 intermediate revisions by 2 users not shown)
Line 1: Line 1:
Many users of Jetty will not ever need to write a Jetty Handler, but instead will simply use the Servlet API. The existing jetty handlers for context, security, sessions and servlets can be reused without the need for extension. However, some users may have special requirements or footprint concerns that prohibit the use of the full servlet API. For them implementing a Jetty handler is a straight forward way to provide dynamic web content with a minimum of fuss.
+
{{Jetty Howto
 +
| introduction =
 +
 
 +
{{Jetty Redirect|http://www.eclipse.org/jetty/documentation/current/writing-custom-handlers.html}}
 +
 
 +
The Handler is the Jetty component that deals with received requests.
 +
 
 +
Many users of Jetty will not ever need to write a Jetty Handler, but instead will simply use the [http://download.eclipse.org/jetty/stable-7/xref/org/eclipse/jetty/servlet/package-summary.html Servlet API.] The existing Jetty handlers for context, security, sessions and servlets can be reused without the need for extension. However, some users might have special requirements or footprint concerns that prohibit the use of the full servlet API. For them implementing a Jetty handler is a straight forward way to provide dynamic web content with a minimum of fuss.
 +
 
 +
See also the [http://wiki.eclipse.org/Jetty/Reference/Jetty_Architecture Jetty Architecture] page to understand more about Handlers vs. Servlets.
 +
}}
  
See also the [/display/JETTY/Architecture Architecture] page to understand more about Handlers vs. Servlets.
 
  
 
==The Handler API==
 
==The Handler API==
  
The [http://jetty.mortbay.org/xref/org/mortbay/jetty/Handler.html org.mortbay.jetty.Handler] interface provides Jetty's core of content generation or manipulation. Classes that implement this interface are used to coordinate requests, filter requests and generate content.
+
The [http://download.eclipse.org/jetty/stable-7/apidocs/org/eclipse/jetty/server/Handler.html Handler] interface provides Jetty's core of content generation or manipulation. Classes that implement this interface are used to coordinate requests, filter requests and generate content.
  
 
The core API of the Handler interface is
 
The core API of the Handler interface is
  
<div class="code panel" style="border-width: 1px"><div class="codeContent panelContent">
+
<source lang="java">
  
+
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
<span class="code-keyword">public</span> void handle(<span class="code-object">String</span> target, HttpServletRequest request, HttpServletResponse response, <span class="code-object">int</span> dispatch)
+
    throws IOException, ServletException
  <span class="code-keyword">throws</span> IOException, ServletException;
+
 
 +
</source>
 +
 
 +
An implementation of this method can handle a request, pass the request onto another handler (or servlet), or it can modify and/or wrap the request and then pass it on. This gives three styles of handler:
  
</div></div>
+
Coordinating Handlers - Handlers that route requests to other handlers (HandlerCollection, ContextHandlerCollection)
 +
Filtering Handlers - Handlers that augment a request and pass it on to other handlers (HandlerWrapper, ContextHandler, SessionHandler)
 +
Generating Handlers - Handlers that produce content (ResourceHandler and ServletHandler)
  
 
===The target===
 
===The target===
  
The target of a handler is an identifier for the resource that should handle the passed request. This is normally the URI that is parsed from a HTTP Request. However, in two key circumstances the target may differ from the URI of the passed request:
+
The target of a handler is an identifier for the resource that should handle the passed request. This is normally the URI that is parsed from an HTTP Request. However, in two key circumstances the target may differ from the URI of the passed request:
  
 
# If the request has been dispatched to a named resource, such as a named servlet, then the target is the name of that resource.
 
# If the request has been dispatched to a named resource, such as a named servlet, then the target is the name of that resource.
# If the request is being made by a call to [http://jetty.mortbay.org/apidocs/javax/servlet/RequestDispatcher.html#include(javax.servlet.ServletRequest,%20javax.servlet.ServletResponse) RequestDispatcher.include(...)]<br /> then the target is the URI of the included resource and will be different to the URI of the actual request.
+
# If the request is being made by a call to [http://download.oracle.com/docs/cd/E17477_01/javaee/5/api/javax/servlet/RequestDispatcher.html Request Dispatcher], then the target is the URI of the included resource and will be different to the URI of the actual request.
  
 
===The Request and Response===
 
===The Request and Response===
  
The request and response objects used in the signature of the handle method are [http://jetty.mortbay.org/xref/javax/servlet/http/HttpServletRequest.html HttpServletRequest] and [http://jetty.mortbay.org/xref/javax/servlet/http/HttpServletResponse.html HttpServletResponse]. These are the standard APIs and are moderately restricted in what can be done to the request and response. More often than not, access to the jetty implementations of these classes is required: [http://jetty.mortbay.org/xref/org/mortbay/jetty/Request.html Request] and [http://jetty.mortbay.org/xref/org/mortbay/jetty/Response.html Response]. However, as the request and response may be wrapped by handlers, filters and servlets, it is not possible to pass the implementation directly. The following mantra will retrieve the core implementation objects from under any wrappers:
+
The request and response objects used in the signature of the handle method are [http://download.oracle.com/docs/cd/E17477_01/javaee/5/api/javax/servlet/http/HttpServletRequest.html Servlet Request] and [http://download.oracle.com/docs/cd/E17477_01/javaee/5/api/javax/servlet/http/HttpServletResponse.html Servlet Response]. These are the standard APIs and are moderately restricted in what can be done to the request and response. More often than not, access to the jetty implementations of these classes is required: [http://download.eclipse.org/jetty/stable-7/apidocs/org/eclipse/jetty/server/Request.html Request] and [http://download.eclipse.org/jetty/stable-7/apidocs/org/eclipse/jetty/server/Response.html Response]. However, as the request and response may be wrapped by handlers, filters and servlets, it is not possible to pass the implementation directly. The following mantra retrieves the core implementation objects from under any wrappers:
  
<div class="code panel" style="border-width: 1px"><div class="codeContent panelContent">
+
<source lang="java">
  
+
Request base_request = request instanceof Request ? (Request)request : HttpConnection.getCurrentConnection().getRequest();
Request base_request = request <span class="code-keyword">instanceof</span> Request?(Request)request:HttpConnection.getCurrentConnection().getRequest();
+
Response base_response = response instanceof Response ? (Response)response : HttpConnection.getCurrentConnection().getResponse();
Response base_request = response <span class="code-keyword">instanceof</span> Response?(Response)request:HttpConnection.getCurrentConnection().getResponse();
+
  
</div></div>
+
</source>
  
 
Note that if the handler passes the request on to another handler, it should use the<br /> request/response objects passed in and not the base objects. This is to preserve any wrapping done by up stream handlers.
 
Note that if the handler passes the request on to another handler, it should use the<br /> request/response objects passed in and not the base objects. This is to preserve any wrapping done by up stream handlers.
Line 55: Line 68:
 
===Generating a Response===
 
===Generating a Response===
  
The [http://jetty.mortbay.org/xref/org/mortbay/jetty/example/OneHandler.html OneHandler] embedded example shows how a simple handler may generate a response.
+
The [http://download.eclipse.org/jetty/stable-7/apidocs/org/eclipse/jetty/embedded/OneHandler.html OneHandler] embedded example shows how a simple handler can generate a response.
  
The normal servlet response API may be used and will typically set some status, content headers and the write out the content:
+
The normal servlet response API can be used and will typically set some status, content headers and then write out the content:
  
<div class="code panel" style="border-width: 1px"><div class="codeContent panelContent">
+
<source lang="java">
  
 
   
 
   
  response.setContentType(<span class="code-quote">"text/html"</span>);
+
  response.setContentType("text/html");
 
  response.setStatus(HttpServletResponse.SC_OK);
 
  response.setStatus(HttpServletResponse.SC_OK);
  response.getWriter().println(<span class="code-quote">"<h1>Hello OneHandler</h1>"</span>);
+
  response.getWriter().println("<h1>Hello OneHandler</h1>");
  
</div></div>
+
</source>
  
 
It is also very important that a handler indicate that it has completed handling the request and that the request should not be passed to other handlers:
 
It is also very important that a handler indicate that it has completed handling the request and that the request should not be passed to other handlers:
  
<div class="code panel" style="border-width: 1px"><div class="codeContent panelContent">
+
<source lang="java">
  
 
   
 
   
  Request base_request = (request <span class="code-keyword">instanceof</span> Request) ? (Request)request:HttpConnection.getCurrentConnection().getRequest();
+
  Request base_request = (request instanceof Request) ? (Request)request:HttpConnection.getCurrentConnection().getRequest();
  base_request.setHandled(<span class="code-keyword">true</span>);               
+
  base_request.setHandled(true);               
  
</div></div>
+
</source>
  
 
===Filtering the Request and/or Response===
 
===Filtering the Request and/or Response===
  
Once the base request or response object is obtained, it may be modified. Typically modifications are done to achieve:
+
Once the base request or response object is obtained, you can modify it. Typically you would make modifications to accomplish:
  
 
* breaking the URI into contextPath, servletPath and pathInfo components
 
* breaking the URI into contextPath, servletPath and pathInfo components
* to associate a resource base with a request for static content.
+
* associating a resource base with a request for static content.
* to associate a session with a request
+
* associating a session with a request
* to associate a security principal with a request
+
* associating a security principal with a request
* to change the URI and paths during a request dispatch forward to another resource.
+
* changing the URI and paths during a request dispatch forward to another resource.
  
The context of the request may also be updated:
+
You can also update the context of the request:
  
* Setting of the current threads context classloader
+
* Setting the current threads context classloader
 
* Setting thread locals to identify the current ServletContext.
 
* Setting thread locals to identify the current ServletContext.
  
 
Typically a modified request is passed to another handler and then the modifications are undone in a finally block afterwards:
 
Typically a modified request is passed to another handler and then the modifications are undone in a finally block afterwards:
  
<div class="code panel" style="border-width: 1px"><div class="codeContent panelContent">
+
<source lang="java">
  
 
   
 
   
  <span class="code-keyword">try</span>
+
  try
 
  {
 
  {
 
     base_request.setSession(a_session);
 
     base_request.setSession(a_session);
 
     next_handler.handle(target,request,response,dispatch);
 
     next_handler.handle(target,request,response,dispatch);
 
  }
 
  }
  <span class="code-keyword">finally</span>
+
  finally
 
  {
 
  {
 
     base_request.setSession(old_session);
 
     base_request.setSession(old_session);
 
  }
 
  }
  
</div></div>
+
</source>
  
The classes that implement the [http://jetty.mortbay.org/xref/org/mortbay/jetty/handler/HandlerWrapper.html HandlerWrapper] class are typically handler filters of this style.
+
The classes that implement the [http://download.eclipse.org/jetty/stable-7/apidocs/org/eclipse/jetty/server/handler/HandlerWrapper.html HandlerWrapper] class are typically handler filters of this style.
  
 
===Passing the Request and Response to another handler===
 
===Passing the Request and Response to another handler===
  
A handler may simply inspect the request and use the target, request URI or other information to select another handler to pass the request to. These handlers typically implement the [http://jetty.mortbay.org/xref/org/mortbay/jetty/HandlerContainer.html HandlerContainer] interface.
+
A handler might simply inspect the request and use the target, request URI or other information to select another handler to pass the request to. These handlers typically implement the [http://download.eclipse.org/jetty/stable-7/apidocs/org/eclipse/jetty/server/HandlerContainer.html HandlerContainer] interface.
  
 
Examples include:
 
Examples include:
  
* [http://jetty.mortbay.org/xref/org/mortbay/jetty/handler/HandlerCollection.html HandlerCollection] - A collection of handlers, where each handler is called regardless of the state of the request. This is typically used to pass a request to a [http://jetty.mortbay.org/xref/org/mortbay/jetty/handler/ContextHandlerCollection.html ContextHandlerCollection] and then the a [http://jetty.mortbay.org/xref/org/mortbay/jetty/handler/RequestLogHandler.html RequestLogHandler]
+
* [http://download.eclipse.org/jetty/stable-7/apidocs/org/eclipse/jetty/server/handler/HandlerCollection.html Class Handler Collection] - A collection of handlers, where each handler is called regardless of the state of the request. This is typically used to pass a request to a [http://download.eclipse.org/jetty/stable-7/apidocs/org/eclipse/jetty/server/handler/ContextHandlerCollection.html ContextHandlerCollection] and then the a [http://download.eclipse.org/jetty/stable-7/apidocs/org/eclipse/jetty/server/handler/RequestLogHandler.html RequestLogHandler]
* [http://jetty.mortbay.org/xref/org/mortbay/jetty/handler/HandlerList.html HandlerList] - A list of handlers which are called in turn until the request state is set as handled.
+
* [http://download.eclipse.org/jetty/stable-7/apidocs/org/eclipse/jetty/server/handler/HandlerList.html HandlerList] - A list of handlers which are called in turn until the request state is set as handled.
* [http://jetty.mortbay.org/xref/org/mortbay/jetty/handler/ContextHandlerCollection.html ContextHandlerCollection] - collection of Handlers of which on is selected by best match for the context path.
+
* [http://download.eclipse.org/jetty/stable-7/apidocs/org/eclipse/jetty/server/handler/ContextHandlerCollection.html ContextHandlerCollection] - collection of Handlers of which one is selected by best match for the context path.
 
+
===Examples===
+
  
See [http://jetty.mortbay.org/xref/org/mortbay/jetty/handler/package-summary.html org.mortbay.jetty.handler] package for some examples.
+
==More About Handlers==
  
</div>
+
See [http://download.eclipse.org/jetty/stable-7/xref/ Jetty 7 Latest Source XRef] and [http://download.eclipse.org/jetty/stable-7/apidocs/ Jetty 7 Latest JavaDoc] for detailed information on each Jetty handler.

Latest revision as of 15:11, 23 April 2013



Introduction

Warning2.png
Jetty 7 and Jetty 8 are now EOL (End of Life)




THIS IS NOT THE DOCUMENTATION YOU ARE LOOKING FOR!!!!!






All development and stable releases are being performed with Jetty 9 and Jetty 10.






This wiki is now officially out of date and all content has been moved to the Jetty Documentation Hub






Direct Link to updated documentation: http://www.eclipse.org/jetty/documentation/current/writing-custom-handlers.html


The Handler is the Jetty component that deals with received requests.

Many users of Jetty will not ever need to write a Jetty Handler, but instead will simply use the Servlet API. The existing Jetty handlers for context, security, sessions and servlets can be reused without the need for extension. However, some users might have special requirements or footprint concerns that prohibit the use of the full servlet API. For them implementing a Jetty handler is a straight forward way to provide dynamic web content with a minimum of fuss.

See also the Jetty Architecture page to understand more about Handlers vs. Servlets.


The Handler API

The Handler interface provides Jetty's core of content generation or manipulation. 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

An implementation of this method can handle a request, pass the request onto another handler (or servlet), or it can modify and/or wrap the request and then pass it on. This gives three styles of handler:

Coordinating Handlers - Handlers that route requests to other handlers (HandlerCollection, ContextHandlerCollection) Filtering Handlers - Handlers that augment a request and pass it on to other handlers (HandlerWrapper, ContextHandler, SessionHandler) Generating Handlers - Handlers that produce content (ResourceHandler and ServletHandler)

The target

The target of a handler is an identifier for the resource that should handle the passed request. This is normally the URI that is parsed from an HTTP Request. However, in two key circumstances the target may differ from the URI of the passed request:

  1. If the request has been dispatched to a named resource, such as a named servlet, then the target is the name of that resource.
  2. If the request is being made by a call to Request Dispatcher, then the target is the URI of the included resource and will be different to the URI of the actual request.

The Request and Response

The request and response objects used in the signature of the handle method are Servlet Request and Servlet Response. These are the standard APIs and are moderately restricted in what can be done to the request and response. More often than not, access to the jetty implementations of these classes is required: Request and Response. However, as the request and response may be wrapped by handlers, filters and servlets, it is not possible to pass the implementation directly. The following mantra retrieves the core implementation objects from under any wrappers:

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

Note that if the handler passes the request on to another handler, it should use the
request/response objects passed in and not the base objects. This is to preserve any wrapping done by up stream handlers.

The dispatch

The dispatch argument indicates the state of the handling of the call and may be:

  • REQUEST == 1 - An original request received from a connector.
  • FORWARD == 2 - A request being forwarded by a RequestDispatcher
  • INCLUDE == 4 - A request being included by a RequestDispatcher
  • ERROR == 8 - A request being forwarded to a error handler by the container.

These mostly have significance for servlet and related handlers. For example, the security handler only applies authentication and authorization to REQUEST dispatches.

Handling Requests

A Handler may handle a request by:

Generating a Response

The OneHandler embedded example shows how a simple handler can generate a response.

The normal servlet response API can be used and will typically set some status, content headers and then write out the content:

 
 response.setContentType("text/html");
 response.setStatus(HttpServletResponse.SC_OK);
 response.getWriter().println("<h1>Hello OneHandler</h1>");

It is also very important that a handler indicate that it has completed handling the request and that the request should not be passed to other handlers:

 
 Request base_request = (request instanceof Request) ? (Request)request:HttpConnection.getCurrentConnection().getRequest();
 base_request.setHandled(true);

Filtering the Request and/or Response

Once the base request or response object is obtained, you can modify it. Typically you would make modifications to accomplish:

  • breaking the URI into contextPath, servletPath and pathInfo components
  • associating a resource base with a request for static content.
  • associating a session with a request
  • associating a security principal with a request
  • changing the URI and paths during a request dispatch forward to another resource.

You can also update the context of the request:

  • Setting the current threads context classloader
  • Setting thread locals to identify the current ServletContext.

Typically a modified request is passed to another handler and then the modifications are undone in a finally block afterwards:

 
 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 typically handler filters of this style.

Passing the Request and Response to another handler

A handler might simply inspect the request and use the target, request URI or other information to select another handler to pass the request to. These handlers typically implement the HandlerContainer interface.

Examples include:

More About Handlers

See Jetty 7 Latest Source XRef and Jetty 7 Latest JavaDoc for detailed information on each Jetty handler.

Back to the top