快捷搜索: 王者荣耀 脱发

Spring 参数中包含空格

Spring解决Http请求参数 包含空格

  1. HttpGet请求 Spring中已经包含了默认的处理方式 ====> StringTrimmerEditor 构造器中默认的参数配置为True的情况下 空字符会被转换成NULL @ControllerAdvice public class GlobalControllerAdvice { @InitBinder public void initBinder(WebDataBinder binder){ binder.registerCustomEditor(String.class, new StringTrimmerEditor(false)); } } /** * Create a new StringTrimmerEditor. * @param emptyAsNull {@code true} if an empty String is to be * transformed into {@code null} */ public StringTrimmerEditor(boolean emptyAsNull) { this.charsToDelete = null; this.emptyAsNull = emptyAsNull; }
  2. HttpPost请求 解决方案是扩展Jackson中的ObjectMapper类,并重新配置到xml中 /** * 扩展反序列化Jackson的ObjectMapper类 * 实现字符串类型的参数Trim操作 * * 注意点: * 需要配置到Spring的类型转换器中 * <mvc:annotation-driven> */ public class CustomObjectMapper extends ObjectMapper { private static final long serialVersionUID = -7113628198861940948L; public CustomObjectMapper() { SimpleModule simpleModule = new SimpleModule(); // 注册对于String类型值对象的反序列化器 // 对于反序列化器直接new StdDeserializer的子类StdScalarDeserializer完成 simpleModule.addDeserializer(String.class, new StdScalarDeserializer<String>(String.class) { @Override public String deserialize(JsonParser jp, DeserializationContext context) throws IOException { return StringUtils.trim(jp.getValueAsString()); } }); // 调用ObjectMapper的registerModule方法添加扩展点 registerModule(simpleModule); } } <mvc:annotation-driven> <mvc:message-converters> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="objectMapper"> <bean class="******.CustomObjectMapper"> <property name="dateFormat"> <bean class="java.text.SimpleDateFormat"> <constructor-arg type="java.lang.String" value="yyyy-MM-dd HH:mm:ss"/> </bean> </property> </bean> </property> </bean> </mvc:message-converters> </mvc:annotation-driven>
经验分享 程序员 微信小程序 职场和发展