您现在的位置是:首页 > 正文

html前端对象字段去空格,springboot中前台传来的string字符串自动去除前后面的空格...

2024-02-01 03:09:48阅读 2

服务器后端接收前端传来的字符串带空格,如下

现在在后端接收时需要把字符串前后的空格去除掉。

解决办法

importcom.fasterxml.jackson.databind.DeserializationFeature;importcom.fasterxml.jackson.databind.ObjectMapper;importcom.fasterxml.jackson.databind.module.SimpleModule;importcom.xx.convertor.StringWithoutSpaceDeserializer;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.http.converter.HttpMessageConverter;importorg.springframework.http.converter.json.MappingJackson2HttpMessageConverter;importorg.springframework.web.servlet.config.annotation.WebMvcConfigurer;importjava.util.List;

@Configurationpublic class HttpMessageConvertor implementsWebMvcConfigurer {

@Overridepublic void extendMessageConverters(List>converters) {

converters.add(mappingJackson2HttpMessageConverter());

}

@BeanpublicMappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {

MappingJackson2HttpMessageConverter converter= newMappingJackson2HttpMessageConverter();

ObjectMapper mapper= newObjectMapper();

mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);

SimpleModule module= newSimpleModule();

module.addDeserializer(String.class, new StringWithoutSpaceDeserializer(String.class));

mapper.registerModule(module);

converter.setObjectMapper(mapper);returnconverter;

}

}

importcom.fasterxml.jackson.core.JsonParser;importcom.fasterxml.jackson.databind.DeserializationContext;importcom.fasterxml.jackson.databind.deser.std.StdDeserializer;importjava.io.IOException;public class StringWithoutSpaceDeserializer extends StdDeserializer{private static final long serialVersionUID = -6972065572263950443L;public StringWithoutSpaceDeserializer(Classvc) {super(vc);

}

@Overridepublic String deserialize(JsonParser p, DeserializationContext ctxt) throwsIOException {return p.getText() != null ? p.getText().trim() : null;

}

}

最终在服务端接收到数据如下:

其他参考

importcom.xxx.util.security.StringEscapeEditor;importorg.springframework.beans.propertyeditors.CustomDateEditor;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.format.support.DefaultFormattingConversionService;importorg.springframework.format.support.FormattingConversionService;importorg.springframework.web.bind.annotation.ControllerAdvice;importorg.springframework.web.bind.support.ConfigurableWebBindingInitializer;importjava.text.SimpleDateFormat;importjava.util.Date;/*** 自定义Web绑定初始化器

*@seeorg.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport 的getConfigurableWebBindingInitializer方法*/@Configuration

@ControllerAdvicepublic classWebBindingInitializerConfiguration {//final ConfigurableWebBindingInitializer initializer = new ConfigurableWebBindingInitializer();//final FormattingConversionService conversionService = new DefaultFormattingConversionService();//@Bean//public ConfigurableWebBindingInitializer configurableWebBindingInitializer(FormattingConversionService conversionService, Validator mvcValidator) {//ConfigurableWebBindingInitializer initializer = new ConfigurableWebBindingInitializer();//initializer.setConversionService(conversionService);//initializer.setValidator(mvcValidator);// //装配自定义属性编辑器//initializer.setPropertyEditorRegistrar(propertyEditorRegistry -> {// //PropertyEditors并不是线程安全的,对于每一个请求,我们都需要new一个PropertyEditor对象//propertyEditorRegistry.registerCustomEditor(String.class, new StringEscapeEditor());//propertyEditorRegistry.registerCustomEditor(Date.class, new DateEditor());//});//return initializer;//}

@BeanpublicConfigurableWebBindingInitializer getConfigurableWebBindingInitializer() {

ConfigurableWebBindingInitializer initializer= newConfigurableWebBindingInitializer();

FormattingConversionService conversionService= newDefaultFormattingConversionService();//we can add our custom converters and formatters//conversionService.addConverter(...);//conversionService.addFormatter(...);

initializer.setConversionService(conversionService);//we can set our custom validator//initializer.setValidator(....);//here we are setting a custom PropertyEditor

initializer.setPropertyEditorRegistrar(propertyEditorRegistry ->{

SimpleDateFormat dateFormatter= new SimpleDateFormat("yyyy-MM-dd");

propertyEditorRegistry.registerCustomEditor(Date.class,new CustomDateEditor(dateFormatter, true));

propertyEditorRegistry.registerCustomEditor(String.class,newStringEscapeEditor());

});returninitializer;

}

}

importorg.springframework.web.util.HtmlUtils;importorg.springframework.web.util.JavaScriptUtils;importjava.beans.PropertyEditorSupport;importjava.util.Objects;/***

* @description 与spring mvc的@InitBinder结合 用于防止XSS攻击*/

