如何让jersey根据http标头注入一个参数?

时间:2016-04-17 15:10:50

标签: jersey jax-rs

我有一个界面,并希望将其作为REST API打开。

接口:

string createToken(String username, String scopes);

REST Web API:

@GET
@Path("/createToken")
@Override
public string createToken(@InjectParam String username, String scopes) {
  ...
}

作为一个简单的Java API,接口本身是有意义的 - 由特定(唯一)用户创建访问令牌。

但是,作为REST Web API,我需要上一步来检索用户名,这是基于http头中传递的一些用户数据,如SSO密钥。

如何将值注入username - 从HTTP标头中提取?谢谢。

2 个答案:

答案 0 :(得分:1)

创建Provider以将值注入自定义注释。请参阅小工作示例here。请参阅下面的内联源。

该示例从sso标记中提取用户名。这是一个虚拟提取。

*我没有使用@InjectParam

调用示例:

curl -X POST -H "ssoToken: 1234" http://localhost:8080/JerseyCustomParamInjection-1.0-SNAPSHOT/oauth2/createAccessToken

自定义注释:

@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface LoggedUser {
}

进行注射的提供者:

@Provider
public class LoggedUserProvider implements
        Injectable<String>,
        InjectableProvider<LoggedUser, Parameter> {

    @Context
    private HttpServletRequest request;

    public LoggedUserProvider() {
    }

    @Override
    public Injectable<String> getInjectable(ComponentContext cc, LoggedUser a, com.sun.jersey.api.model.Parameter c) {
        return this;
    }

    @Override
    public ComponentScope getScope() {
        return ComponentScope.PerRequest;
    }

    @Override
    public String getValue() {
        String sso = request.getHeader("ssoToken");
        if (sso == null) {
            throw new WebApplicationException(Response.Status.UNAUTHORIZED);
        }
        // Retreive username from soo
        String username = " <extracted username from sso="+sso+">";
        return username;
    }
}

定义要注入值的资源:

@Path("/oauth2")
public class Resource {

    @POST
    @Path("/createAccessToken")
    public String createAccessToken(
            @LoggedUser String username
    ) {
        return username + " <created access token using the logged in injected username>";
    }
}

Servlet配置(web.xml):

<web-app id="WebApp_ID" version="2.4"
         xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <display-name>Restful Web Application</display-name>
    <servlet>
        <servlet-name>jersey-serlvet</servlet-name>
        <servlet-class>
            com.sun.jersey.spi.container.servlet.ServletContainer
        </servlet-class>
        <init-param>
            <param-name>com.sun.jersey.config.property.packages</param-name>
            <param-value>info.fastpace.jerseycustomparaminjection</param-value>
        </init-param>
        <init-param>
            <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
            <param-value>true</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>jersey-serlvet</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
</web-app>

答案 1 :(得分:0)

您应该使用HeaderParam。见this

@GET
@Path("/createToken")
@Override
public string createToken(@HeaderParam("username") String username, String scopes) {
  ...
}

如果你必须提取用户名并且必须注入它,你将必须实现一个提供者:

@Provider
public class UsernameProvider
      extends AbstractHttpContextInjectable<Locale>
      implements InjectableProvider<Context, Type> {

    @Override
    public Injectable<E> getInjectable(ComponentContext compCntxt, Context cntxt, Type typ) {
        if (typ.equals(String.class)) {
            return this;
        }
        return null;
    }

    @Override
    public ComponentScope getScope() {
        return ComponentScope.PerRequest;
    }

    @Override
    public String getValue(HttpContext httpCntxt) {
        final Request rqst = httpCntxt.getRequest();
        String username = null;
        //Extract 'username' from Headers 
        return username;
    }
}

详细解释here