您好,登錄后才能下訂單哦!
本篇內容介紹了“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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。