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

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

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

解决办法

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值