当前位置:   article > 正文

HttpServletRequestWrapper、HttpServletResponseWrapper结合 过滤器 实现接口的加解密、国际化

servletrequestwrapper

目录

一、HttpServletRequestWrapper代码

二、HttpServletRequestWrapper代码

三、加解密过滤器代码

四、国际化过滤器代码


一、HttpServletRequestWrapper代码

  1. package com.vteam.uap.security.httpWrapper;
  2. import jakarta.servlet.ReadListener;
  3. import jakarta.servlet.ServletInputStream;
  4. import jakarta.servlet.http.HttpServletRequest;
  5. import jakarta.servlet.http.HttpServletRequestWrapper;
  6. import java.io.BufferedInputStream;
  7. import java.io.ByteArrayInputStream;
  8. import java.io.ByteArrayOutputStream;
  9. import java.io.IOException;
  10. /**
  11. * @author Miller.Lai
  12. * @description: 请求装饰器
  13. * @date 2023-12-18 11:09:46
  14. */
  15. public class RequestWrapper extends HttpServletRequestWrapper {
  16. private byte[] bytes;
  17. private HttpServletRequest request;
  18. /**
  19. * @param request
  20. */
  21. public RequestWrapper(HttpServletRequest request) {
  22. super(request);
  23. this.request = request;
  24. }
  25. public String getRequestBody() throws IOException {
  26. try (BufferedInputStream bis = new BufferedInputStream(request.getInputStream());
  27. ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
  28. byte[] buffer = new byte[1024];
  29. int len;
  30. while ((len = bis.read(buffer)) > 0) {
  31. baos.write(buffer, 0, len);
  32. }
  33. bytes = baos.toByteArray();
  34. String body = new String(bytes);
  35. return body;
  36. } catch (IOException ex) {
  37. throw ex;
  38. }
  39. }
  40. public void setRequestBody(String body){
  41. bytes = body.getBytes();
  42. }
  43. public ServletInputStream getInputStream() throws IOException {
  44. final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
  45. return new ServletInputStream() {
  46. @Override
  47. public boolean isFinished() {
  48. return false;
  49. }
  50. @Override
  51. public boolean isReady() {
  52. return false;
  53. }
  54. @Override
  55. public void setReadListener(ReadListener readListener) {
  56. }
  57. @Override
  58. public int read() throws IOException {
  59. return byteArrayInputStream.read();
  60. }
  61. };
  62. }
  63. }

二、HttpServletRequestWrapper代码

  1. package com.vteam.uap.security.httpWrapper;
  2. import jakarta.servlet.ServletOutputStream;
  3. import jakarta.servlet.WriteListener;
  4. import jakarta.servlet.http.HttpServletResponse;
  5. import jakarta.servlet.http.HttpServletResponseWrapper;
  6. import java.io.*;
  7. /**
  8. * @author Miller.Lai
  9. * @description: 响应装饰器
  10. * @date 2023-12-15 13:29:16
  11. */
  12. public class ResponseWrapper extends HttpServletResponseWrapper {
  13. private ByteArrayOutputStream outputStream;
  14. public byte[] getResponseData(){
  15. try {
  16. outputStream.flush();
  17. } catch (IOException e) {
  18. e.printStackTrace();
  19. }
  20. return outputStream.toByteArray();
  21. }
  22. public ResponseWrapper(HttpServletResponse response) {
  23. super(response);
  24. this.outputStream =new ByteArrayOutputStream();
  25. }
  26. @Override
  27. public PrintWriter getWriter() throws IOException {
  28. return new PrintWriter(outputStream);
  29. }
  30. @Override
  31. public ServletOutputStream getOutputStream() throws IOException {
  32. return new ServletOutputStream() {
  33. @Override
  34. public boolean isReady() {
  35. return false;
  36. }
  37. @Override
  38. public void setWriteListener(WriteListener listener) {
  39. }
  40. @Override
  41. public void write(int b) throws IOException {
  42. outputStream.write(b);
  43. }
  44. };
  45. }
  46. }

