Jax-rs和servlet过滤器:IllegalStateException:响应已提交

时间:2015-09-28 20:57:00

标签: java web-services jax-rs

我有使用JAX-RS的REST API,我需要在响应中添加加密,所以我添加了一个servlet过滤器:

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {

    ServletRequestWrapper request = new ServletRequestWrapper((HttpServletRequest) servletRequest);
    ServletResponseWrapper response = new ServletResponseWrapper((HttpServletResponse) servletResponse);
    PrintWriter out = response.getWriter();

    filterChain.doFilter(request, response);

    response.getResponse().resetBuffer();
    String servletResponseString = response.toString();
    out.write("Hola"); // Here you can change the response
    out.flush();
    out.close();

    logger.info("AFTER filter, original response: "
            + servletResponseString);
}

但我得到java.lang.IllegalStateException: Response already committed

使用JAX-RS和servlet过滤器有什么问题吗?有没有办法保留发送的响应?

感谢。

1 个答案:

答案 0 :(得分:1)

JAX-RS适用于servlet过滤器。检查您所拥有的任何其他过滤器是否已提交响应。

[更新]如果您使用的是Jersey,请检查Jersey's Docs

用于ContainerResponseFilter。

[更新2]一个例子: 过滤类,JerseyTestFilter.java:

package jersey.example;
import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.container.ContainerResponse;
import com.sun.jersey.spi.container.ContainerResponseFilter;

public class JerseyTestFilter implements ContainerResponseFilter {
@Override 
    public ContainerResponse filter(ContainerRequest request, ContainerResponse response) {
       String resp = (String) response.getEntity();
       resp += " - filter applied";
      response.setEntity(resp);
      return response;
    }
}

它假定响应主体是一个字符串并对其进行修改。

现在转到<servlet>内的web.xml:

<init-param>
    <param-name>com.sun.jersey.spi.container.ContainerResponseFilters</param-name>
    <param-value>jersey.example.JerseyTestFilter</param-value>
</init-param>

以下是working exmaple