iis服务器助手广告广告
返回顶部
首页 > 资讯 > 精选 >如何用RequestBodyAdvice实现对Http请求非法字符过滤
  • 421
分享到

如何用RequestBodyAdvice实现对Http请求非法字符过滤

2023-06-20 12:06:47 421人浏览 安东尼
摘要

这篇文章主要介绍“如何用RequestBodyAdvice实现对Http请求非法字符过滤”,在日常操作中,相信很多人在如何用RequestBodyAdvice实现对Http请求非法字符过滤问题上存在疑惑,小编查阅了各式资料,整理出简单好用的

这篇文章主要介绍“如何用RequestBodyAdvice实现对Http请求非法字符过滤”,在日常操作中,相信很多人在如何用RequestBodyAdvice实现对Http请求非法字符过滤问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”如何用RequestBodyAdvice实现对Http请求非法字符过滤”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

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;@ControllerAdvice(basePackages = "com.niugang")public class MyRequestBodyAdvice implements RequestBodyAdvice {private final static Logger logger = LoggerFactory.getLogger(MyRequestBodyAdvice.class);  @Overridepublic boolean supports(MethodParameter methodParameter, Type targetType,Class<? extends HttpMessageConverter<?>> converterType) {return true;}@Overridepublic Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter,Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {return body;}  @Overridepublic 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; }}@Overridepublic 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");} @Overridepublic InputStream getBody() throws IOException {return body;} @Overridepublic 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。

测试

如何用RequestBodyAdvice实现对Http请求非法字符过滤

过滤后的数据

如何用RequestBodyAdvice实现对Http请求非法字符过滤

自定义RequestBodyAdvice过滤Json表情符号

