MetaCubeHttpServletRequestWrapper.java 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package com.primeton.dgs.kernel.core.web;
  2. import javax.servlet.http.HttpServletRequest;
  3. import javax.servlet.http.HttpServletRequestWrapper;
  4. import java.util.Collections;
  5. import java.util.Enumeration;
  6. import java.util.HashMap;
  7. import java.util.HashSet;
  8. import java.util.Map;
  9. import java.util.Set;
  10. /**
  11. *
  12. * 元数据旧架构支持 RESTFull API 扩展
  13. *
  14. *
  15. * <pre>
  16. *
  17. * Created by zhaopx.
  18. * User: zhaopx
  19. * Date: 2020/9/10
  20. * Time: 14:24
  21. *
  22. * </pre>
  23. *
  24. * @author zhaopx
  25. */
  26. public class MetaCubeHttpServletRequestWrapper extends HttpServletRequestWrapper {
  27. /**
  28. * 元数据部分参数是从 payload 获得的,装饰 RestFull API
  29. */
  30. protected final Map<String, Object> payloadParameters = new HashMap<>();
  31. /**
  32. * Constructs a request object wrapping the given request.
  33. *
  34. * @param request the {@link HttpServletRequest} to be wrapped.
  35. * @throws IllegalArgumentException if the request is null
  36. */
  37. public MetaCubeHttpServletRequestWrapper(HttpServletRequest request) {
  38. super(request);
  39. }
  40. public MetaCubeHttpServletRequestWrapper(HttpServletRequest request, Map<String, Object> payloadParameters) {
  41. super(request);
  42. this.payloadParameters.putAll(payloadParameters);
  43. }
  44. @Override
  45. public String getParameter(String name) {
  46. String parameter = super.getParameter(name);
  47. // 获取参数,如果 form 中为空,则从 payload 中获取
  48. return parameter == null ? (String)payloadParameters.get(name) : parameter;
  49. }
  50. @Override
  51. public String[] getParameterValues(String name) {
  52. String[] parameterValues = super.getParameterValues(name);
  53. // 获取参数,如果 form 中为空,则从 payload 中获取
  54. return parameterValues == null ? new String[]{ (String)payloadParameters.get(name)} : parameterValues;
  55. }
  56. @Override
  57. public Map<String, String[]> getParameterMap() {
  58. Map<String, String[]> parameterMap = new HashMap<>(super.getParameterMap());
  59. // 合并参数
  60. for (Map.Entry<String, Object> entry : payloadParameters.entrySet()) {
  61. parameterMap.put(entry.getKey(), new String[]{ (String)entry.getValue()});
  62. }
  63. return parameterMap;
  64. }
  65. @Override
  66. public Enumeration<String> getParameterNames() {
  67. Set<String> vector = new HashSet();
  68. // form 参数
  69. Enumeration<String> parameterNames = super.getParameterNames();
  70. while (parameterNames.hasMoreElements()) {
  71. vector.add(parameterNames.nextElement());
  72. }
  73. // payload 参数
  74. for (String s : payloadParameters.keySet()) {
  75. vector.add(s);
  76. }
  77. // 构造一次性返回
  78. return Collections.enumeration(vector);
  79. }
  80. }