HttpServletRequestWrapper、HttpServletResponseWrapper結合 過濾器 實現接口的加解密、國際化

目錄

一、HttpServletRequestWrapper代碼

二、HttpServletRequestWrapper代碼

三、加解密過濾器代碼

四、國際化過濾器代碼


一、HttpServletRequestWrapper代碼

package com.vteam.uap.security.httpWrapper;import jakarta.servlet.ReadListener;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;/*** @author Miller.Lai* @description: 請求裝飾器* @date 2023-12-18 11:09:46*/
public class RequestWrapper extends HttpServletRequestWrapper {private byte[] bytes;private HttpServletRequest request;/*** @param request*/public RequestWrapper(HttpServletRequest request) {super(request);this.request = request;}public String getRequestBody() throws IOException {try (BufferedInputStream bis = new BufferedInputStream(request.getInputStream());ByteArrayOutputStream baos = new ByteArrayOutputStream()) {byte[] buffer = new byte[1024];int len;while ((len = bis.read(buffer)) > 0) {baos.write(buffer, 0, len);}bytes = baos.toByteArray();String body = new String(bytes);return body;} catch (IOException ex) {throw ex;}}public void setRequestBody(String body){bytes = body.getBytes();}public ServletInputStream getInputStream() throws IOException {final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);return new ServletInputStream() {@Overridepublic boolean isFinished() {return false;}@Overridepublic boolean isReady() {return false;}@Overridepublic void setReadListener(ReadListener readListener) {}@Overridepublic int read() throws IOException {return byteArrayInputStream.read();}};}}

二、HttpServletRequestWrapper代碼

package com.vteam.uap.security.httpWrapper;import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.WriteListener;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpServletResponseWrapper;import java.io.*;/*** @author Miller.Lai* @description: 響應裝飾器* @date 2023-12-15 13:29:16*/
public class ResponseWrapper extends HttpServletResponseWrapper {private ByteArrayOutputStream outputStream;public byte[] getResponseData(){try {outputStream.flush();} catch (IOException e) {e.printStackTrace();}return outputStream.toByteArray();}public ResponseWrapper(HttpServletResponse response) {super(response);this.outputStream =new ByteArrayOutputStream();}@Overridepublic PrintWriter getWriter() throws IOException {return new PrintWriter(outputStream);}@Overridepublic ServletOutputStream getOutputStream() throws IOException {return new ServletOutputStream() {@Overridepublic boolean isReady() {return false;}@Overridepublic void setWriteListener(WriteListener listener) {}@Overridepublic void write(int b) throws IOException {outputStream.write(b);}};}
}

三、加解密過濾器代碼

