本篇内容介绍了“Springboot怎么去掉前后的空格”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
自定义转换器实现参数去空格
1.自定义转换器类
2.将转换器交给spring容器处理
SpringBoot请求参数过滤空格
1、参数修改SpaceHttpServletRequestWrapper
2、空格过滤器
3、过滤器初始化
实现Converter<S, T>类,重写convert()方法,直接上代码。
/** * 自定义转换器 * 去掉前后空格 * @author liuy * @version 2018年11月13日 */ public class CustomConverter implements Converter<String, String>{ @Override public String convert(String source) { try { if(source != null){ source = source.trim(); if(!"".equals(source)){ return source; } } } catch (Exception e) { e.printStackTrace(); } return null; } }
@Configuration public class SpringdataConvert { @Autowired private RequestMappingHandlerAdapter requestMappingHandlerAdapter; @PostConstruct public void addConversionConfig(){ ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) requestMappingHandlerAdapter.getWebBindingInitializer(); if(initializer.getConversionService()!=null){ GenericConversionService genericConversionService =(GenericConversionService) initializer.getConversionService(); genericConversionService.addConverter(new CustomConverter()); } } }
public class SpaceHttpServletRequestWrapper extends HttpServletRequestWrapper { public SpaceHttpServletRequestWrapper(HttpServletRequest servletRequest) { super(servletRequest); } @Override public String[] getParameterValues(String parameter) { String[] values = super.getParameterValues(parameter); if (values == null) { return new String[0]; } int count = values.length; String[] encodedValues = new String[count]; for (int i = 0; i < count; i++) { encodedValues[i] = values[i].trim(); } return encodedValues; } @Override public String getParameter(String parameter) { String value = super.getParameter(parameter); if (value == null) { return null; } return value.trim(); } }
public class SpaceFilter implements Filter { private FilterConfig filterConfig; @Override public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig = filterConfig; } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { filterChain.doFilter(new SpaceHttpServletRequestWrapper( (HttpServletRequest) servletRequest), servletResponse); } @Override public void destroy() { this.filterConfig = null; } }
@Configuration public class WebMvcConfiguration implements WebMvcConfigurer { @Bean public FilterRegistrationBean spaceFilter() { FilterRegistrationBean fitler = new FilterRegistrationBean(); fitler.setFilter(new SpaceFilter()); fitler.addUrlPatterns("/*"); fitler.setName("SpaceFilter"); fitler.setDispatcherTypes(DispatcherType.REQUEST); return fitler; } }
“Springboot怎么去掉前后的空格”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。