如何在Jersey中的POST请求中处理重复参数

时间:2016-06-15 07:58:47

标签: java jersey jax-rs jersey-2.0 bean-validation

我使用Jersey 2.22.1来实现REST API。

我想知道如何处理POST请求中的重复参数。

这是我的资源类:

public class MyResource
{
    @NotNull(message = "Missing parameter 'param1'")
    @FormParam("param1")
    private String m_param1;

    @NotNull(message = "Missing parameter 'param2'")
    @FormParam("param2")
    private String m_param2;

    @POST
    @Produces(MediaType.TEXT_PLAIN)
    @Consumes("application/x-www-form-urlencoded")
    public Response test(String body)
    {
        // at this point...
        // the value of `body` is the full request body
        // the value of `m_param1` is the 1st value of param1 in the request body
        // the value of `m_param2` is the value of param2 in the request body
        ...
    }
}

E.g。如果我发送一个POST请求与以下正文:

param1=00000001&param2=00000002&param1=00000003

然后m_param1的值为00000001

Jersey框架可以检测请求体中是否存在重复参数?或者我是否需要添加代码来解析请求正文以查找重复项?

1 个答案:

答案 0 :(得分:1)

您可以使用filter检查参数以确保没有重复项。如果有,只需发送400状态。

public class DuplicateFormParamsFilter implements ContainerRequestFilter {

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        ContainerRequest cr = (ContainerRequest) requestContext;
        cr.bufferEntity();
        Form form = cr.readEntity(Form.class);
        MultivaluedMap<String, String> asMap = form.asMap();
        for (String key: asMap.keySet()) {
            if (asMap.get(key).size() > 1) {
                throw new BadRequestException("Duplicate param: " + key);
            }
        }
    }
}

在这里,您正在阅读请求实体,但首先要缓冲它,以便Jersey可以重新读取它。

以下是使用Jersey Test Framework的完整示例。

import java.io.IOException;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import javax.ws.rs.BadRequestException;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.NameBinding;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.client.Entity;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;

import org.glassfish.jersey.server.ContainerRequest;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.glassfish.jersey.test.TestProperties;
import org.junit.Test;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;

/**
 * @author Paul Samsotha
 */
public class DuplicateFormParamsTest extends JerseyTest {

    @Path("test")
    public static class TestResource {

        @POST
        @NoDuplicateParams
        @Consumes("application/x-www-form-urlencoded")
        public String post(@FormParam("param") String param) {
            return param;
        }
    }

    @NoDuplicateParams
    public static class DuplicateFormParamsFilter implements ContainerRequestFilter {

        @Override
        public void filter(ContainerRequestContext requestContext) throws IOException {
            ContainerRequest cr = (ContainerRequest) requestContext;
            cr.bufferEntity();
            Form form = cr.readEntity(Form.class);
            MultivaluedMap<String, String> asMap = form.asMap();
            for (String key: asMap.keySet()) {
                if (asMap.get(key).size() > 1) {
                    throw new BadRequestException("Duplicate param: " + key);
                }
            }
        }
    }

    @NameBinding
    @Target({ElementType.METHOD, ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    public static @interface NoDuplicateParams {
    }

    @Override
    public ResourceConfig configure() {
        enable(TestProperties.DUMP_ENTITY);
        enable(TestProperties.LOG_TRAFFIC);
        return new ResourceConfig(TestResource.class)
                .register(DuplicateFormParamsFilter.class);
    }

    @Test
    public void sdhoul_get_400_with_dup() {
        final Form form = new Form()
                .param("param", "value1")
                .param("param", "value2");
        final Response response = target("test").request().post(Entity.form(form));
        assertThat(response.getStatus(), is(400));
    }

    @Test
    public void sdhoul_get_200_with_single() {
        final Form form = new Form()
                .param("param", "value1");
        final Response response = target("test").request().post(Entity.form(form));
        assertThat(response.getStatus(), is(200));
        assertThat(response.readEntity(String.class), is("value1"));
    }
}

示例使用了Name Binding,因此只有使用@NoDuplicateParams注释的方法才能通过过滤器。或者您可以忘记名称绑定,并让所有请求都通过过滤器,只需检查过滤器中的内容类型application/x-www-form-urlencoded。这样你就不需要在任何地方注释。

更新

我应该提到的一件事是,我想我记得一个不起作用的情况(尝试如上所述提取表格)。我完全忘记了这种情况,但它与servlet环境有关,并且之前读取了表单参数,因此上面的尝试阅读不会起作用。

我必须做的是使用Jersey内部属性,Jersey stores the parameters。所以你需要以这种方式检索表单

Form form = (Form) requestContext.getProperty(
        InternalServerProperties.FORM_DECODED_PROPERTY);