package com.vteam.uap.core.filter;import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.vteam.uap.common.util.*;
import com.vteam.uap.security.codec.CodecProperties;
import com.vteam.uap.security.httpWrapper.RequestWrapper;
import com.vteam.uap.security.httpWrapper.ResponseWrapper;
import jakarta.annotation.Resource;
import jakarta.servlet.Filter;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.util.PatternMatchUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;import java.io.IOException;
import java.util.Objects;/*** @author Miller.Lai* @description:  加解碼過濾器* @date 2023-12-15 16:46:03*/
@Slf4j
public class CodecFilter implements Filter {@Resourceprotected CodecProperties codecProperties;@Overridepublic void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {// 請求解密if (codecProperties.isApiEnable() && !isIgnore() && ("POST".equals(((HttpServletRequest)request).getMethod().trim().toUpperCase())) && "application/json".equals(request.getContentType().trim().toLowerCase())){RequestWrapper requestWrapper = new RequestWrapper((HttpServletRequest) request);String bodyStr =  requestWrapper.getRequestBody();if(StringUtils.isNotBlank(bodyStr)){JSONObject bodyJson = JSONObject.parseObject(bodyStr);Object data = bodyJson.get("data");if(data != null && data instanceof String && ((String)data).trim().length () !=0 ){if (log.isDebugEnabled()) {log.debug("解密 API 請求消息:type={}, requestBody={}",requestWrapper.getMethod(), bodyJson.toJSONString());}String plainText = AesUtils.decrypt((String) data, AesUtils.Mode.API,codecProperties.getAesKey(),codecProperties.getAesIv(),codecProperties.isDbEnable());bodyJson.put("data",JSONObject.parseObject(plainText));requestWrapper.setRequestBody(bodyJson.toJSONString());}}// 包裝響應對象ResponseWrapper responseWrapper = new ResponseWrapper((HttpServletResponse) response);chain.doFilter(requestWrapper, responseWrapper);// 拿到響應對象byte[] responseData = responseWrapper.getResponseData();if("application/json".equals(responseWrapper.getContentType().trim().toLowerCase())){String originalResulet = new String(responseData);JSONObject jsonObject  =JSONObject.parseObject(originalResulet);// 拿到響應對象中的dataObject data = jsonObject.get("data");if(data != null){String encText = AesUtils.encrypt(JSON.toJSONString(data), AesUtils.Mode.API,codecProperties.getAesKey(),codecProperties.getAesIv(),codecProperties.isDbEnable());jsonObject.put("data", encText);}responseData = jsonObject.toJSONString().getBytes("utf-8");}HttpServletResponse httpServletResponse = (HttpServletResponse) response;response.setContentLength(responseData.length);httpServletResponse.getOutputStream().write(responseData);httpServletResponse.getOutputStream().flush();}else{// 處理業務邏輯chain.doFilter(request, response);}}@Overridepublic void destroy() {}protected boolean isIgnore() {boolean isIgnore = false;String[] ignoreUrl = codecProperties.getIgnoreUrl();if (ArrayUtils.isNotEmpty(ignoreUrl)) {HttpServletRequest request =((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();for (String s : ignoreUrl) {if (PatternMatchUtils.simpleMatch(s, request.getRequestURI())) {isIgnore = true;break;}}}return isIgnore;}}

四、國際化過濾器代碼

package com.vteam.uap.core.filter;import com.alibaba.fastjson2.JSONObject;
import com.vteam.uap.common.constant.CommonConstants;
import com.vteam.uap.common.util.GlobalConstants;
import com.vteam.uap.common.util.I18NUtils;
import com.vteam.uap.common.util.StringUtils;
import com.vteam.uap.common.util.UuidUtil;
import com.vteam.uap.security.httpWrapper.ResponseWrapper;
import jakarta.servlet.*;
import jakarta.servlet.Filter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.PatternMatchUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;import java.io.IOException;
import java.util.Objects;/*** @author Miller.Lai* @description:* @date 2023-12-15 16:46:03*/
@Slf4j
public class I18NFilter implements Filter {@Value("${uap.i18n.enable:false}")private boolean i18nEnable;@Value("${uap.i18n.language:zh_CN}")private String language;@Value("${uap.i18n.ignore-url:/doc.html,/webjars/**,/v3/api-docs/**,/actuator**,/favicon.ico}")private String ignoreUrl;@Value("${uap.response.msg.include-request-id:false}")private boolean msgIncludeRequestId;public I18NFilter() {}@Overridepublic void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {// 如果開啟了國際化則進行國際化處理if (i18nEnable && !isIgnore()) {// 包裝響應對象ResponseWrapper customResponseWrapper = new ResponseWrapper((HttpServletResponse) response);// 處理業務邏輯chain.doFilter(request, customResponseWrapper);// 拿到響應對象byte[] responseData = customResponseWrapper.getResponseData();if("application/json".equals(customResponseWrapper.getContentType().trim().toLowerCase())){String originalResulet = new String(responseData);JSONObject jsonObject  =JSONObject.parseObject(originalResulet);// 拿到響應對象中的msgString msg = (String)jsonObject.get("msg");String i18nMsg = null;if ( StringUtils.isNotBlank(msg) ) {HttpServletRequest httpServletRequest = (HttpServletRequest) request;String languageInheader = httpServletRequest.getHeader("Language");// 優先使用請求頭里的國際化語言if (languageInheader != null) {i18nMsg = I18NUtils.getI18N(msg, languageInheader);} else {i18nMsg = I18NUtils.getI18N(msg, language);}}else if( StringUtils.isNotBlank(msg) ){// 不進行國際化也要清除相關緩存I18NUtils.getActualContainBraceMsgParamMap().remove(msg+GlobalConstants.Symbol.UNDERLINE+Thread.currentThread().getId());I18NUtils.getActualContainBraceMsgMap().remove(msg+GlobalConstants.Symbol.UNDERLINE+Thread.currentThread().getId());}if(i18nMsg != null ){msg = i18nMsg;}if(msg == null){msg = "";}// 如果線程號不存在,則進行設置if(StringUtils.isEmpty(MDC.get("UUID"))){MDC.put("UUID", UuidUtil.getShortUuid());}// msg中攜帶請求id返回if(msgIncludeRequestId ){msg = MDC.get("UUID") + GlobalConstants.Symbol.SPACE + msg ;}jsonObject.put("msg", msg);responseData =  jsonObject.toJSONString().getBytes("utf-8");}HttpServletResponse httpServletResponse = (HttpServletResponse) response;response.setContentLength(responseData.length);httpServletResponse.getOutputStream().write(responseData);httpServletResponse.getOutputStream().flush();}else{// 處理業務邏輯chain.doFilter(request, response);}}@Overridepublic void destroy() {}protected boolean isIgnore() {boolean isIgnore = false;if(StringUtils.isEmpty(ignoreUrl)){return false;}String[] ignoreUrls = ignoreUrl.split(CommonConstants.Symbol.COMMA);if (ArrayUtils.isNotEmpty(ignoreUrls)) {HttpServletRequest request =((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();for (String s : ignoreUrls) {if (PatternMatchUtils.simpleMatch(s, request.getRequestURI())) {isIgnore = true;break;}}}return isIgnore;}
}

五、過濾器注冊

