修改请求

Filter可以对请求进行预处理,因此,我们可以把很多公共预处理逻辑放到Filter中完成。

考察这样一种需求:我们在Web应用中经常需要处理用户上传文件,例如,一个UploadServlet可以简单地编写如下:

  1. @WebServlet(urlPatterns = "/upload/file")
  2. public class UploadServlet extends HttpServlet {
  3. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  4. // 读取Request Body:
  5. InputStream input = req.getInputStream();
  6. ByteArrayOutputStream output = new ByteArrayOutputStream();
  7. byte[] buffer = new byte[1024];
  8. for (;;) {
  9. int len = input.read(buffer);
  10. if (len == -1) {
  11. break;
  12. }
  13. output.write(buffer, 0, len);
  14. }
  15. // TODO: 写入文件:
  16. // 显示上传结果:
  17. String uploadedText = output.toString(StandardCharsets.UTF_8);
  18. PrintWriter pw = resp.getWriter();
  19. pw.write("<h1>Uploaded:</h1>");
  20. pw.write("<pre><code>");
  21. pw.write(uploadedText);
  22. pw.write("</code></pre>");
  23. pw.flush();
  24. }
  25. }

但是要保证文件上传的完整性怎么办?在哈希算法一节中,我们知道,如果在上传文件的同时,把文件的哈希也传过来,服务器端做一个验证,就可以确保用户上传的文件一定是完整的。

这个验证逻辑非常适合写在ValidateUploadFilter中,因为它可以复用。

我们先写一个简单的版本,快速实现ValidateUploadFilter的逻辑:

  1. @WebFilter("/upload/*")
  2. public class ValidateUploadFilter implements Filter {
  3. @Override
  4. public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
  5. throws IOException, ServletException {
  6. HttpServletRequest req = (HttpServletRequest) request;
  7. HttpServletResponse resp = (HttpServletResponse) response;
  8. // 获取客户端传入的签名方法和签名:
  9. String digest = req.getHeader("Signature-Method");
  10. String signature = req.getHeader("Signature");
  11. if (digest == null || digest.isEmpty() || signature == null || signature.isEmpty()) {
  12. sendErrorPage(resp, "Missing signature.");
  13. return;
  14. }
  15. // 读取Request的Body并验证签名:
  16. MessageDigest md = getMessageDigest(digest);
  17. InputStream input = new DigestInputStream(request.getInputStream(), md);
  18. byte[] buffer = new byte[1024];
  19. for (;;) {
  20. int len = input.read(buffer);
  21. if (len == -1) {
  22. break;
  23. }
  24. }
  25. String actual = toHexString(md.digest());
  26. if (!signature.equals(actual)) {
  27. sendErrorPage(resp, "Invalid signature.");
  28. return;
  29. }
  30. // 验证成功后继续处理:
  31. chain.doFilter(request, response);
  32. }
  33. // 将byte[]转换为hex string:
  34. private String toHexString(byte[] digest) {
  35. StringBuilder sb = new StringBuilder();
  36. for (byte b : digest) {
  37. sb.append(String.format("%02x", b));
  38. }
  39. return sb.toString();
  40. }
  41. // 根据名称创建MessageDigest:
  42. private MessageDigest getMessageDigest(String name) throws ServletException {
  43. try {
  44. return MessageDigest.getInstance(name);
  45. } catch (NoSuchAlgorithmException e) {
  46. throw new ServletException(e);
  47. }
  48. }
  49. // 发送一个错误响应:
  50. private void sendErrorPage(HttpServletResponse resp, String errorMessage) throws IOException {
  51. resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
  52. PrintWriter pw = resp.getWriter();
  53. pw.write("<html><body><h1>");
  54. pw.write(errorMessage);
  55. pw.write("</h1></body></html>");
  56. pw.flush();
  57. }
  58. }

