1,获取参数
package com.hcycom.ctginms.utils;
import com.alibaba.fastjson.JSONObject;
import org.apache.maven.shared.utils.StringUtils;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
/**
* @program: ctgnet-inms
* @description:
* @author: dhq
* @create: 2020-04-15 12:57
**/
public class MyRequestWrapper extends HttpServletRequestWrapper {
private String body;
public MyRequestWrapper(HttpServletRequest request) throws IOException {
super(request);
StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = null;
try {
InputStream inputStream = request.getInputStream();
if (inputStream != null) {
bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
char[] charBuffer = new char[128];
int bytesRead = -1;
while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
stringBuilder.append(charBuffer, 0, bytesRead);
}
} else {
stringBuilder.append("");
}
} catch (IOException ex) {
throw ex;
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException ex) {
throw ex;
}
}
}
body = stringBuilder.toString();
}
@Override
public ServletInputStream getInputStream() throws IOException {
final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes());
ServletInputStream servletInputStream = new ServletInputStream() {
@Override
public boolean isFinished() {
return false;
}
@Override
public boolean isReady() {
return false;
}
@Override
public void setReadListener(ReadListener readListener) {
}
public int read() throws IOException {
return byteArrayInputStream.read();
}
};
return servletInputStream;
}
@Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(this.getInputStream()));
}
public String getBody() {
return this.body;
}
@Override
public String getParameter(String name) {
return super.getParameter(name);
}
@Override
public Map<String, String[]> getParameterMap() {
return super.getParameterMap();
}
@Override
public Enumeration<String> getParameterNames() {
return super.getParameterNames();
}
@Override
public String[] getParameterValues(String name) {
return super.getParameterValues(name);
}
/**
* 设置自定义post参数 //
*
* @param paramMaps
* @return
*/
public void setParamsMaps(Map paramMaps) {
Map paramBodyMap = new HashMap();
if (!StringUtils.isEmpty(body)) {
paramBodyMap = JSONObject.parseObject(body, Map.class);
}
paramBodyMap.putAll(paramMaps);
body = JSONObject.toJSONString(paramBodyMap);
}
}
2.添加过滤器
package com.hcycom.ctginms.config;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.servlet.Filter;
@Configuration
public class FilterConfig {
//是初始化让@Autowired可以自动注入
@Bean
public Filter ApiInfo() {
return new ApiInfo();
}
@Bean
public FilterRegistrationBean sessionExpireFilter(){
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(this.ApiInfo());
registrationBean.addUrlPatterns("/ctgnet/circuit/*");
registrationBean.setOrder(1);
return registrationBean;
}
}
3.处理参数存入数据库
package com.hcycom.ctginms.config;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hcycom.ctginms.domain.CtgnetIfLog;
import com.hcycom.ctginms.service.CtgnetIfLogService;
import com.hcycom.ctginms.utils.MyRequestWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* @program: ctgnet-inms
* @description:调用接口监控调用信息
* @author: dhq
* @create: 2020-04-15 09:25
**/
@Slf4j
public class ApiInfo extends OncePerRequestFilter {
@Autowired
private CtgnetIfLogService ctgnetIfLogService;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
TreeMap paramsMaps = new TreeMap();
resp.setCharacterEncoding("UTF-8");
resp.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
String path=req.getServletPath();
String method = req.getMethod();
String ip_X_Forwarded= request.getHeader("X-Forwarded-For");
log.info("ip_X_Forwarded:"+ip_X_Forwarded);
String ipAddress3 = request.getRemoteAddr();
log.info("RemoteAddr:"+ipAddress3);
if (ip_X_Forwarded==null||"".equals(ip_X_Forwarded)) {
ip_X_Forwarded = getIpAddr(request);
}
String ip="";
if(ip_X_Forwarded.indexOf(",")>0){
String[] split = ip_X_Forwarded.split(",");
ip=split[0];
}else {
ip= ip_X_Forwarded;
}
String ipforword=ip_X_Forwarded+","+ipAddress3;
// MyRequestWrapper requestWrapper = new MyRequestWrapper(req);
// if ("POST".equals(req.getMethod().toUpperCase())) {
// String body = requestWrapper.getBody();
// JSONObject jsonObject = JSONObject.parseObject(body);
//// paramsMaps = JSONObject.parseObject(body, TreeMap.class);
// log.info("parameterMap:" + jsonObject);
// } else {
// Map<String, String[]> parameterMap = requestWrapper.getParameterMap();
// Set<Map.Entry<String, String[]>> entries = parameterMap.entrySet();
// Iterator<Map.Entry<String, String[]>> iterator = entries.iterator();
// while (iterator.hasNext()) {
// Map.Entry<String, String[]> next = iterator.next();
// paramsMaps.put(next.getKey(), next.getValue()[0]);
// }
// log.info("parameterMap:" + paramsMaps.toString());
// }
//
//
// filterChain.doFilter(request, response);
MyRequestWrapper requestWrapper = null;
// List<CtgnetIfLog> ctgnetIfLogs=new CopyOnWriteArrayList<>();
CtgnetIfLog ctgnetIfLog=new CtgnetIfLog();
if(request instanceof HttpServletRequest) {
requestWrapper = new MyRequestWrapper(req);
if ("POST".equals(req.getMethod().toUpperCase())) {
String body = requestWrapper.getBody();
JSONObject jsonObject = JSONObject.parseObject(body);
String pam= JSON.toJSONString(jsonObject);
// paramsMaps = JSONObject.parseObject(body, TreeMap.class);
ctgnetIfLog.setSource_ip(ip);
ctgnetIfLog.setInterface_path(path);
ctgnetIfLog.setRequest_data(pam);
ctgnetIfLog.setRequest_type(method);
ctgnetIfLog.setForwarded_For(ipforword);
ctgnetIfLogService.insertCtgnetIfLog(ctgnetIfLog);
log.info("parameterMap:" + jsonObject);
} else {
Map<String, String[]> parameterMap = requestWrapper.getParameterMap();
Set<Map.Entry<String, String[]>> entries = parameterMap.entrySet();
Iterator<Map.Entry<String, String[]>> iterator = entries.iterator();
while (iterator.hasNext()) {
Map.Entry<String, String[]> next = iterator.next();
paramsMaps.put(next.getKey(), next.getValue()[0]);
}
String pa=paramsMaps.toString();
ctgnetIfLog.setInterface_path(path);
ctgnetIfLog.setSource_ip(ip);
ctgnetIfLog.setRequest_data(pa);
ctgnetIfLog.setRequest_type(method);
ctgnetIfLog.setForwarded_For(ipforword);
ctgnetIfLogService.insertCtgnetIfLog(ctgnetIfLog);
log.info("parameterMap:" + pa);
}
}
//获取请求中的流如何,将取出来的字符串,再次转换成流,然后把它放入到新request对象中。
// 在chain.doFiler方法中传递新的request对象
if(requestWrapper == null) {
filterChain.doFilter(request, response);
} else {
filterChain.doFilter(requestWrapper, response);
}
}
private String getIpAddr(HttpServletRequest request) {
String ipAddress = null;
try {
ipAddress = request.getHeader("x-forwarded-for");
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("Proxy-Client-IP");
log.info("ipAddress2:"+ipAddress);
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("WL-Proxy-Client-IP");
log.info("ipAddress3:"+ipAddress);
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getRemoteAddr();
log.info("ipAddress4:"+ipAddress);
if (ipAddress.equals("127.0.0.1")) {
// 根据网卡取本机配置的IP
InetAddress inet = null;
try {
inet = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
}
if (inet==null) {
ipAddress = "127.0.0.1";
}else{
ipAddress = inet.getHostAddress();
}
}
}
// 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照‘,‘分割
if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
log.info("ipAddress5:"+ipAddress);
// = 15
if (ipAddress.indexOf(",") > 0) {
ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
}
}
} catch (Exception e) {
ipAddress="";
}
return ipAddress;
}
}