    /*** 國際化過濾器* @return*/@Beanpublic I18NFilter i18NFilter() {return new I18NFilter();}@Beanpublic FilterRegistrationBean i18NFilterRegistrationBean() {// 新建過濾器注冊類FilterRegistrationBean registration = new FilterRegistrationBean();// 添加自定義 過濾器registration.setFilter(i18NFilter());// 設置過濾器的URL模式registration.addUrlPatterns("/*");//設置過濾器順序registration.setOrder(4);return registration;}/*** 請求加解密過濾器* @return*/@Beanpublic CodecFilter codecFilter() {return new CodecFilter();}@Beanpublic FilterRegistrationBean codecFilterRegistrationBean() {// 新建過濾器注冊類FilterRegistrationBean registration = new FilterRegistrationBean();// 添加自定義 過濾器registration.setFilter(codecFilter());// 設置過濾器的URL模式registration.addUrlPatterns("/*");//設置過濾器順序registration.setOrder(3);return registration;}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/271578.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/271578.shtml
英文地址,請注明出處:http://en.pswp.cn/news/271578.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

razor 寫入html標記,如何在Razor中編寫“ Html.BeginForm”

泛舟湖上清波郎朗以下代碼可以正常工作:using (Html.BeginForm("Upload", "Upload", FormMethod.Post, new { enctype "multipart/form-data" })){ Html.ValidationSummary(true) …

windows安全模式_Winclone 8 for Mac(Windows分區備份遷移和還原工具)

winclone 8 Mac版是一款專業的boot Camp遷移助手,能夠將你的PC移動到你的Mac中,讓你實現win系統的遷移。winclone Mac版可以將Bootcamp分區安裝的windows進行克隆也可將克隆文件傳回Bootcamp分區。并且操作簡單。你只需要通過幾次點擊,就能快…

IDEA中一個被低估的功能,一鍵把項目代碼繪制成UML類圖

閱讀本文大概需要 2 分鐘。來自:blog.csdn.net/hy_coming/article/details/80741717最近在開發的過程當中,對于已有的代碼,想將相關類繪制成UML類圖,雖然現在有很多UML類圖的優秀軟件,比如ProcessOn(可視化…

java導出生成word(類似簡歷導出)

最近做的項目,需要將一些信息導出到word中。在網上找了好多解決方案,現在將這幾天的總結分享一下。 目前來看,java導出word大致有6種解決方案: 1:Jacob是Java-COM Bridge的縮寫,它在Java與微軟的COM組件之間…

計算機基礎:存儲系統知識筆記(一)

1、存儲系統定義 由一個不同容量、成本和訪問時間的存儲結構構成的層次結構,這些存儲器通過適當的硬件和軟件有機的組合在一起。 存儲器的層次:CPU內部的寄存器、高速緩存Cache、主存儲器、輔助存儲器 2、存儲器的分類 2.1 存儲位置分類 內存&#xff1a…

html5和c3屬性,H5與C3不得不說的知識點

1 HTML 5html5包含htm5 css3 javascript1.1 新增語義標簽頭部導航欄塊級內容側邊欄腳部注意:可以多次使用;ie9中需要轉換為塊級元素;針對搜索引擎;針對于移動端;1.2 新增多媒體標簽1.2.1 音頻標簽 audio格式&#xf…

ae繪圖未指定錯誤怎么辦_早晨深化設計研究院47個快捷鍵50個CAD技巧助你神速繪圖,玩轉CAD...

終于知道為什么別人用CAD總比我快了,原來他們早就掌握了這些實用的CAD技巧,還沒看完我就默默地轉了,總有用得到的時候。一、47個快捷鍵1. 創建直線的快捷方式是L空格2. 創建圓的快捷方式是C空格3. 創建圓弧的快捷方式是A空格4. 創建矩形的快捷…

iOS項目架構 小談

層級結構,自底向上 持久層(File,Realm,SQLite)<>網絡層(相信每個公司都有自己的網絡層吧)>業務層(ViewModel)>展示層(View,VC) 持久層 耦合到網絡層 設計要點 持久模型的選擇&#xff0c;我這里選擇了文件&#xff0c;直接緩存了JSON.txt。并且維護一張表映射到文件…

計算機基礎:存儲系統知識筆記(二)

1、高速緩存 1.1 定義 用來存放當前最活躍的程序和數據。 特點&#xff1a;容量在幾千字節到幾兆之間&#xff0c;速度比主存快5~10倍左右。快速半導體組成。 1.2 高速緩存的組成 一般位于CPU和主存之間。主要包括管理模塊、由相聯存儲器構成的存儲表、小容量的高速存儲器。 1.…

spu和sku區別

SPU(Standard Product Unit) 標準化產品單元 SPU是能夠描述一個產品的單元&#xff0c;比如說&#xff0c;iPhone8就是一個SPU&#xff0c;與商家、顏色、款式、套餐無關。 SKU(Stock Keeping Unit) 庫存量單元 SKU是用來定價和管理庫存的&#xff0c;比如說&#xff0c;iPhon…

2020html5開發工具,2020web前端學習路線

原標題&#xff1a;2020web前端學習路線2020年最新web前端學習路線&#xff01;接下來&#xff0c;教大家如何從零基礎小白學習web前端&#xff0c;沒有基礎的伙伴也不要著急&#xff0c;有給大家整理視頻教程&#xff0c;文末&#xff0c;大家按需學習就好&#xff01;一、入門…

layuiajax提交表單控制層代碼_漏洞預警|ThinkPHP 5.0 遠程代碼執行

漏洞預警|ThinkPHP 5.0 遠程代碼執行2019-01-11事件來源2019年1月11日&#xff0c;ThinkPHP Github倉庫發布了新的版本v5.0.24&#xff0c;包含重要的安全更新&#xff0c;山石安服團隊經過分析把該漏洞危險級別定為嚴重。漏洞描述ThinkPHP是一個快速、兼容而且簡單的輕量級國產…

oracle sql日期比較

oracle sql日期比較: 在當前時間之前: select * from up_date where update < to_date(2007-09-07 00:00:00,yyyy-mm-dd hh24:mi:ss) select * from up_date where update < to_date(2007-09-07 00:00:00,yyyy-mm-dd hh24:mi:ss)在當前時間只后: select * from up_date w…

微信商戶平臺結算周期T+1是什么意思

我們在商戶平臺的管理后臺&#xff0c;有的時候&#xff0c;用戶支付了&#xff0c;可是卻沒有看到有資金信息&#xff0c;這個一般是因為您的賬戶類似的T1的原因。那結算周期T1是什么意思呢&#xff1f; 通俗的理解就是&#xff1a;交易日的次日。 T就是today &#xff08;今天…

計算機基礎:存儲系統知識筆記(三)

1、相聯存儲器 1、相聯存儲器介紹 屬于按內容訪問的存儲器。 原理&#xff1a;把數據或數據某一獨立單元作為關鍵字&#xff0c;用該關鍵字和存儲器的每個存儲單元比較&#xff0c;相同則表示找到對應的存儲單元。 2、相聯存儲器的組成部件 1、輸入檢索寄存器&#xff1a;存放要…

事業單位考試題庫計算機網絡,2015年事業單位計算機基礎知識試題及答案

2015年事業單位計算機基礎知識試題及答案一、單選題1、根據報文交換的基本原理&#xff0c;可以將其交換系統的功能概括為A)存儲系統 B)轉發系統C)存儲-轉發系統 D) 傳輸-控制系統2、TCP/IP網絡類型中&#xff0c;提供端到端的通信的是A)應用層 B) 傳輸層C)網絡層 D)網絡接口層…

list 排序_十個必知的排序算法|Python實例系列

十大排序:1.冒泡排序2.選擇排序3.插入排序4.希爾排序5.歸并排序6.快速排序7.堆排序8.計數排序9.桶排序10.基數排序完整代碼和注釋如下# -*- coding: UTF-8 -*-#Space: https://github.com/Tri-x/exercise#Space: https://space.bilibili.com/187492698#Author: Trix#Descriptio…

MySQL的安裝及使用教程

MySQL的安裝及使用教程 一、 MySQL的下載及安裝 首先登陸MySQL的官網&#xff0c;選擇Downloads→Windows→MySQL Installer→Windows(x86,32-bit),MSI Installer 在安裝的時候&#xff0c;可能要下載 .net Framework&#xff0c;直接下載就行&#xff0c;接著一步一步安裝就可…

小程序提供幾種結算周期? T+1是什么意思?

小程序提供4種固定的階梯周期選擇:T1、T7、T14、T28;其中T代表“Today”&#xff0c;今天的收入會在1(第2天)后自 動結算至銀行卡上。

提高國內訪問GitHub速度的9種方案~

GitHub 鏡像訪問GitHub文件加速Github 加速下載加速你的 Github谷歌瀏覽器 GitHub 加速插件(推薦)GitHub raw 加速GitHub Jsdelivr通過 Gitee 中轉 fork 倉庫下載通過修改 HOSTS 文件進行加速為什么 github 下載速度這么慢&#xff1f;如何提高 github 的下載速度&#xff1f;…