这个ValidateUploadFilter的逻辑似乎没有问题,我们可以用curl命令测试:

  1. $ curl http://localhost:8080/upload/file -v -d 'test-data' \
  2. -H 'Signature-Method: SHA-1' \
  3. -H 'Signature: 7115e9890f5b5cc6914bdfa3b7c011db1cdafedb' \
  4. -H 'Content-Type: application/octet-stream'
  5. * Trying ::1...
  6. * TCP_NODELAY set
  7. * Connected to localhost (::1) port 8080 (#0)
  8. > POST /upload/file HTTP/1.1
  9. > Host: localhost:8080
  10. > User-Agent: curl/7.64.1
  11. > Accept: */*
  12. > Signature-Method: SHA-1
  13. > Signature: 7115e9890f5b5cc6914bdfa3b7c011db1cdafedb
  14. > Content-Type: application/octet-stream
  15. > Content-Length: 9
  16. >
  17. * upload completely sent off: 9 out of 9 bytes
  18. < HTTP/1.1 200
  19. < Transfer-Encoding: chunked
  20. < Date: Thu, 30 Jan 2020 13:56:39 GMT
  21. <
  22. * Connection #0 to host localhost left intact
  23. <h1>Uploaded:</h1><pre><code></code></pre>
  24. * Closing connection 0

ValidateUploadFilter对签名进行验证的逻辑是没有问题的,但是,细心的童鞋注意到,UploadServlet并未读取到任何数据!

这里的原因是对HttpServletRequest进行读取时,只能读取一次。如果Filter调用getInputStream()读取了一次数据,后续Servlet处理时,再次读取,将无法读到任何数据。怎么办?

这个时候,我们需要一个“伪造”的HttpServletRequest,具体做法是使用代理模式,对getInputStream()getReader()返回一个新的流:

  1. class ReReadableHttpServletRequest extends HttpServletRequestWrapper {
  2. private byte[] body;
  3. private boolean open = false;
  4. public ReReadableHttpServletRequest(HttpServletRequest request, byte[] body) {
  5. super(request);
  6. this.body = body;
  7. }
  8. // 返回InputStream:
  9. public ServletInputStream getInputStream() throws IOException {
  10. if (open) {
  11. throw new IllegalStateException("Cannot re-open input stream!");
  12. }
  13. open = true;
  14. return new ServletInputStream() {
  15. private int offset = 0;
  16. public boolean isFinished() {
  17. return offset >= body.length;
  18. }
  19. public boolean isReady() {
  20. return true;
  21. }
  22. public void setReadListener(ReadListener listener) {
  23. }
  24. public int read() throws IOException {
  25. if (offset >= body.length) {
  26. return -1;
  27. }
  28. int n = body[offset];
  29. offset++;
  30. return n;
  31. }
  32. };
  33. }
  34. // 返回Reader:
  35. public BufferedReader getReader() throws IOException {
  36. if (open) {
  37. throw new IllegalStateException("Cannot re-open reader!");
  38. }
  39. open = true;
  40. return new BufferedReader(new InputStreamReader(getInputStream(), "UTF-8"));
  41. }
  42. }

注意观察ReReadableHttpServletRequest的构造方法,它保存了ValidateUploadFilter读取的byte[]内容,并在调用getInputStream()时通过byte[]构造了一个新的ServletInputStream

然后,我们在ValidateUploadFilter中,把doFilter()调用时传给下一个处理者的HttpServletRequest替换为我们自己“伪造”的ReReadableHttpServletRequest

  1. public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
  2. throws IOException, ServletException {
  3. ...
  4. chain.doFilter(new ReReadableHttpServletRequest(req, output.toByteArray()), response);
  5. }

再注意到我们编写ReReadableHttpServletRequest时,是从HttpServletRequestWrapper继承,而不是直接实现HttpServletRequest接口。这是因为,Servlet的每个新版本都会对接口增加一些新方法,从HttpServletRequestWrapper继承可以确保新方法被正确地覆写了,因为HttpServletRequestWrapper是由Servlet的jar包提供的,目的就是为了让我们方便地实现对HttpServletRequest接口的代理。

我们总结一下对HttpServletRequest接口进行代理的步骤:

  • HttpServletRequestWrapper继承一个XxxHttpServletRequest,需要传入原始的HttpServletRequest实例;
  • 覆写某些方法,使得新的XxxHttpServletRequest实例看上去“改变”了原始的HttpServletRequest实例;
  • doFilter()中传入新的XxxHttpServletRequest实例。 虽然整个Filter的代码比较复杂,但它的好处在于:这个Filter在整个处理链中实现了灵活的“可插拔”特性,即是否启用对Web应用程序的其他组件(Filter、Servlet)完全没有影响。

练习

修改请求 - 图1下载练习:使用Filter修改请求 (推荐使用IDE练习插件快速下载)

小结

借助HttpServletRequestWrapper,我们可以在Filter中实现对原始HttpServletRequest的修改。

读后有收获可以支付宝请作者喝咖啡,读后有疑问请加微信群讨论:

修改请求 - 图2 修改请求 - 图3