注入多值映射的注入提供程序(application / x-www-form-urlencoded)

时间:2016-10-10 21:10:01

标签: java jersey jersey-2.0 hk2

泽西岛文档举例how to inject HttpSession on resources。我应该如何注入(或获取访问权限)使用“Content-Type:application / x-www-form-urlencoded”的请求发送的表单参数?我看到这些是parameters on methods, and do not seem to be annotated传递的,让我相信这里有一些怪癖?

我正在使用的(天真)工厂实现如下,JerseyHttpServletRequestWrapper是我自己的一个类:

import org.glassfish.hk2.api.Factory;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.MultivaluedMap;

public class JerseyHttpServletRequestWrapperFactory implements Factory<JerseyHttpServletRequestWrapper> {
    private final HttpServletRequest request;
    private final MultivaluedMap<String, String> formParams;

    @Inject
    public JerseyHttpServletRequestWrapperFactory(HttpServletRequest request, MultivaluedMap<String, String> formParams) {
        this.request = request;
        this.formParams = formParams;
    }

    @Override
    public JerseyHttpServletRequestWrapper provide() {
        return new JerseyHttpServletRequestWrapper(request, formParams);
    }

    @Override
    public void dispose(JerseyHttpServletRequestWrapper jerseyHttpServletRequestWrapper) {
    }
}

我在想这里应该将一个实体提供者注入到实例中,这样我就可以检查实际上是否有一个随请求发送的实体。尝试直接注入MultivaluedMap错误:

org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at SystemInjecteeImpl(requiredType=MultivaluedMap<String,String>,parent=JerseyHttpServletRequestWrapperFactory,qualifiers={},position=1,optional=false,self=false,unqualified=null,2067821943)

1 个答案:

答案 0 :(得分:2)

当你这样做时

@POST
public Response post(MultivaluedMap<String, String> params) {}

此方法参数注入的处理方式与常规字段/构造函数注入不同。因此,您无法尝试将MultivaluedMap注入字段。

你可以做的是注入ContainerRequest,然后阅读正文。您需要检查它是否为POST请求,而Content-Type是application / x-www-form-urlencoded。如果不这样做,当您尝试阅读实体时,您可能会遇到异常。

@Inject
ContainerRequest request;

if (request.getMethod().toUpperCase().equals("POST")
     && request.getMediaType().equals(MediaType.APPLICATION_FORM_URLENCODED_TYPE)) {
    request.bufferEntity();
    Form form = request.readEntity(Form.class);
    MultivaluedMap<String, String> params = form.asMap();
}