在Content-Type中指定charset时,Jersey和@FormParam无法正常工作

时间:2013-07-11 20:03:33

标签: java servlets http-headers jersey jax-rs

charset标题中指定Content-Type属性时,似乎Jersey 2.0(使用servlet 3.1)无法解码参数。

例如,考虑以下终点:

@POST
@Path("/hello")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON)
public Response hello(@FormParam("name") String name) {
    System.out.println(name);
    return ok();
}

此卷曲请求有效:

curl -X POST -H "content-type: application/x-www-form-urlencoded" -d "name=tom" http://localhost:8080/sampleapp/hello

以下请求改为name参数为null

curl -X POST -H "content-type: application/x-www-form-urlencoded; charset=UTF-8" -d "name=tom" http://localhost:8080/sampleapp/hello

我认为内容类型中的charset=UTF-8添加会破坏我的代码。

修改

我已经打开了官方机票,以防这是一个错误:https://java.net/jira/browse/JERSEY-1978

2 个答案:

答案 0 :(得分:7)

我认为这是一个错误。

有一个拉取请求可以支持这个用例: https://github.com/jersey/jersey/pull/24/files

与此同时,我建议使用过滤器来删除有问题的编码。

根据OP评论

编辑

我正在思考这些问题:

@Provider
@PreMatching
public class ContentTypeFilter implements ContainerRequestFilter{

    @Override
    public void filter(ContainerRequestContext requestContext)
            throws IOException {
        MultivaluedMap<String,String> headers=requestContext.getHeaders();
        List<String> contentTypes=headers.remove(HttpHeaders.CONTENT_TYPE);
        if (contentTypes!=null && !contentTypes.isEmpty()){
            String contentType= contentTypes.get(0);
            String sanitizedContentType=contentType.replaceFirst(";.*", "");
            headers.add(HttpHeaders.CONTENT_TYPE, sanitizedContentType);
        }
    }
}

答案 1 :(得分:4)

这是一个简单的解决方案,灵感来自Carlo的帖子。唯一的修改是匹配';字符集= UTF-8' ;否则,'multipart / form-data; boundary = ...'内容类型失败。

// IMPLEMENTATION NOTE: Resolves an issue with FormParam processing
// @see https://java.net/jira/browse/JERSEY-1978

@Provider
@PreMatching
public class ContentTypeFilter implements ContainerRequestFilter {

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        MultivaluedMap<String,String> headers = requestContext.getHeaders();
        List<String> contentTypes = headers.remove(HttpHeaders.CONTENT_TYPE);
        if (contentTypes != null && !contentTypes.isEmpty()) {
            String contentType = contentTypes.get(0);
            String sanitizedContentType = contentType.replaceFirst("; charset=UTF-8", "");
            headers.add(HttpHeaders.CONTENT_TYPE, sanitizedContentType);
        }
    }
}