JBoss.orgCommunity Documentation

第 7 章 @HeaderParam

7.1. HeaderDelegates

注意

RESTEasy @HeaderParam 注解支持不直接指定参数名

@HeaderParam 注解允许您将请求 HTTP 头信息映射到方法调用。

GET /books?num=5

@GET
public String getBooks(@HeaderParam("From") String from) {
...
}

与 PathParam 类似,您的参数类型可以是String,原生类型,String作为输入参数的构造函数或静态 valueOf() 方法。例如,MediaType 有一个 valueOf() 方法,您可以这样做:

@PUT
public void put(@HeaderParam("Content-Type") MediaType contentType, ...)

除了常见的将参数转换为字符串和从字符串转换参数的方法之外,使用@HeaderParam注解的参数还有另一个选项: RuntimeDelegate$HeaderDelegate 的实现:

    /**
     * Defines the contract for a delegate that is responsible for
     * converting between the String form of a HTTP header and
     * the corresponding JAX-RS type {@code T}.
     *
     * @param <T> a JAX-RS type that corresponds to the value of a HTTP header.
     */
    public static interface HeaderDelegate<T> {

        /**
         * Parse the supplied value and create an instance of {@code T}.
         *
         * @param value the string value.
         * @return the newly created instance of {@code T}.
         * @throws IllegalArgumentException if the supplied string cannot be
         *                                  parsed or is {@code null}.
         */
        public T fromString(String value);

        /**
         * Convert the supplied value to a String.
         *
         * @param value the value of type {@code T}.
         * @return a String representation of the value.
         * @throws IllegalArgumentException if the supplied object cannot be
         *                                  serialized or is {@code null}.
         */
        public String toString(T value);
    }

HeaderDelegate 类似于 ParamConverter ,但是注册一个 HeaderDelegate 并不十分方便。因为与 ParamConverterProvider 等不同,JAX-RS 规范没有将它视为提供者(provider)。org.jboss.resteasy.spi.ResteasyProviderFactory 有如下方法,需要 javax.ws.rs.core.Configurable 的子类或实现: The class javax.ws.rs.core.Configurable, which is subclassed by, for example, org.jboss.resteasy.spi.ResteasyProviderFactory has methods like

    /**
     * Register a class of a custom JAX-RS component (such as an extension provider or
     * a {@link javax.ws.rs.core.Feature feature} meta-provider) to be instantiated
     * and used in the scope of this configurable context.
     *
     * ...
     *
     * @param componentClass JAX-RS component class to be configured in the scope of this
     *                       configurable context.
     * @return the updated configurable context.
     */
    public C register(Class<?> componentClass);

但目前尚不清楚它们是否适用于HeaderDelegates。

RESTEasy 通过允许 HeaderDelegates 使用@Provider注解来解决这个问题。不仅 ResteasyProviderFactory.register() 处理 HeaderDelegates,而且另一个有用的结果是可以在运行时自动发现 HeaderDelegates。