一、配置
-
定义正则表达式
/** * 正则静态常量 */ public interface PatternConstant { /** * 匹配表情符号 **/ Pattern EMOJI = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]"); }
-
RequestBody 中 JSON 对象参数
@Configuration public class JacksonConfig { @Bean public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() { return jacksonMapper -> jacksonMapper.deserializerByType(String.class, new StdScalarDeserializer<String>(String.class) { @Override public String deserialize(JsonParser jsonParser, DeserializationContext ctx) throws IOException { String text = jsonParser.getValueAsString(); if (text == null) { return null; } Matcher matcher = PatternConstant.EMOJI.matcher(text); return matcher.replaceAll("").trim(); } }); } }
-
URL 和 FORM 表单中的参数
/** * 去除请求参数中的表情符号和首尾空白字符 */ @ControllerAdvice public class WebMvcAutoTrimEmojiConfig { @InitBinder public void initWebDataBinder(WebDataBinder binder) { //当值为" "时,是否转换为null StringTrimmerEditor propertyEditor = new StringTrimEmojiEditor(true); // 为 String 类对象注册编辑器 binder.registerCustomEditor(String.class, propertyEditor); } public static class StringTrimEmojiEditor extends PropertyEditorSupport { /** * 当值为" "时,是否转换为null */ private final boolean emptyAsNull; public StringTrimEmojiEditor(boolean emptyAsNull) { this.emptyAsNull = emptyAsNull; } @Override public void setAsText(@Nullable String text) { if (text == null) { setValue(null); } else { Matcher matcher = PatternConstant.EMOJI.matcher(text); String value = matcher.replaceAll("").trim(); if (this.emptyAsNull && value.isEmpty()) { super.setValue(null); } else { super.setValue(value); } } } @Override public String getAsText() { Object value = getValue(); return (value != null ? value.toString() : ""); } } }
提示: 如果只去除首尾空白字符可以直接使用 org.springframework.beans.propertyeditors.StringTrimmerEditor
二、测试
@RestController
@RequestMapping(value = "/")
public class SpringTrimController {
@GetMapping("/url")
public String urlParam(String name) {
return name;
}
@PostMapping("/form")
public User formParam(User user) {
return user;
}
@PostMapping(value = "/body")
public User bodyParam(@RequestBody User user) {
return user;
}
}
网友评论