In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article introduces the relevant knowledge of "filtering methods of Springboot sensitive words and special characters". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
The technology uses SpringBoot, and the request method is mainly POST, which is delivered to the tester for testing. The tester searches all kinds of special characters in the fuzzy search module, so that sensitive words and special characters are stored in the database. Then how to implement springboot sensitive word filtering and special character filtering?
@ ControllerAdvice (basePackages = "com.my")
To process the data submitted by the user.
The following is the sample code, which does not affect the functional implementation of the author's summary table: / * * @ author Ryan* @ date 2019-4-25 18:41*/@ControllerAdvice (basePackages = "com.ytkj") public class EscapeSensitiveWordFilter implements RequestBodyAdvice {@ Overridepublic boolean supports (MethodParameter methodParameter, Type type, Class > aClass) {return true;} @ Overridepublic HttpInputMessage beforeBodyRead (HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class > converterType) throws IOException {return inputMessage } @ Overridepublic Object afterBodyRead (Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class > aClass) {if (o! = null) {SensitiveWordUtils.apply (o);} return o;} @ Overridepublic Object handleEmptyBody (Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class > aClass) {return o;}}
Since we mainly deal with the submitted data, the main entry is SensitiveWordUtils.apply (o); here the "Object" parameter, that is, the entity in our Controller method parameter, is typed @ RequestBody. We can just use some means to deal with it directly here.
The method here can only use reflection (if the reader has any good plan, please let me know).
1. String substitution
two。 Custom throw runtime exception
Another advantage of this is that sensitive words can be managed uniformly here.
If you use replaceAll, unified management is more difficult.
Finally, the author puts his own reflection below for reference only, and the sensitive word replacement part writes a "test" as the mark to replace the entry.
Welcome bosses from all walks of life to straighten up!
Import java.lang.reflect.Field;import java.util.ArrayList;import java.util.Arrays;import java.util.List;import java.util.Map;/*** @ author Ryan* @ date 2019-4-26 12:40*/public class SensitiveWordUtils {/ * * @ param result* @ return*/public static Object apply (Object result) {if (result = = null) {return null;} objectParse (result); return result } / * * @ param obj*/public static void objectParse (Object obj) {List allField = findAllField (obj); for (Field field: allField) {field.setAccessible (true); Class typeClazz = field.getType (); matchFieldType (obj, field, typeClazz);} public static List findAllField (Object object) {List result = new ArrayList (); Class clazz = object.getClass (); while (true) {clazz = clazz.getSuperclass (); if (clazz = = Object.class) {break;} Field [] declaredFields = clazz.getDeclaredFields () Result.addAll (Arrays.asList (declaredFields));} return result;} / * * @ param obj* @ param field* @ param clazz*/public static void matchFieldType (Object obj, Field field, T clazz) {try {T param = (T) field.get (obj); if (param = = null) {return;} if (clazz = List.class) {List p = (List) param;for (Object o: P) {objectParse (o) }} else if (clazz = = String.class) {setValue (obj, field, "test");} else if (clazz = = Map.class) {Map map = (Map) param;for (Object o: map.keySet ()) {objectParse (o);}} catch (IllegalAccessException e) {e.printStackTrace () } / * @ param object* @ param field* @ param param* @ throws IllegalAccessException*/public static void setValue (Object object, Field field, Object param) throws IllegalAccessException {if (! field.isAccessible ()) {throw new IllegalAccessException ("modify the field fail.");} field.set (object, param);}}
SensitiveWordUtils here also has a lot of optimization points, I do not have here at present just look at the effect, the writing is very rough, hope God do not spray.
Readers do it on their own, and I'll talk about the optimization point:
1. Cache Field or methodName; of String.class type of object is cached when it is loaded for the first time; does it feel much more refreshing when it is put into ConcurrentHashMap?
two。 Filter out the Field of String type, and other types are considered as appropriate
3. Wait for the concubine to think again.
Spring Boot uniform sensitive words filter demo
Processing before object serialization
For example, springframework Framework (responseBody) json format:
Org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyAdviceChain#beforeBodyWrite
Object data is converted in the.
@ ControllerAdvice@Slf4jpublic class ShanDongShengYuHandler implements ResponseBodyAdvice {@ Autowiredprivate ObjectMapper objectMapper;@Overridepublic boolean supports (MethodParameter returnType, Class converterType) {return true;} @ Overridepublic Object beforeBodyWrite (Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {ResponseData d = new ResponseData (); sensitiveHidden (body); d.setData (body); return d } / * only supports sensitive word filtering for custom type data, considering recursive performance * / private void sensitiveHidden (Object body) {if (body==null | | StringUtils.isBlank (body.getClass (). GetName ()) |! body.getClass (). GetName (). Contains ("Shandong") {return;} Field [] declaredFields = body.getClass (). GetDeclaredFields (); for (Field declaredField: declaredFields) {SensitiveWorldHidden annotation = declaredField.getAnnotation (SensitiveWorldHidden.class) Log.warn ("[annotation type] {}", annotation); try {declaredField.setAccessible (true); Object o = declaredField.get (body); if (annotation! = null) {String content = objectMapper.writeValueAsString (o); content = content.replace ("garbage", "*"); Object replaced = objectMapper.readValue (content, o.getClass (); declaredField.set (body, replaced);} else {sensitiveHidden (o);} catch (IllegalAccessException e) {e.printStackTrace () } catch (JsonProcessingException e) {e.printStackTrace ();} catch (IOException e) {e.printStackTrace ();} "methods for filtering Springboot sensitive words and special characters" ends here. Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.