2011-05-17

And Yet They Complain

Compare and contrast. PHP:

<?php
$body = @file_get_contents("php://input");
header('Content-type: text/plain');
print $body;
flush();
?>

Java:

import java.io.IOException;
import java.io.Reader;
import java.io.Writer;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/reflect")
public class ReflectorServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;
       
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    dump(request, response);
  }

  protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    dump(request, response);
  }

  private void dump(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    response.setContentType("text/plain");
    response.setCharacterEncoding(request.getCharacterEncoding());
    final Reader reader = request.getReader();
    final Writer writer = response.getWriter();
    final StringBuilder builder = new StringBuilder();
    final char[] buffer = new char[1024];
    int nread;
    while ( (nread = reader.read(buffer, 0, buffer.length)) >= 0 )
      builder.append(buffer, 0, nread);
    final String contents = builder.toString();
    response.setContentLength(contents.length());
    writer.write(contents);
    response.flushBuffer();
    reader.close();
    writer.close();
  }
}

Granted, the Java version does one thing the PHP one doesn't (can you spot it?).

Sometimes the end does justify the means.

2 comments:

Anonymous said...

Besides reflecting the character encoding back, the Java version does some routing. I like the @WebServlet(url) annotation at least.

grant rettke said...

LOL there must be a worse version than Java!