2015-09-28 82 views
1

我有JAX-RS REST API,我需要加密添加到的答覆,所以我加入一個Servlet過濾器:JAX-RS和Servlet過濾器:IllegalStateException異常:響應已承諾

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過濾器有什麼問題嗎?有沒有辦法保留髮送回復?

謝謝。

+0

什麼JAX-RS的實現和版本您使用的是什麼? –

回答

1

JAX-RS適用於servlet過濾器。檢查是否有任何其他過濾器已提交響應。

[更新]如果你使用的球衣,檢查Jersey's Docs

的ContainerResponseFilter。

[更新2]的例子: Filter類,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

+0

我沒有任何其他過濾器:( –