三、加解密过滤器代码

  1. package com.vteam.uap.core.filter;
  2. import com.alibaba.fastjson2.JSON;
  3. import com.alibaba.fastjson2.JSONObject;
  4. import com.vteam.uap.common.util.*;
  5. import com.vteam.uap.security.codec.CodecProperties;
  6. import com.vteam.uap.security.httpWrapper.RequestWrapper;
  7. import com.vteam.uap.security.httpWrapper.ResponseWrapper;
  8. import jakarta.annotation.Resource;
  9. import jakarta.servlet.Filter;
  10. import jakarta.servlet.*;
  11. import jakarta.servlet.http.HttpServletRequest;
  12. import jakarta.servlet.http.HttpServletResponse;
  13. import lombok.extern.slf4j.Slf4j;
  14. import org.apache.commons.lang3.ArrayUtils;
  15. import org.springframework.util.PatternMatchUtils;
  16. import org.springframework.web.context.request.RequestContextHolder;
  17. import org.springframework.web.context.request.ServletRequestAttributes;
  18. import java.io.IOException;
  19. import java.util.Objects;
  20. /**
  21. * @author Miller.Lai
  22. * @description: 加解码过滤器
  23. * @date 2023-12-15 16:46:03
  24. */
  25. @Slf4j
  26. public class CodecFilter implements Filter {
  27. @Resource
  28. protected CodecProperties codecProperties;
  29. @Override
  30. public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
  31. // 请求解密
  32. if (codecProperties.isApiEnable() && !isIgnore() && ("POST".equals(((HttpServletRequest)request).getMethod().trim().toUpperCase())) && "application/json".equals(request.getContentType().trim().toLowerCase())){
  33. RequestWrapper requestWrapper = new RequestWrapper((HttpServletRequest) request);
  34. String bodyStr = requestWrapper.getRequestBody();
  35. if(StringUtils.isNotBlank(bodyStr)){
  36. JSONObject bodyJson = JSONObject.parseObject(bodyStr);
  37. Object data = bodyJson.get("data");
  38. if(data != null && data instanceof String && ((String)data).trim().length () !=0 ){
  39. if (log.isDebugEnabled()) {
  40. log.debug("解密 API 请求消息:type={}, requestBody={}",requestWrapper.getMethod(), bodyJson.toJSONString());
  41. }
  42. String plainText = AesUtils.decrypt((String) data, AesUtils.Mode.API,codecProperties.getAesKey(),codecProperties.getAesIv(),codecProperties.isDbEnable());
  43. bodyJson.put("data",JSONObject.parseObject(plainText));
  44. requestWrapper.setRequestBody(bodyJson.toJSONString());
  45. }
  46. }
  47. // 包装响应对象
  48. ResponseWrapper responseWrapper = new ResponseWrapper((HttpServletResponse) response);
  49. chain.doFilter(requestWrapper, responseWrapper);
  50. // 拿到响应对象
  51. byte[] responseData = responseWrapper.getResponseData();
  52. if("application/json".equals(responseWrapper.getContentType().trim().toLowerCase())){
  53. String originalResulet = new String(responseData);
  54. JSONObject jsonObject =JSONObject.parseObject(originalResulet);
  55. // 拿到响应对象中的data
  56. Object data = jsonObject.get("data");
  57. if(data != null){
  58. String encText = AesUtils.encrypt(JSON.toJSONString(data), AesUtils.Mode.API,codecProperties.getAesKey(),codecProperties.getAesIv(),codecProperties.isDbEnable());
  59. jsonObject.put("data", encText);
  60. }
  61. responseData = jsonObject.toJSONString().getBytes("utf-8");
  62. }
  63. HttpServletResponse httpServletResponse = (HttpServletResponse) response;
  64. response.setContentLength(responseData.length);
  65. httpServletResponse.getOutputStream().write(responseData);
  66. httpServletResponse.getOutputStream().flush();
  67. }else{
  68. // 处理业务逻辑
  69. chain.doFilter(request, response);
  70. }
  71. }
  72. @Override
  73. public void destroy() {
  74. }
  75. protected boolean isIgnore() {
  76. boolean isIgnore = false;
  77. String[] ignoreUrl = codecProperties.getIgnoreUrl();
  78. if (ArrayUtils.isNotEmpty(ignoreUrl)) {
  79. HttpServletRequest request =
  80. ((ServletRequestAttributes) Objects.requireNonNull(
  81. RequestContextHolder.getRequestAttributes())).getRequest();
  82. for (String s : ignoreUrl) {
  83. if (PatternMatchUtils.simpleMatch(s, request.getRequestURI())) {
  84. isIgnore = true;
  85. break;
  86. }
  87. }
  88. }
  89. return isIgnore;
  90. }
  91. }

