package com.hyatt.temp.filter;
import org.springframework.context.annotation.Configuration;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
/**
* @author Hyatt
* @date 2019/11/21
*/
@Configuration
@WebFilter(filterName="wrappedFilter",urlPatterns="/*")
public class SimpleWrappedFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
WrappedHttpServletRequest requestWrapper = new WrappedHttpServletRequest((HttpServletRequest) request);
// 这里doFilter传入实现的子类
chain.doFilter(requestWrapper, response);
}
@Override
public void destroy() {
}
}
package com.hyatt.temp.filter;
import com.alibaba.fastjson.JSON;
import com.hyatt.temp.interception.ControllerInterceptor;
import com.hyatt.temp.utils.StringJsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.util.*;
/**
* @author Hyatt
* @date 2019/11/21
*/
public class WrappedHttpServletRequest extends HttpServletRequestWrapper {
private static final Logger log = LoggerFactory.getLogger(ControllerInterceptor.class);
private Map<String , String[]> params = new HashMap<String, String[]>();
WrappedHttpServletRequest(HttpServletRequest request) {
// 将request交给父类,以便于调用对应方法的时候,将其输出,其实父亲类的实现方式和第一种new的方式类似
super(request);
//将参数表,赋予给当前的Map以便于持有request中的参数
Map<String, String[]> requestMap=request.getParameterMap();
log.info("parameterMap convert before :"+JSON.toJSONString(requestMap));
this.params.putAll(requestMap);
this.modifyParameterValues();
log.info("parameterMap convert after :"+JSON.toJSONString(params));
}
/**
* 重写getInputStream方法 post类型的请求参数必须通过流才能获取到值
*/
@Override
public ServletInputStream getInputStream() throws IOException {
//非json类型,直接返回
if(!super.getHeader(HttpHeaders.CONTENT_TYPE).equalsIgnoreCase(MediaType.APPLICATION_JSON_VALUE)){
return super.getInputStream();
}
//为空,直接返回
String json = new String(toByteArray(super.getInputStream()),super.getCharacterEncoding());
if(StringUtils.isEmpty(json)) {
ByteArrayInputStream bis = new ByteArrayInputStream("".getBytes(super.getCharacterEncoding()));
return new MyServletInputStream(bis);
}
log.info("inputStream convert before :"+json);
if(json.startsWith("{")&&json.endsWith("}")&&StringJsonUtils.isJsonObject(json)) {
Map<Object,Object> map=StringJsonUtils.jsonStringToMap(json);
log.info("jsonObject convert after :"+JSON.toJSONString(map));
ByteArrayInputStream bis = new ByteArrayInputStream(JSON.toJSONString(map).getBytes(super.getCharacterEncoding()));
return new MyServletInputStream(bis);
} else if(json.startsWith("[{")&&json.endsWith("}]")&&StringJsonUtils.isJsonArray(json)) {
List<Map<Object,Object>> list=StringJsonUtils.jsonStringToList(json);
log.info("jsonArray convert after :"+JSON.toJSONString(list));
ByteArrayInputStream bis = new ByteArrayInputStream(JSON.toJSONString(list).getBytes(super.getCharacterEncoding()));
return new MyServletInputStream(bis);
} else {
ByteArrayInputStream bis = new ByteArrayInputStream(json.trim().getBytes(super.getCharacterEncoding()));
return new MyServletInputStream(bis);
}
}
/**
* 读取流到字节数组
* @param input
* @return
* @throws IOException
*/
private byte[] toByteArray(InputStream input) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[1024 * 4];
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
}
return output.toByteArray();
}
/**
* 将parameter的值去除空格后重写回去
*/
private void modifyParameterValues(){
Set<String> set =params.keySet();
for (String key : set) {
String[] values = params.get(key);
values[0] = values[0].trim();
params.put(key, values);
}
}
/**
* 重写getParameter 参数从当前类中的map获取
* @param name
* @return
*/
@Override
public String getParameter(String name) {
String[]values = params.get(name);
if(values == null || values.length == 0) {
return null;
}
return values[0];
}
/**
* 重写getParameterValues
* @param name
* @return
*/
public String[] getParameterValues(String name) {
return params.get(name);
}
class MyServletInputStream extends ServletInputStream{
private ByteArrayInputStream bis;
private MyServletInputStream(ByteArrayInputStream bis){
this.bis=bis;
}
@Override
public boolean isFinished() {
return true;
}
@Override
public boolean isReady() {
return true;
}
@Override
public void setReadListener(ReadListener listener) {
}
@Override
public int read() throws IOException {
return bis.read();
}
}
}
package com.hyatt.temp.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
/**
* @author Hyatt
* @date 2019/11/21
*/
public class StringJsonUtils {
private static final Logger log = LoggerFactory.getLogger(StringJsonUtils.class);
/**
* jsonString 转换成map
* @param jsonString
*/
public static Map<Object, Object> jsonStringToMap(String jsonString) {
ObjectMapper mapper = new ObjectMapper();
Map<Object, Object> map = new HashMap<Object, Object>();
try {
map = mapper.readValue(jsonString, new TypeReference<HashMap<Object, Object>>() { });
Set<Object> set = map.keySet();
for (Object key : set) {
Object values = map.get(key);
if (values instanceof String) {
values = values.toString().trim();
}
map.put(key, values);
}
} catch (Exception e) {
log.error(e.getMessage(),e);
}
return map;
}
/**
* jsonString 转换成List<map>
* @param jsonString
*/
public static List<Map<Object, Object>> jsonStringToList(String jsonString) {
List<Map<Object, Object>> list = new ArrayList<>();
JSONArray jsonArray = JSON.parseArray(jsonString);
for (int i=0; i<jsonArray.size(); i++) {
list.add(jsonStringToMap(jsonArray.getJSONObject(i).toString()));
}
return list;
}
/**
* 判断是否是jsonArray
* @param s
* @return
*/
public static boolean isJsonArray(String s){
try {
JSON.parseArray(s);
} catch (Exception e){
return false;
}
return true;
}
/**
* 判断是否是jsonObject
* @param s
* @return
*/
public static boolean isJsonObject(String s){
try {
JSON.parseObject(s);
} catch (Exception e){
return false;
}
return true;
}
}