@ControllerAdvice@Slf4jpublic class FilterEmojiRequestBodyAdvice implements RequestBodyAdvice {    @Override    public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {        Annotation[] annotations = methodParameter.getParameterAnnotations();        for (Annotation ann : annotations) {            Validated validatedAnn = AnnotationUtils.getAnnotation(ann, Validated.class);            if (validatedAnn != null || ann.annotationType().getSimpleName().startsWith("Valid")) {                return true;            }        }        return false;    }    @Override    public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) throws IOException {        return inputMessage;    }    @Override    public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {        try {            this.filterEmojiAfterBody(body);        } catch (Exception e) {            log.info("过滤表情异常:{}", e);        }        return body;    }    private void filterEmojiAfterBody(Object body) throws IllegalAccessException {        if (null != body) {            Field[] fields = ReflectUtil.getFields(body.getClass());            for (int i = 0; i < fields.length; i++) {                Field field = fields[i];                if (field.isAnnotationPresent(Valid.class)) {                    field.setAccessible(true);                    this.filterEmojiAfterBody(field.get(body));                }                if (field.isAnnotationPresent(FilterEmoji.class)) {                    field.setAccessible(true);                    Object value = field.get(body);                    if (value instanceof String) {                        String str = filterEmoji(value.toString());                        field.set(body, str);                    }                }            }        }    }    @Override    public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {        return body;    }        public static String filterEmoji(String source) {        if (StringUtils.isEmpty(source)) {            return "";        }        if (!containsEmoji(source)) {            return source;//如果不包含,直接返回        }        StringBuilder buf = new StringBuilder();        int len = source.length();        for (int i = 0; i < len; i++) {            char codePoint = source.charAt(i);            if (isNotEmojiCharacter(codePoint)) {                buf.append(codePoint);            }        }        return buf.toString().trim();    }        public static boolean containsEmoji(String source) {        if (StringUtils.isBlank(source)) {            return false;        }        int len = source.length();        for (int i = 0; i < len; i++) {            char codePoint = source.charAt(i);            if (!isNotEmojiCharacter(codePoint)) {                //判断到了这里表明,确认有表情字符                return true;            }        }        return false;    }        public static boolean isNotEmojiCharacter(char codePoint) {        return (codePoint == 0x0) ||                (codePoint == 0x9) ||                (codePoint == 0xA) ||                (codePoint == 0xD) ||                ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) ||                ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) ||                ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF));    }}

到此,关于“如何用RequestBodyAdvice实现对Http请求非法字符过滤”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注编程网网站,小编会继续努力为大家带来更多实用的文章!

--结束END--

本文标题: 如何用RequestBodyAdvice实现对Http请求非法字符过滤

本文链接: https://www.lsjlt.com/news/296505.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • 如何用RequestBodyAdvice实现对Http请求非法字符过滤
    这篇文章主要介绍“如何用RequestBodyAdvice实现对Http请求非法字符过滤”,在日常操作中,相信很多人在如何用RequestBodyAdvice实现对Http请求非法字符过滤问题上存在疑惑,小编查阅了各式资料,整理出简单好用的...
    99+
    2023-06-20
  • 使用RequestBodyAdvice实现对Http请求非法字符过滤
    RequestBodyAdvice对Http请求非法字符过滤 利用RequestBodyAdvice对HTTP请求参数放入body中的参数进行非法字符过滤。 要求:spring 4....
    99+
    2024-04-02
  • Angular如何通过HTTP Interceptor实现HTTP请求超时监控
    这篇文章主要介绍“Angular如何通过HTTP Interceptor实现HTTP请求超时监控”,在日常操作中,相信很多人在Angular如何通过HTTP Interceptor实现HTTP请求超时监控问题上存在疑惑,小编查阅了各式资料,...
    99+
    2023-07-02
  • Ajax如何实现返回字符串的过滤
    这篇文章主要介绍“Ajax如何实现返回字符串的过滤”,在日常操作中,相信很多人在Ajax如何实现返回字符串的过滤问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”Ajax如何实现...
    99+
    2024-04-02
  • 如何使用PHP实现同步HTTP请求并记录请求日志?
    PHP是一种流行的编程语言,它被广泛应用于Web开发领域。在Web开发中,我们通常需要使用HTTP请求与其他服务进行通信。本文将介绍如何使用PHP实现同步HTTP请求并记录请求日志,希望对你有所帮助。 一、PHP实现同步HTTP请求 在PH...
    99+
    2023-09-03
    同步 http 日志
  • Spring中的Http请求如何使用restTemplete实现
    这篇文章给大家介绍Spring中的Http请求如何使用restTemplete实现,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。使用Spring的restTemplete进行Http请求public class Res...
    99+
    2023-05-31
    resttemplete spring http请求
  • SpringBoot中如何使用@RestController注解实现http请求
    本篇内容主要讲解“SpringBoot中如何使用@RestController注解实现http请求”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“SpringBoot中如何使用@RestContr...
    99+
    2023-06-08
  • PHP编程算法:如何处理HTTP请求路径中的转义字符?
    在进行Web开发时,我们经常需要处理HTTP请求路径。然而,有时候这些路径中会包含一些特殊字符,例如空格、斜杠和问号等。为了避免出现问题,我们需要对这些特殊字符进行转义处理。本文将介绍如何在PHP中处理HTTP请求路径中的转义字符。 什...
    99+
    2023-08-18
    编程算法 http path
  • PHP编程算法:如何处理HTTP请求路径中的特殊字符?
    在Web开发中,处理HTTP请求路径中的特殊字符是非常常见的任务。这些特殊字符包括空格、斜杠、问号等等,如果不加以处理,可能会导致程序出错或安全问题。本文将介绍如何使用PHP编程算法来处理HTTP请求路径中的特殊字符。 一、什么是HTTP...
    99+
    2023-08-18
    编程算法 http path
  • .NET 6开发TodoList应用中如何实现DELETE请求与HTTP请求幂等性
    本篇文章为大家展示了.NET 6开发TodoList应用中如何实现DELETE请求与HTTP请求幂等性,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。需求先说明一下关于原本想要去更新的PAT...
    99+
    2023-06-22
  • SpringBoot基于过滤器和内存如何实现重复请求拦截功能
    这篇文章主要介绍了SpringBoot基于过滤器和内存如何实现重复请求拦截功能的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇SpringBoot基于过滤器和内存如何实现重复请求拦截功能文章都会有所收获,下面我们...
    99+
    2023-07-05
  • Spring Boot如何实现敏感词及特殊字符过滤处理
    这篇文章主要介绍“Spring Boot如何实现敏感词及特殊字符过滤处理”,在日常操作中,相信很多人在Spring Boot如何实现敏感词及特殊字符过滤处理问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”Spr...
    99+
    2023-06-20
  • PHP API编程算法:如何在HTTP请求中实现最佳实践?
    随着Web应用程序的不断发展,API已成为现代应用程序开发的重要组成部分。API的好处是显而易见的:它们提供了一种灵活的方式,使应用程序可以共享数据和功能。在本文中,我们将讨论如何在PHP中编写API,并实现HTTP请求的最佳实践。 HT...
    99+
    2023-07-02
    api 编程算法 http
  • 如何使用Java缓存HTTP请求日志?详解实现步骤
    当今互联网时代,HTTP请求日志已经成为了系统监控和性能优化的重要指标之一。为了更好地跟踪和分析系统运行状态,我们需要对HTTP请求日志进行缓存处理。本文将详细介绍如何使用Java缓存HTTP请求日志,包括实现步骤和演示代码。 一、缓存HT...
    99+
    2023-07-24
    http 日志 缓存
  • 你知道如何使用PHP编写优秀的API算法,以实现HTTP请求?
    PHP作为一种开源的脚本语言,被广泛应用于Web开发领域。PHP提供了强大的API开发支持,以便开发人员可以轻松地创建高效且易于使用的API。本文将介绍如何使用PHP编写优秀的API算法,以实现HTTP请求。 1.了解API 在开始介绍AP...
    99+
    2023-07-02
    api 编程算法 http
  • Java和Shell编程算法:如何实现HTTP请求的调试和优化?
    HTTP请求是现代Web应用程序的基础,它们可以用于从服务器获取数据,向服务器发送数据以及执行其他各种任务。在本文中,我们将讨论如何使用Java和Shell编程算法来实现HTTP请求的调试和优化。 Java编程实现HTTP请求 Jav...
    99+
    2023-06-03
    shell 编程算法 http
  • Java和Shell编程算法:如何实现HTTP请求的自动化测试?
    随着互联网的快速发展,HTTP协议已经成为了互联网上最常用的协议之一。在Web应用程序的开发过程中,HTTP请求是必不可少的一部分。而在Web应用程序的测试过程中,自动化测试已经成为了一种越来越流行的趋势。本文将介绍如何使用Java和Sh...
    99+
    2023-06-03
    shell 编程算法 http
  • 如何通过递归方法实现用json-diff渲染json字符串对比结果
    目录前言分析json-diff的结构用递归方法拼接json字符串字符串修改非数组对象修改数组对象修改总结前言 上一篇,对比了js-diff和json-diff,发现js-diff对比...
    99+
    2022-12-08
    json-diff渲染json字符串 json diff
  • 如何使用Python实现高效的HTTP请求和二维码生成?
    随着现代互联网的迅速发展,HTTP请求已成为了现代应用开发的重要组成部分之一。同时,二维码的应用也越来越广泛,如何快速、高效地使用Python实现HTTP请求和二维码生成,成为了许多开发者需要掌握的技能。 本文将介绍如何使用Python实现...
    99+
    2023-09-21
    http 二维码 并发
  • HTTP请求时,如何使用PHP实现同步性并记录日志?
    在Web开发中,我们经常需要使用HTTP请求来获取或提交数据。而在PHP中,我们可以使用cURL库来发送HTTP请求。但是,如果我们需要在一个脚本中发送多个HTTP请求,并且需要等待所有请求都完成后才能进行下一步操作,就需要使用同步性。同...
    99+
    2023-09-03
    同步 http 日志
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作