四、国际化过滤器代码

  1. package com.vteam.uap.core.filter;
  2. import com.alibaba.fastjson2.JSONObject;
  3. import com.vteam.uap.common.constant.CommonConstants;
  4. import com.vteam.uap.common.util.GlobalConstants;
  5. import com.vteam.uap.common.util.I18NUtils;
  6. import com.vteam.uap.common.util.StringUtils;
  7. import com.vteam.uap.common.util.UuidUtil;
  8. import com.vteam.uap.security.httpWrapper.ResponseWrapper;
  9. import jakarta.servlet.*;
  10. import jakarta.servlet.Filter;
  11. import jakarta.servlet.http.HttpServletRequest;
  12. import jakarta.servlet.http.HttpServletResponse;
  13. import lombok.extern.slf4j.Slf4j;
  14. import org.apache.commons.lang3.ArrayUtils;
  15. import org.slf4j.MDC;
  16. import org.springframework.beans.factory.annotation.Value;
  17. import org.springframework.util.PatternMatchUtils;
  18. import org.springframework.web.context.request.RequestContextHolder;
  19. import org.springframework.web.context.request.ServletRequestAttributes;
  20. import java.io.IOException;
  21. import java.util.Objects;
  22. /**
  23. * @author Miller.Lai
  24. * @description:
  25. * @date 2023-12-15 16:46:03
  26. */
  27. @Slf4j
  28. public class I18NFilter implements Filter {
  29. @Value("${uap.i18n.enable:false}")
  30. private boolean i18nEnable;
  31. @Value("${uap.i18n.language:zh_CN}")
  32. private String language;
  33. @Value("${uap.i18n.ignore-url:/doc.html,/webjars/**,/v3/api-docs/**,/actuator**,/favicon.ico}")
  34. private String ignoreUrl;
  35. @Value("${uap.response.msg.include-request-id:false}")
  36. private boolean msgIncludeRequestId;
  37. public I18NFilter() {
  38. }
  39. @Override
  40. public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
  41. // 如果开启了国际化则进行国际化处理
  42. if (i18nEnable && !isIgnore()) {
  43. // 包装响应对象
  44. ResponseWrapper customResponseWrapper = new ResponseWrapper((HttpServletResponse) response);
  45. // 处理业务逻辑
  46. chain.doFilter(request, customResponseWrapper);
  47. // 拿到响应对象
  48. byte[] responseData = customResponseWrapper.getResponseData();
  49. if("application/json".equals(customResponseWrapper.getContentType().trim().toLowerCase())){
  50. String originalResulet = new String(responseData);
  51. JSONObject jsonObject =JSONObject.parseObject(originalResulet);
  52. // 拿到响应对象中的msg
  53. String msg = (String)jsonObject.get("msg");
  54. String i18nMsg = null;
  55. if ( StringUtils.isNotBlank(msg) ) {
  56. HttpServletRequest httpServletRequest = (HttpServletRequest) request;
  57. String languageInheader = httpServletRequest.getHeader("Language");
  58. // 优先使用请求头里的国际化语言
  59. if (languageInheader != null) {
  60. i18nMsg = I18NUtils.getI18N(msg, languageInheader);
  61. } else {
  62. i18nMsg = I18NUtils.getI18N(msg, language);
  63. }
  64. }else if( StringUtils.isNotBlank(msg) ){// 不进行国际化也要清除相关缓存
  65. I18NUtils.getActualContainBraceMsgParamMap().remove(msg+GlobalConstants.Symbol.UNDERLINE+Thread.currentThread().getId());
  66. I18NUtils.getActualContainBraceMsgMap().remove(msg+GlobalConstants.Symbol.UNDERLINE+Thread.currentThread().getId());
  67. }
  68. if(i18nMsg != null ){
  69. msg = i18nMsg;
  70. }
  71. if(msg == null){
  72. msg = "";
  73. }
  74. // 如果线程号不存在,则进行设置
  75. if(StringUtils.isEmpty(MDC.get("UUID"))){
  76. MDC.put("UUID", UuidUtil.getShortUuid());
  77. }
  78. // msg中携带请求id返回
  79. if(msgIncludeRequestId ){
  80. msg = MDC.get("UUID") + GlobalConstants.Symbol.SPACE + msg ;
  81. }
  82. jsonObject.put("msg", msg);
  83. responseData = jsonObject.toJSONString().getBytes("utf-8");
  84. }
  85. HttpServletResponse httpServletResponse = (HttpServletResponse) response;
  86. response.setContentLength(responseData.length);
  87. httpServletResponse.getOutputStream().write(responseData);
  88. httpServletResponse.getOutputStream().flush();
  89. }else{
  90. // 处理业务逻辑
  91. chain.doFilter(request, response);
  92. }
  93. }
  94. @Override
  95. public void destroy() {
  96. }
  97. protected boolean isIgnore() {
  98. boolean isIgnore = false;
  99. if(StringUtils.isEmpty(ignoreUrl)){
  100. return false;
  101. }
  102. String[] ignoreUrls = ignoreUrl.split(CommonConstants.Symbol.COMMA);
  103. if (ArrayUtils.isNotEmpty(ignoreUrls)) {
  104. HttpServletRequest request =
  105. ((ServletRequestAttributes) Objects.requireNonNull(
  106. RequestContextHolder.getRequestAttributes())).getRequest();
  107. for (String s : ignoreUrls) {
  108. if (PatternMatchUtils.simpleMatch(s, request.getRequestURI())) {
  109. isIgnore = true;
  110. break;
  111. }
  112. }
  113. }
  114. return isIgnore;
  115. }
  116. }

