1.總結內容參考:https://blog.csdn.net/dhklsl/article/details/127533485 2.下麵是本人工作項目中實戰到的案例(具體業務的實體沒必要關註) 2.1.攔截器使用 點擊查看代碼 import java.lang.invoke.MethodHandle ...
1.總結內容參考:https://blog.csdn.net/dhklsl/article/details/127533485
2.下麵是本人工作項目中實戰到的案例(具體業務的實體沒必要關註)
2.1.攔截器使用
點擊查看代碼
import java.lang.invoke.MethodHandles;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.logging.log4j.Logger;
import org.dom4j.Document;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.epoint.core.utils.string.StringUtil;
import com.epoint.financeproduct.dao.TBaoHanApplyDao;
import com.epoint.financeproduct.domain.Tbaohanapply;
import com.epoint.financeproduct.tbaohanbtdh.dao.TBaoHanApplyBTDHDao;
import com.epoint.financeproduct.util.DynamicLoggerUtil;
/**
* 通知api路由攔截器
* @作者 jawel
* @version [版本號, 2021年3月16日]
* @see [相關類/方法]
* @since [產品/模塊版本]
*/
public class BTDHNoticeApiRouterInterceptor implements HandlerInterceptor
{
protected Logger logger = DynamicLoggerUtil.getLoggerByClass(MethodHandles.lookup().lookupClass(), DynamicLoggerUtil.LogType.COMMON);
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
Document document = BTDHApiRouterInterceptorUtil.preHandle(request, response, handler);
document.getRootElement().element("body").elementText("OrderNo");
String ApplyOrderNo = document.getRootElement().element("body").elementText("OrderNo");
String baohanno = document.getRootElement().element("body").elementText("PolicyNo");
logger.info("ApplyOrderNo"+ApplyOrderNo);
logger.info("baohanno"+baohanno);
//applyno和baohanno均為空,則直接通過,防止誤攔截
if(StringUtil.isBlank(ApplyOrderNo) && StringUtil.isBlank(baohanno)){
return true;
}
//獲取保函申請數據
TBaoHanApplyBTDHDao tBaoHanApplyDao = new TBaoHanApplyBTDHDao();
Tbaohanapply tBaoHanApply = null;
if (StringUtil.isNotBlank(ApplyOrderNo)) {
tBaoHanApply = tBaoHanApplyDao.getTBaoHanInfoByApplyorderno(ApplyOrderNo);
}
//如果通過applyno獲取申請數據為空,則再通過baohanno獲取數據
if (tBaoHanApply == null && StringUtil.isNotBlank(baohanno)) {
tBaoHanApply = tBaoHanApplyDao.getTBaoHanApplyByBaoHanNo(baohanno);
}
logger.info("tBaoHanApply"+tBaoHanApply.toString());
request.setAttribute("tBaoHanApply", tBaoHanApply);
// 處理攔截請求
return BTDHApiRouterInterceptorUtil.doInterceptRequest(request, response);
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
}
}
點擊查看工具類
package com.epoint.financeproduct.btdh.util;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.lang.invoke.MethodHandles;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.logging.log4j.Logger;
import org.dom4j.Document;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.method.HandlerMethod;
import com.epoint.core.utils.config.ConfigUtil;
import com.epoint.core.utils.httpclient.HttpClientUtil;
import com.epoint.core.utils.string.StringUtil;
import com.epoint.financeproduct.domain.Tbaohanapply;
import com.epoint.financeproduct.job.DataSync2EpointFinanceProduct_Push_Data_Sec_H_Job;
import com.epoint.financeproduct.util.Constant.IsOrNot;
import com.epoint.financeproduct.util.DynamicLoggerUtil;
import com.epoint.financeproduct.util.IDUtils;
import com.epoint.financeproduct.util.InsuranceServerInfo;
import com.epoint.financeproduct.util.InsuranceServerInfoUtil;
import com.epoint.financeproduct.util.RequestUtils;
import com.epoint.financeproduct.util.ValueProcessUtils;
public class BTDHApiRouterInterceptorUtil
{
private static Logger logger = DynamicLoggerUtil.getLoggerByClass(MethodHandles.lookup().lookupClass(), DynamicLoggerUtil.LogType.COMMON);
public static Document preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
//獲取RequestMapping註解
HandlerMethod method = (HandlerMethod) handler;
RequestMapping controllerRequestMapping = method.getBean().getClass().getAnnotation(RequestMapping.class);
RequestMapping methodRequestMapping = method.getMethod().getAnnotation(RequestMapping.class);
//拼接url路徑
StringBuilder sb = new StringBuilder("");
sb.append(getRequestMappingValue(controllerRequestMapping));
sb.append(getRequestMappingValue(methodRequestMapping));
//獲取mapping地址
String mappingUrl = sb.toString();
// 存入request區域
logger.info("mappingUrl"+mappingUrl);
request.setAttribute("mappingUrl", mappingUrl);
//獲取請求參數
BTBaseService baseService = null;
try {
baseService = new BTBaseService(request, response);
}
catch (Exception e) {
logger.error("獲取baseService異常", e);
}
return baseService.receivexmlString;
}
/**
* [處理攔截請求]
* @param request
* @param response
* @return
* @throws Exception
*/
public static boolean doInterceptRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
// 從request請求域獲取保函申請對象
Tbaohanapply tBaoHanApply = (Tbaohanapply) request.getAttribute("tBaoHanApply");
// 從request請求域獲取mappingUrl
String mappingUrl = (String) request.getAttribute("mappingUrl");
logger.info("mappingUrl"+mappingUrl);
//如果申請數據不存在,則進行轉發
if (tBaoHanApply == null) {
logger.info("tBaoHanApply==kong");
// 判斷下當前系統是否為119大平臺,防止死迴圈
String isEpointProduct = ConfigUtil.getConfigValue("isepointproduct");
if (StringUtil.isNotBlank(isEpointProduct) && IsOrNot.是.value.equals(Integer.valueOf(isEpointProduct))) {
return true;
}
//轉發請求
//獲取新點產品端web地址
String epointFinanceProductInterfaceUrl = DataSync2EpointFinanceProduct_Push_Data_Sec_H_Job.getEpointFinanceProductInterfaceUrl();
//如果未配置“新點金融服務支撐平臺(產品端)介面地址”,或者mappingUrl為空,則直接通過
if(StringUtil.isBlank(epointFinanceProductInterfaceUrl) || StringUtil.isBlank(mappingUrl)){
return true;
}
// 請求轉發
doRequestForward(request, response, epointFinanceProductInterfaceUrl, mappingUrl);
return false;
}
else {
logger.info("tBaoHanApply==getIsPushFinanceInsurance"+tBaoHanApply.getIsPushFinanceInsurance());
// 保函申請數據存在,根據保函申請表(TBaoHanApply)上的IsPushFinanceInsurance(是否推送金融機構產品端系統)欄位和FinanceInsuranceID(金融機構產品端ID)欄位來判斷是否轉發
// 如果IsPushFinanceInsurance(是否推送金融機構產品端系統)欄位的值是“IsOrNot.是.value”,說明是轉發的
if (IsOrNot.是.value.equals(tBaoHanApply.getIsPushFinanceInsurance())) {
// 根據FinanceInsuranceID(金融機構產品端ID)欄位值找到對應的轉發伺服器信息,將通知介面轉發到對應的伺服器上
InsuranceServerInfo insuranceServerInfo = InsuranceServerInfoUtil.getInsuranceServerInfoByID(tBaoHanApply.getPlatformcode(), tBaoHanApply.getProductcode(), tBaoHanApply.getFinanceInsuranceID());
String financeInsuranceUrl = insuranceServerInfo.getFinanceInsuranceUrl();
logger.info("financeInsuranceUrl"+financeInsuranceUrl);
logger.info("mappingUrl"+mappingUrl);
// 轉發
doRequestForward(request, response, financeInsuranceUrl, mappingUrl);
return false;
}
}
return true;
}
/**
* [轉發]
* @param request
* @param response
* @param financeProductInterfaceUrl
* @param mappingUrl
* @throws Exception
*/
public static void doRequestForward(HttpServletRequest request, HttpServletResponse response, String financeProductInterfaceUrl, String mappingUrl) throws Exception {
InputStream in = (ByteArrayInputStream) request.getAttribute("inputstream");
//重置流讀取位置
in.reset();
String params = ValueProcessUtils.convertInputStream2String(in);
String url = financeProductInterfaceUrl + mappingUrl;
String reqID = IDUtils.getID("REQ", 5);
logger.info("reqID=" + reqID + ",NoticeApiRouterInterceptor.url=" + url);
String resultStr = RequestUtils.httpsPostUTF8Xml(url, params);
logger.info("reqID=" + reqID + ",NoticeApiRouterInterceptor.postBody=" + resultStr);
//響應返回值
response.setHeader("Content-Type", "text/xml;charset=UTF-8");
// response.setHeader("Content-Type", "application/json;charset=utf-8");
response.getWriter().write(resultStr);
}
/**
* 獲取RequestMapping的value值
* @param requestMapping
* @return
* @exception/throws [違例類型] [違例說明]
* @see [類、類#方法、類#成員]
*/
private static String getRequestMappingValue(RequestMapping requestMapping) {
String value = "";
if (requestMapping != null && requestMapping.value() != null && requestMapping.value().length > 0) {
value = requestMapping.value()[0];
}
return value;
}
}
2.2 過濾器的使用
點擊查看代碼
package com.epoint.financeproduct.btdh.util;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.invoke.MethodHandles;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ReadListener;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import org.apache.logging.log4j.Logger;
import org.dom4j.Document;
import com.epoint.core.utils.string.StringUtil;
import com.epoint.financeproduct.dao.FinancePlatformProductSettingsDao;
import com.epoint.financeproduct.dao.FinanceProductDao;
import com.epoint.financeproduct.domain.FinancePlatformProductSettings;
import com.epoint.financeproduct.domain.Financeproduct;
import com.epoint.financeproduct.domain.Tbaohanapply;
import com.epoint.financeproduct.tbaohanbtdh.dao.TBaoHanApplyBTDHDao;
import com.epoint.financeproduct.util.Constant.IsOrNot;
import com.epoint.financeproduct.util.DynamicLoggerUtil;
import com.epoint.financeproduct.util.FileManage;
import com.epoint.financeproduct.util.IDUtils;
import com.epoint.financeproduct.util.RequestUtils;
import com.epoint.financeproduct.util.ValueProcessUtils;
/**
* 標準版通知api路由攔截器
* @作者 jawel
* @version [版本號, 2021年5月27日]
* @see [相關類/方法]
* @since [產品/模塊版本]
*/
public class BTDHNoticeApiRouterFilter implements Filter
{
private static final Logger logger = DynamicLoggerUtil
.getLogger(MethodHandles.lookup().lookupClass().getSimpleName(), DynamicLoggerUtil.LogType.COMMON);
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest requestWrapper = null;
out: if (request instanceof HttpServletRequest) {
try {
//requestWrapper = new BufferedServletRequestWrapper((HttpServletRequest) request);
requestWrapper = (HttpServletRequest) request;
BTBaseService baseService = new BTBaseService((HttpServletRequest) request, (HttpServletResponse) response);
Document document = baseService.receivexmlString;
document.getRootElement().element("body").elementText("OrderNo");
String ApplyOrderNo = document.getRootElement().element("body").elementText("OrderNo");
String baohanno = document.getRootElement().element("body").elementText("PolicyNo");
//appkey為空,則直接通過,防止誤攔截
if (StringUtil.isBlank(ApplyOrderNo)) {
break out;
}
// applyNo為空,則直接通過,防止誤攔截
if (StringUtil.isBlank(baohanno)) {
break out;
}
// 獲取申請信息
//獲取保函申請數據
TBaoHanApplyBTDHDao tBaoHanApplyDao = new TBaoHanApplyBTDHDao();
Tbaohanapply tBaoHanApply = null;
if (StringUtil.isNotBlank(ApplyOrderNo)) {
tBaoHanApply = tBaoHanApplyDao.getTBaoHanInfoByApplyorderno(ApplyOrderNo);
}
if (tBaoHanApply == null) {
break out;
}
FinanceProductDao financeProductDao = new FinanceProductDao();
Financeproduct productInfo = financeProductDao.getProductInfoByProductCode(tBaoHanApply.getProductcode());
//productInfo為空,則直接通過,防止誤攔截
if (productInfo == null) {
break out;
}
// 獲取平臺產品配置信息
FinancePlatformProductSettings settings = new FinancePlatformProductSettingsDao()
.getSettingsByPlatformCodeAndProductCode(tBaoHanApply.getPlatformcode(),
productInfo.getProductcode());
//如果產品上配置轉發到開發環境,則進行轉發
if (IsOrNot.是.value.toString()
.equals(ValueProcessUtils.getValueNoException(settings, "isredirectdev"))) {
String requestURI = requestWrapper.getRequestURI();
//轉發請求
//獲取轉發地址
String routerDevUrl = ValueProcessUtils.getValueNoException(settings, "devrouterurl");
//如果未配置“新點金融服務支撐平臺(產品端)介面地址”,或者requestURI為空,則直接通過
if (StringUtil.isBlank(routerDevUrl) || StringUtil.isBlank(requestURI)) {
break out;
}
String url = routerDevUrl + requestURI;
InputStream in = requestWrapper.getInputStream();
//獲取原始報文參數
String params = "";
try {
params = ValueProcessUtils.convertInputStream2String(in);
}
catch (Exception e) {
logger.error("url=" + url + ">>>InputStream轉String失敗error", e);
}
String reqID = IDUtils.getID("REQ", 5);
logger.info("BTDHNoticeApiRouterFilterreqID=" + reqID + ",NoticeApiRouterInterceptor.url=" + url);
String resultStr = RequestUtils.httpsPostUTF8Xml(url, params);
logger.info("BTDHNoticeApiRouterFilterreqID=" + reqID + ",NoticeApiRouterInterceptor.postBody=" + resultStr);
//響應返回值
HttpServletResponse newResponse = (HttpServletResponse) response;
newResponse.setHeader("Content-Type", "text/xml;charset=UTF-8");
//newResponse.setHeader("Content-Type", "application/json;charset=utf-8");
newResponse.getWriter().write(resultStr);
return;
}
}
catch (Exception e) {
logger.error("BTDHNoticeApiRouterFilter.doFilter error", e);
}
}
if (requestWrapper == null) {
chain.doFilter(request, response);
}
else {
chain.doFilter(requestWrapper, response);
}
}
@Override
public void destroy() {
}
}
class BufferedServletRequestWrapper extends HttpServletRequestWrapper
{
private final byte[] body; // 報文
public BufferedServletRequestWrapper(HttpServletRequest request) throws IOException {
super(request);
body = FileManage.fileToByte(request.getInputStream());
}
@Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(getInputStream()));
}
@Override
public ServletInputStream getInputStream() throws IOException {
final ByteArrayInputStream bais = new ByteArrayInputStream(body);
return new ServletInputStream()
{
@Override
public int read() throws IOException {
return bais.read();
}
@Override
public boolean isFinished() {
return false;
}
@Override
public boolean isReady() {
return false;
}
@Override
public void setReadListener(ReadListener readListener) {
}
};
}
}