在JAX-RS中验证PUT的空体请求,POST方法

时间:2014-01-21 11:14:52

标签: java rest java-ee jax-rs resteasy

我很好奇JAX-RS中是否有注释/过滤器/拦截器功能来检测PUT或POST方法是否包含空体。

目前我有方法,如果请求有空体,可能会抛出NPE。

@PUT
@Produces("application/json")
@Consumes("application/json")
@Path("/update/{id}")
public Response updateCustomer(@PathParam("id") final String customerIdStr, final CustomerJson customer) {
    // if request body is empty -> customer == null
    return Response.ok().build();
}

我可以检查customer null 。但由于我有很多这样的方法,最好让过滤器进行这样的验证。

请!

2 个答案:

答案 0 :(得分:1)

您是否尝试在@NotNull方法参数上使用CustomerJson注释来使用Bean验证?

答案 1 :(得分:1)

拦截器读取HTTP主体,我找不到发送主体进行进一步处理的方法。但是你可以通过Servlet Filter和HTTP servlet请求包装器

来做到这一点
public class EmptyCheckFilter implements javax.servlet.Filter {

  @Override
  public void doFilter(ServletRequest request, ServletResponse response,
      FilterChain chain) throws IOException, ServletException {

    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;

    if (req.getMethod().equals("POST") || req.getMethod().equals("PUT")) {
      boolean dirty = false;
      HttpRequestWrapper wrapper = new MyHTTPRequestWrapper(req);
      try {
    // check body is empty by wrapper.getBody() and set dirty = true;
      } catch (Exception e) {
      }
      if (dirty) {
        res.sendError(400, "Invalid input");
      } else
        chain.doFilter(wrapper, response);
    } else
      chain.doFilter(request, response);
  }

  @Override
  public void destroy() {
  }

  @Override
  public void init(FilterConfig arg0) throws ServletException {
  }
}

public class MyHTTPRequestWrapper extends HttpServletRequestWrapper {

  private final String body;

  public MyHTTPRequestWrapper(HttpServletRequest request) throws IOException {
    super(request);
    StringBuilder stringBuilder = new StringBuilder();
    BufferedReader bufferedReader = null;
    try {
      InputStream inputStream = request.getInputStream();
      if (inputStream != null) {
        if (request.getCharacterEncoding() != null)
        bufferedReader = new BufferedReader(new InputStreamReader(inputStream, request.getCharacterEncoding()));
        else
          bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        char[] charBuffer = new char[128];
        int bytesRead = -1;
        while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
          stringBuilder.append(charBuffer, 0, bytesRead);
        }
      } else {
        stringBuilder.append("");
      }
    } catch (IOException ex) {
      throw ex;
    } finally {
      if (bufferedReader != null) {
        try {
          bufferedReader.close();
        } catch (IOException ex) {
          throw ex;
        }
      }
    }
    body = stringBuilder.toString();
  }

  @Override
  public ServletInputStream getInputStream() throws IOException {
    final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
        body.getBytes());
    ServletInputStream servletInputStream = new ServletInputStream() {
      public int read() throws IOException {
        return byteArrayInputStream.read();
      }
    };
    return servletInputStream;
  }

  @Override
  public BufferedReader getReader() throws IOException {
    return new BufferedReader(new InputStreamReader(this.getInputStream()));
  }

  public String getBody() {
    return this.body;
  }
}