Java Reference
In-Depth Information
ous case, response filters run after
resume()
,
cancel()
, or a timeout happens. See
Chapter 13
for more details on the asynchronous API.
Server Request Filters
Request filters are implementations of the
ContainerRequestFilter
interface:
package
package
javax
.
ws
.
rs
.
container
;
public
public interface
interface
ContainerRequestFilter
ContainerRequestFilter
{
public
public
void
void
filter
(
ContainerRequestContext requestContext
)
throws
throws
IOException
;
}
ContainerRequestFilters
come in two flavors: prematching and postmatching. Prematch-
ing
ContainerRequestFilters
are designated with the
@PreMatching
annotation and will
execute before the JAX-RS resource method is matched with the incoming HTTP request.
Prematching filters often are used to modify request attributes to change how they match to a
specific resource. For example, some firewalls do not allow PUT and/or DELETE invoca-
tions. To circumvent this limitation, many applications tunnel the HTTP method through the
HTTP header
X-Http-Method-Override
:
import
import
javax.ws.rs.container.ContainerRequestFilter
javax.ws.rs.container.ContainerRequestFilter
;
import
import
javax.ws.rs.container.ContainerRequestContext
javax.ws.rs.container.ContainerRequestContext
;
@Provider
@PreMatching
public
public class
class
HttpMethodOverride
HttpMethodOverride
implements
implements
ContainerRequestFilter
{
public
public
void
throws
IOException
{
String methodOverride
=
ctx
.
getHeaderString
(
"X-Http-Method-Override"
);
iif
(
methodOverride
!=
null
void
filter
(
ContainerRequestContext ctx
)
throws
null
)
ctx
.
setMethod
(
methodOverride
);
}
}
This
HttpMethodOverride
filter will run before the HTTP request is matched to a specific
JAX-RS method. The
ContainerRequestContext
parameter passed to the
filter()
meth-
od provides information about the request like headers, the URI, and so on. The
filter()
method uses the
ContainerRequestContext
parameter to check the value of the
X-Http-
Method-Override
header. If the header is set in the request, the filter overrides the request's
HTTP method by calling
ContainerRequestFilter.setMethod()
. Filters can modify
pretty much anything about the incoming request through methods on
Container-
RequestContext
, but once the request is matched to a JAX-RS method, a filter cannot modi-
fy the request URI or HTTP method.