五、过滤器注册

  1. /**
  2. * 国际化过滤器
  3. * @return
  4. */
  5. @Bean
  6. public I18NFilter i18NFilter() {
  7. return new I18NFilter();
  8. }
  9. @Bean
  10. public FilterRegistrationBean i18NFilterRegistrationBean() {
  11. // 新建过滤器注册类
  12. FilterRegistrationBean registration = new FilterRegistrationBean();
  13. // 添加自定义 过滤器
  14. registration.setFilter(i18NFilter());
  15. // 设置过滤器的URL模式
  16. registration.addUrlPatterns("/*");
  17. //设置过滤器顺序
  18. registration.setOrder(4);
  19. return registration;
  20. }
  21. /**
  22. * 请求加解密过滤器
  23. * @return
  24. */
  25. @Bean
  26. public CodecFilter codecFilter() {
  27. return new CodecFilter();
  28. }
  29. @Bean
  30. public FilterRegistrationBean codecFilterRegistrationBean() {
  31. // 新建过滤器注册类
  32. FilterRegistrationBean registration = new FilterRegistrationBean();
  33. // 添加自定义 过滤器
  34. registration.setFilter(codecFilter());
  35. // 设置过滤器的URL模式
  36. registration.addUrlPatterns("/*");
  37. //设置过滤器顺序
  38. registration.setOrder(3);
  39. return registration;
  40. }

      本人近十年JAVA架构设计经验,长期从事IT技术资源整合。有志于自我技术提升、需要最新IT技术课程的小伙伴,可私信联系我 ,粉丝一律友情价

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/589165
推荐阅读
相关标签
  

闽ICP备14008679号