public class StringEscapeEditor extendsPropertyEditorSupport {/**转义HTML*/

private booleanescapeHTML;/**转义javascript*/

private booleanescapeJavaScript;/**是否将空字符串转换为null*/

private final booleanemptyAsNull;/**是否去掉前后空格*/

private final booleantrimmed;publicStringEscapeEditor() {this(true,true,false,false);

}public StringEscapeEditor(boolean escapeHTML, booleanescapeJavaScript) {this(true,true,escapeHTML,escapeJavaScript);

}public StringEscapeEditor(boolean emptyAsNull,boolean trimmed, boolean escapeHTML, booleanescapeJavaScript) {super();this.emptyAsNull =emptyAsNull;this.trimmed =trimmed;this.escapeHTML =escapeHTML;this.escapeJavaScript =escapeJavaScript;

}

@OverridepublicString getAsText() {

Object value=getValue();if(Objects.nonNull(value))

{returnvalue.toString();

}return value != null ? value.toString() : null;

}

@Overridepublic void setAsText(String text) throwsIllegalArgumentException {

String value=text;if (value == null || emptyAsNull &&text.isEmpty()) {//do nothing

} else if(trimmed) {

value=value.trim();

}if(escapeHTML) {//HTML转义(防止XSS攻击)//HtmlUtils.htmlEscape 默认的是ISO-8859-1编码格式,会将中文的某些符号进行转义。//如果不想让中文符号进行转义请使用UTF-8的编码格式。例如:HtmlUtils.htmlEscape(text, "UTF-8")

value =HtmlUtils.htmlEscape(value);

}if(escapeJavaScript) {//HTML转义(防止XSS攻击)//HtmlUtils.htmlEscape 默认的是ISO-8859-1编码格式,会将中文的某些符号进行转义。//如果不想让中文符号进行转义请使用UTF-8的编码格式。例如:HtmlUtils.htmlEscape(text.trim(), "UTF-8")

value =JavaScriptUtils.javaScriptEscape(value);

}

setValue(value);

}

}

参考来源:

https://stackoverflow.com/questions/39853350/spring-initbinder-register-multiple-custom-editor-string-class/39869054#39869054

https://stackoverflow.com/questions/42362490/how-to-auto-trim-strings-of-bean-object-in-spring-with-restful-api

https://stackoverflow.com/questions/25403676/initbinder-with-requestbody-escaping-xss-in-spring-3-2-4

https://stackoverflow.com/questions/57090437/spring-mvc-stringtrimmereditor-not-working

https://stackoverflow.com/questions/57134262/spring-stringtrimmereditor-not-trimming-the-whitespaces

https://stackoverflow.com/questions/25403676/initbinder-with-requestbody-escaping-xss-in-spring-3-2-4/25405385#25405385

https://stackoverflow.com/questions/50297719/using-initbinder-with-command-objects

网站文章

  • java ftl转pdf_FreeMarker(二):利用FreeMarker转pdf

    java ftl转pdf_FreeMarker(二):利用FreeMarker转pdf

    1. 设计需求订票成功后,生成一个pdf 文件,用户打印入场票,门票大致如下所示: 2. 设计思想1). 使用FreeMarker 转换 ftl(就是FreeMarker 魔板文件),生成HTML2)...

    2024-02-01 03:09:18
  • BootStrap 多个tab页面 保存提交后停留在操作tab页或者指定tab页

    jQ+ Bootstrap 动态控制tab页面切换最近在做一个功能,一个页面包含多个tab页签,每一个tab页面都有保存和提交按钮功能,现在是希望在某个tab页面点击保存或者提交按钮提交表单后,重新加...

    2024-02-01 03:09:11
  • 手把手教你搭建自己的git+gerrit代码评审服务器

    手把手教你搭建自己的git+gerrit代码评审服务器

    你可能遇到过这样的问题,不知道如何管理自己的代码。自己开发的代码,过了几天,忘记修改了什么,忘了上次改到哪了,代码突然找不到了等等,甚至容易消磨自己的耐心,成就感不高。今天就教你用git+gerrit...

    2024-02-01 03:09:04
  • 每日面试题(三)----深拷贝

    每日面试题(三)----深拷贝

    深拷贝与浅拷贝

    2024-02-01 03:08:35
  • 离线安装docker

    离线安装docker

    在/usr/lib/systemd/system/目录下,创建docker.service文件:sudo touch /usr/lib/systemd/system/docker.service。编辑...

    2024-02-01 03:08:19
  • java数据结构和算法

    java数据结构和算法

    java数据结构与算法

    2024-02-01 03:08:11
  • 多标签mAP解释和计算

    多标签mAP计算

    2024-02-01 03:08:04
  • 【VMware】VMware 虚拟机使用笔记

    【VMware】VMware 虚拟机使用笔记

    目录 共享文件夹配置 VMware问题记录 VMware安装出错error 1021 Vmware虚拟机Ubuntu未发现WiFi适配器解决方案汇总 添加域名解析服务器 虚拟机没有网络(不显示网络图标)解决方法 虚拟机添加新硬盘的方法 共享文件夹配置 在vmware上操作: 1.1打开 虚拟机 --> 设置 1.2在 「虚拟...

    2024-02-01 03:07:35
  • mysql 全文检索 demo

    mysql 全文检索 demo

    mysql5.6.7之后开始支持中文全文检索 模拟插入点数据,是的 存储过程。

    2024-02-01 03:07:29
  • [033] 微信公众帐号开发教程第9篇-QQ表情的发送与接收

    [033] 微信公众帐号开发教程第9篇-QQ表情的发送与接收

    我想大家对QQ表情一定不会陌生,一个个小头像极大丰富了聊天的乐趣,使得聊天不再是简单的文字叙述,还能够配上喜、怒、哀、乐等表达人物心情的小图片。本文重点要介绍的内容就是如何在微信公众平台使用QQ表情,即在微信公众帐号开发模式下,如何发送QQ表情给用户,以及如何识别用户发来的是QQ表情。 QQ表情代码表 首先需要明确的是:QQ表情虽然呈现为一张张动态的表情图片,但在微信公众平台的消息接口中却...

    2024-02-01 03:07:23