利用RequestBodyAdvice对Http请求非法字符过滤

利用RequestBodyAdvice对HTTP请求参数放入body中的参数进行非法字符过滤。

 

  • 要求:spring 4.2+

额外的pom.xml


<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>

           <dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.44</version>
</dependency>
  • 代码
package com.niugang.controller;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
/**
 * RequestBodyAdvice:解释
 * 允许在将请求的主体读取和转换成一个对象之前对请求进行自定义,
 * 并允许在将其传递到控制器方法作为一个@RequestBody或HttpEntity方法参数之前处理结果对象。
 * 
 * @author niugang
 *
 */
@ControllerAdvice(basePackages = "com.niugang")
public class MyRequestBodyAdvice implements RequestBodyAdvice {
private final static Logger logger = LoggerFactory.getLogger(MyRequestBodyAdvice.class);


@Override
public boolean supports(MethodParameter methodParameter, Type targetType,
Class<? extends HttpMessageConverter<?>> converterType) {
return true;
}
     @Override
public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter,
Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
return body;
}


@Override
public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
Class<? extends HttpMessageConverter<?>> converterType) throws IOException {


try {
return new MyHttpInputMessage(inputMessage);
} catch (Exception e) {
e.printStackTrace();
return inputMessage;


}
}
@Override
public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
Class<? extends HttpMessageConverter<?>> converterType) {
return body;
}


class MyHttpInputMessage implements HttpInputMessage {
private HttpHeaders headers;
private InputStream body;
              @SuppressWarnings("unchecked")
public MyHttpInputMessage(HttpInputMessage inputMessage) throws Exception {
String string = IOUtils.toString(inputMessage.getBody(), "UTF-8");
Map<String, Object> mapJson = (Map<String, Object>) JSON.parseObject(string, Map.class);
Map<String, Object> map = new HashMap<String, Object>();
Set<Entry<String, Object>> entrySet = mapJson.entrySet();
for (Entry<String, Object> entry : entrySet) {
String key = entry.getKey();
Object objValue = entry.getValue();
                            if (objValue instanceof String) {
String value = objValue.toString();
map.put(key, filterDangerString(value));
} else { // 针对结合的处理
@SuppressWarnings("rawtypes")
List<HashMap> parseArray = JSONArray.parseArray(objValue.toString(), HashMap.class);
List<Map<String, Object>> listMap = new ArrayList<Map<String, Object>>();
for (Map<String, Object> innerMap : parseArray) {
Map<String, Object> childrenMap = new HashMap<String, Object>();
Set<Entry<String, Object>> elseEntrySet = innerMap.entrySet();
for (Entry<String, Object> en : elseEntrySet) {
                                                        String innerKey = en.getKey();
Object innerObj = en.getValue();
if (innerObj instanceof String) {
String value = innerObj.toString();
childrenMap.put(innerKey, filterDangerString(value));
}


}
listMap.add(childrenMap);
}
map.put(key, listMap);
}
}
this.headers = inputMessage.getHeaders();
this.body = IOUtils.toInputStream(JSON.toJSONString(map), "UTF-8");
}

@Override
public InputStream getBody() throws IOException {
return body;
}

@Override
public HttpHeaders getHeaders() {
return headers;
}
}
       private String filterDangerString(String value) {
if (value == null) {
return null;
}
value = value.replaceAll("\\|", "");
value = value.replaceAll("&", "");
value = value.replaceAll(";", "");
value = value.replaceAll("@", "");
value = value.replaceAll("'", "");
value = value.replaceAll("\\'", "");
value = value.replaceAll("<", "");
value = value.replaceAll("-", "");
value = value.replaceAll(">", "");
value = value.replaceAll("\\(", "");
value = value.replaceAll("\\)", "");
value = value.replaceAll("\\+", "");
value = value.replaceAll("\r", "");
value = value.replaceAll("\n", "");
value = value.replaceAll("script", "");
value = value.replaceAll("select", "");
value = value.replaceAll("\"", "");
value = value.replaceAll(">", "");
value = value.replaceAll("<", "");
value = value.replaceAll("=", "");
value = value.replaceAll("/", "");
return value;
}
}

对于以上的配置Controller接收参数需要加@RequestBody。

测试

   

 

过滤后的数据

   

   

微信公众号

                          

 

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
Spring框架中,如果我们想要对一个GET请求请求体进行处理,则可以通过实现`RequestBodyAdvice`接口来实现。 `RequestBodyAdvice`接口有四个方法: 1. `supports(MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType)`:用于判断支持哪些请求体的处理。如果返回`true`,则会调用后面三个方法对请求体进行处理;否则不会进行处理。 2. `beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType)`:在请求体读取之前调用,用于对请求体进行处理。 3. `afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType)`:在请求体读取之后调用,用于对请求体进行处理。 4. `handleError(HttpMessageNotReadableException ex, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType)`:在读取请求体出现异常时调用。 需要注意的是,`RequestBodyAdvice`只对请求体为JSON格式的GET请求有效,对于其他格式的请求体(如form-data),需要使用其他方式进行处理。 以下是一个使用`RequestBodyAdvice`处理请求体的示例: ```java @ControllerAdvice public class CustomRequestBodyAdvice implements RequestBodyAdvice { @Override public boolean supports(MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) { return methodParameter.getMethod().getName().equals("getUserInfo") && type.equals(UserInfo.class); } @Override public Object beforeBodyRead(HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) throws IOException, HttpMessageNotReadableException { String requestBody = StreamUtils.copyToString(httpInputMessage.getBody(), StandardCharsets.UTF_8); JSONObject jsonObject = JSON.parseObject(requestBody); UserInfo userInfo = new UserInfo(); userInfo.setUserName(jsonObject.getString("userName")); userInfo.setPassword(jsonObject.getString("password")); return userInfo; } @Override public Object afterBodyRead(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) { return o; } @Override public Object handleEmptyBody(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) { return o; } @Override public void handleError(HttpMessageNotReadableException httpMessageNotReadableException, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) throws IOException { throw httpMessageNotReadableException; } } ``` 在以上示例中,我们使用`supports`方法判断请求体是否为`UserInfo`类型,如果是则调用`beforeBodyRead`方法对请求体进行处理,将JSON格式的请求体转换成`UserInfo`对象。最后,我们返回处理后的`UserInfo`对象即可。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值