拦截器(Inteceptor),过滤器(Filter),切面(Aspect)处理HttpServiceReqeust请求
1.拦截器
java里的拦截器是动态拦截Action调用的对象。它提供了一种机制可以使开发者可以定义在一个action执行的前后执行的代码,也可以在一个action执行前阻止其执行,同时也提供了一种可以提取action中可重用部分的方式。在AOP(Aspect-Oriented Programming)中拦截器用于在某个方法或字段被访问之前,进行拦截然后在之前或之后加入某些操作。
package com.shitou.deposit.interceptor; import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Parameter; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView; import com.shitou.deposit.contract.dto.req.Request; /**
* DepositInterceptor
* @author zhouky
* @since 2018年12月27日
*/
public class DepositInterceptor implements HandlerInterceptor {
private Logger logger = LoggerFactory.getLogger(getClass()); @Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
logger.info("DepositInterceptor ..."); // 所有请求第一个进入的方法
String reqURL = request.getRequestURL().toString();
String ip = request.getRemoteHost ();
InputStream is = request.getInputStream ();
StringBuilder responseStrBuilder = new StringBuilder ();
BufferedReader streamReader = new BufferedReader (new InputStreamReader (is,"UTF-8"));
String inputStr;
while ((inputStr = streamReader.readLine()) != null) responseStrBuilder.append(inputStr);
String parmeter = responseStrBuilder.toString();
long startTime = System.currentTimeMillis();
request.setAttribute("startTime", startTime);
if (handler instanceof HandlerMethod) {
StringBuilder sb = new StringBuilder(1000);
sb.append("-----------------------\n");
HandlerMethod h = (HandlerMethod) handler;
Parameter[] objs =h.getMethod().getParameters();
for(Object obj:objs){
Request req = (Request) obj;
System.out.println("");
if(obj instanceof Request){
}
} //Controller 的包名
sb.append("Controller: ").append(h.getBean().getClass().getName()).append("\n");
//方法名称
sb.append("Method: ").append(h.getMethod().getName()).append("\n");
//请求方式post\put\get 等等
sb.append("RequestMethod: ").append(request.getMethod()).append("\n");
//所有的请求参数
sb.append("Params: ").append(parmeter).append("\n");
//部分请求链接
sb.append("URI : ").append(request.getRequestURI()).append("\n");
//完整的请求链接
sb.append("AllURI: ").append(reqURL).append("\n");
//请求方的 ip地址
sb.append("request IP: ").append(ip).append("\n");
logger.info(sb.toString());
}
//修改request中的参数并保存到request中
request.setAttribute("parmeter_json", parmeter); return true;
} @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.shitou.deposit.config; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import com.shitou.deposit.interceptor.DepositInterceptor;
import com.shitou.deposit.interceptor.DepositInterceptor1; /**
* InterceptorConfig
* @author zhouky
* @since 2018年12月27日
*/
@Configuration
public class InterceptorConfig extends WebMvcConfigurerAdapter { @Bean
public DepositInterceptor getDepositInterceptor() {
return new DepositInterceptor();
} @Bean
public DepositInterceptor1 getDepositInterceptor1() {
return new DepositInterceptor1();
} @Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(getDepositInterceptor()).addPathPatterns("/deposit/**");
// registry.addInterceptor(getDepositInterceptor1()).addPathPatterns("/deposit/**");
super.addInterceptors(registry);
} }
package com.shitou.deposit.interceptor; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView; import com.alibaba.fastjson.JSONObject;
import com.shitou.deposit.filter.BufferedServletRequestWrapper; /**
* DepositInterceptor1
* @author zhouky
* @since 2018年12月27日
*/
public class DepositInterceptor1 implements HandlerInterceptor {
private Logger logger = LoggerFactory.getLogger(getClass()); @Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
logger.info("DepositInterceptor begin ..."); BufferedServletRequestWrapper requestWrapper = new BufferedServletRequestWrapper(request);
//在这边替换流,使用工具类GetRequestJsonUtils获取json参数
JSONObject json = GetRequestJsonUtils.getRequestJsonObject(requestWrapper); logger.info("DepositInterceptor end ...{}",json.toJSONString());
return true;
} @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.shitou.deposit.filter; import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader; import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper; /**
* BufferedServletRequestWrapper
* @author zhouky
* @since 2018年12月27日
*/
public class BufferedServletRequestWrapper extends HttpServletRequestWrapper { private byte[] buffer; public BufferedServletRequestWrapper(HttpServletRequest request) throws IOException {
super(request);
InputStream is = request.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte buff[] = new byte[1024];
int read;
while ((read = is.read(buff)) > 0) {
baos.write(buff, 0, read);
}
this.buffer = baos.toByteArray();
} @Override
public ServletInputStream getInputStream() throws IOException {
return new BufferedServletInputStream(this.buffer);
} // 对外提供读取流的方法
@Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(getInputStream()));
}
}
package com.shitou.deposit.interceptor; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang3.StringUtils; import com.alibaba.fastjson.JSONObject; /**
* GetRequestJsonUtils
* @author zhouky
* @since 2018年12月27日
*/
public class GetRequestJsonUtils { public static JSONObject getRequestJsonObject(HttpServletRequest request) throws IOException {
String json = getRequestJsonString(request);
return JSONObject.parseObject(json);
} /***
* 获取 request 中 json 字符串的内容
*
* @param request
* @return : <code>byte[]</code>
* @throws IOException
*/
public static String getRequestJsonString(HttpServletRequest request)
throws IOException {
String submitMehtod = request.getMethod();
// GET
if (submitMehtod.equals("GET")) {
if(StringUtils.isNotEmpty(request.getQueryString())){
return new String(request.getQueryString().getBytes("iso-8859-1"),"utf-8").replaceAll("%22", "\"");
}else{
return new String("".getBytes("iso-8859-1"), "utf-8").replaceAll("%22", "\"");
}
// POST
} else {
return getRequestPostStr(request);
}
} /**
* 描述:获取 post 请求的 byte[] 数组
* <pre>
* 举例:
* </pre>
* @param request
* @return
* @throws IOException
*/
public static byte[] getRequestPostBytes(HttpServletRequest request)
throws IOException {
int contentLength = request.getContentLength();
if(contentLength<0){
return null;
}
byte buffer[] = new byte[contentLength];
for (int i = 0; i < contentLength;) { int readlen = request.getInputStream().read(buffer, i,
contentLength - i);
if (readlen == -1) {
break;
}
i += readlen;
}
return buffer;
} /**
* 描述:获取 post 请求内容
* <pre>
* 举例:
* </pre>
* @param request
* @return
* @throws IOException
*/
public static String getRequestPostStr(HttpServletRequest request)
throws IOException {
byte buffer[] = getRequestPostBytes(request);
String charEncoding = request.getCharacterEncoding();
if (charEncoding == null) {
charEncoding = "UTF-8";
}
return new String(buffer, charEncoding);
}
}
2.过滤器
package com.shitou.deposit.filter; import java.io.IOException; import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Component; /**
* DepositFilter
* @author zhouky
* @since 2018年12月27日
*/
@Component
@WebFilter(filterName="DepositFilter",urlPatterns="/**")
public class DepositFilter implements Filter{ /**
* 过滤
*/
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
ServletRequest requestWrapepr = null;
if(request instanceof HttpServletRequest){
requestWrapepr = new BufferedServletRequestWrapper((HttpServletRequest)request);
}
if(requestWrapepr == null){
chain.doFilter(request, response);
}else{
chain.doFilter(requestWrapepr, response);
}
} /**
* 初始化
*/
@Override
public void init(FilterConfig arg0) throws ServletException {} /**
* 销毁
*/
@Override
public void destroy() {} }
package com.shitou.deposit.filter; import java.io.ByteArrayInputStream;
import java.io.IOException; import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream; class BufferedServletInputStream extends ServletInputStream {
private ByteArrayInputStream inputStream;
public BufferedServletInputStream(byte[] buffer) {
this.inputStream = new ByteArrayInputStream( buffer );
}
@Override
public int available() throws IOException {
return inputStream.available();
}
@Override
public int read() throws IOException {
return inputStream.read();
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
return inputStream.read( b, off, len );
}
@Override
public boolean isFinished() {
return false;
}
@Override
public boolean isReady() {
return false;
}
@Override
public void setReadListener(ReadListener listener) {}
}
package com.shitou.deposit.filter; import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader; import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper; /**
* BufferedServletRequestWrapper
* @author zhouky
* @since 2018年12月27日
*/
public class BufferedServletRequestWrapper extends HttpServletRequestWrapper { private byte[] buffer; public BufferedServletRequestWrapper(HttpServletRequest request) throws IOException {
super(request);
InputStream is = request.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte buff[] = new byte[1024];
int read;
while ((read = is.read(buff)) > 0) {
baos.write(buff, 0, read);
}
this.buffer = baos.toByteArray();
} @Override
public ServletInputStream getInputStream() throws IOException {
return new BufferedServletInputStream(this.buffer);
} // 对外提供读取流的方法
@Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(getInputStream()));
}
}
package com.shitou.deposit.filter; import java.io.IOException;
import java.util.HashMap;
import java.util.Map; import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component; import com.alibaba.fastjson.JSONObject; //@Component
//@WebFilter(filterName = "DepositFilter1", urlPatterns = "/*")
public class DepositFilter1 implements Filter { @SuppressWarnings("unused")
private Logger logger = LoggerFactory.getLogger(DepositFilter1.class); @Override
public void init(FilterConfig filterConfig) throws ServletException {} @Override
public void doFilter(ServletRequest srequest, ServletResponse sresponse, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) srequest;
// 访问地址
String uri = request.getRequestURI();
if ("/deposit/execute".equals(uri)) {
Map<String,Object> m = new HashMap<String, Object>(request.getParameterMap());
logger.info(JSONObject.toJSONString(m));
HttpServletRequest req = (HttpServletRequest) request;
ParameterRequestWrapper wrapRequest = new ParameterRequestWrapper(req, m);
logger.info(JSONObject.toJSONString(wrapRequest.getParameterMap()));
request = wrapRequest;
}
filterChain.doFilter(request, sresponse);
} @Override
public void destroy() {} }
3.切面
package com.shitou.deposit.aspect; import java.util.Base64;
import java.util.Map; import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component; import com.shitou.deposit.baofu.config.BaoFuConfig;
import com.shitou.deposit.contract.dto.req.Request;
import com.shitou.deposit.lanmaoly.config.LanMaolyConfig;
import com.shitou.deposit.strategy.enums.TransactionChannelEnum;
import com.shitou.framework.log.LOG_TYPE; @SuppressWarnings("unchecked")
//@Component
//@Aspect
public class DepositAspect {
private final Logger logger = LoggerFactory.getLogger(LOG_TYPE.CONTROLLER_ASPECT.val); @Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
public void depositAspect() {} @Before(value = "depositAspect()")
public void beforeAdvice(JoinPoint pjp) throws Throwable {
Object[] objects = pjp.getArgs();
for(Object obj:objects){
if(obj instanceof Request){
Request paramVO = (Request) obj; Map<String,Object> reqMap = (Map<String, Object>) paramVO.getReqData();
boolean bool = reqMap.containsKey("retUrl");
if(bool){
String retUrl = (String) reqMap.get("retUrl");
if(StringUtils.isNotBlank(retUrl)){
String encodedUrl = Base64.getEncoder().encodeToString(retUrl.getBytes());
if(TransactionChannelEnum.LANM.getCode().equals("")&&
!"1".equals(LanMaolyConfig.ifSyncDirectSwitch)){// 懒猫是否开启同步回盘直连前端开关 1-是 0-否
retUrl = LanMaolyConfig.syncLM+"/"+encodedUrl;
}else if(TransactionChannelEnum.BAOF.getCode().equals("")&&
!"1".equals(BaoFuConfig.ifSyncDirectSwitch)){
retUrl = BaoFuConfig.syncBF+"/"+encodedUrl;
}
reqMap.put("retUrl", retUrl);
paramVO.setReqData(reqMap);
}
}
}
} }
}
拦截器(Inteceptor),过滤器(Filter),切面(Aspect)处理HttpServiceReqeust请求的更多相关文章
- Spring Boot实战:拦截器与过滤器
一.拦截器与过滤器 在讲Spring boot之前,我们先了解一下过滤器和拦截器.这两者在功能方面很类似,但是在具体技术实现方面,差距还是比较大的.在分析两者的区别之前,我们先理解一下AOP的概念,A ...
- struct_2拦截器与过滤器
这个为网上所剪切的知识点,仅为个人学习所用,无其他用途. 过滤器,是在java web中,你传入的request,response提前过滤掉一些信息,或者提前设置一些参数,然后再传入servlet或者 ...
- java 拦截器、过滤器、监听器
一.理解Struts2拦截器 1. Struts2拦截器是在访问某个Action或Action的某个方法,字段之前或之后实施拦截,并且Struts2拦截器是可插拔的,拦截器是AOP的一种实现. 2. ...
- Spring Boot之拦截器与过滤器(完整版)
作者:liuxiaopeng 链接:http://www.cnblogs.com/paddix 作者:蓝精灵lx原文:https://blog.csdn.net/liuxiao723846/artic ...
- Spring Aop、拦截器、过滤器的区别
Filter过滤器:拦截web访问url地址.Interceptor拦截器:拦截以 .action结尾的url,拦截Action的访问.Spring AOP拦截器:只能拦截Spring管理Bean的访 ...
- SpringMVC——拦截器,过滤器实现登录拦截
一.拦截器与过滤器的区别 1.过滤器 依赖于servlet容器.在实现上基于函数回调,可以对几乎所有请求进行过滤,但是缺点是一个过滤器实例只能在容器初始化时调用一次.使用过滤器的目的是用来做一些过滤操 ...
- 简单理解Struts2中拦截器与过滤器的区别及执行顺序
简单理解Struts2中拦截器与过滤器的区别及执行顺序 当接收到一个httprequest , a) 当外部的httpservletrequest到来时 b) 初始到了servlet容器 传递给一个标 ...
- struts2拦截器与过滤器
转载:http://www.cnblogs.com/JohnLiang/archive/2011/12/15/2288376.html 过滤器,是在java web中,你传入的request,resp ...
- SpringMVC中的拦截器、过滤器的区别、处理异常
1. SpringMVC中的拦截器(Interceptor) 1.1. 作用 拦截器是运行在DispatcherServlet之后,在每个Controller之前的,且运行结果可以选择放行或拦截! 除 ...
随机推荐
- 基于SpringBoot的Environment源码理解实现分散配置
前提 org.springframework.core.env.Environment是当前应用运行环境的公开接口,主要包括应用程序运行环境的两个关键方面:配置文件(profiles)和属性.Envi ...
- ant Table td 溢出隐藏(省略号)
1.创建组件 components/LineWrap/index.js /** * td 溢出隐藏 组件 */ import React, { PureComponent } from 'react' ...
- Android双向seekbar
※效果 watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/disso ...
- Unity 背包道具搜索
因为背包有很多道具,用户要根据不同需要搜索出不同的道具. 道具的属性有非常居多,游戏快开发完毕的时候,突然发现ItemManager类里面几乎每一个搜索方法都有一个foreach循环, 循环里面因为 ...
- C++从零实现简单深度神经网络(基于OpenCV)
代码地址如下:http://www.demodashi.com/demo/11138.html 一.准备工作 需要准备什么环境 需要安装有Visual Studio并且配置了OpenCV.能够使用Op ...
- Excel 时间格式相减
https://jingyan.baidu.com/article/3065b3b6e8b9dabecff8a4d6.html datedif函数是excel的隐藏函数,主要用于计算日期之差,不是四舍 ...
- DEDECMS 添加栏目图片
当我们一个栏目列表都用缩略图来表示产,而不仅仅只是文字,如果没有这项功能会非常麻烦,网上有很多这方面的资料,但是都试过了有很多问题,自己研究一下,测试基本通过.需要新加字段 typeimg 后台执行S ...
- mysql安装在centos7报错ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)
原文链接:http://blog.csdn.net/kuluzs/article/details/51924086 [问题]:mysql版本:5.7.13 首次在centos下安装MySQL,客户端连 ...
- zookeeper(四):核心原理(Watcher、事件和状态)
zookeeper主要是为了统一分布式系统中各个节点的工作状态,在资源冲突的情况下协调提供节点资源抢占,提供给每个节点了解整个集群所处状态的途径.这一切的实现都依赖于zookeeper中的事件监听和通 ...
- vivado设计四:自定义IP核测试
在vivado设计三中:http://blog.chinaaet.com/detail/37177已经建立了vivado工程和封装好了自定义IP核. 那么接下来,我们对这个自定义IP核进行测试了:我们 ...