您好,登錄后才能下訂單哦!
本篇內容主要講解“springboot清除字符串前后空格的方法”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“springboot清除字符串前后空格的方法”吧!
springboot清除字符串前后空格與防xss攻擊
一、查看WebMvcAutoConfiguration.class中的方法源碼
二、自定義屬性編輯器
三、創建WebBindingInitializerConfiguration類
springboot去除參數中前后空格說明
一、 需求
二、 解決方法
三、 完美解決
protected ConfigurableWebBindingInitializer getConfigurableWebBindingInitializer() { try { //從容器中獲取 return (ConfigurableWebBindingInitializer)this.beanFactory.getBean(ConfigurableWebBindingInitializer.class); } catch (NoSuchBeanDefinitionException ex) { return super.getConfigurableWebBindingInitializer(); }
可以發現ConfigurableWebBindingInitializer是從容器(beanFactory)中獲取到的,所以我們可以配置一個
ConfigurableWebBindingInitializer來替換默認的,只需要在容器中添加一個我們自定義的轉換器即可。
當我們創建了自己的ConfigurableWebBindingInitializer這個Bean,Spring boot就會自動使用它來配置Spring MVC實現參數的類型轉換。
/** * * @description 與spring mvc的@InitBinder結合 用于防止XSS攻擊 */ class StringEscapeEditor extends PropertyEditorSupport { /** 轉義HTML */ private boolean escapeHTML; /** 轉義javascript */ private boolean escapeJavaScript; /** 是否將空字符串轉換為null */ private final boolean emptyAsNull; /** 是否去掉前后空格 */ private final boolean trimmed; public StringEscapeEditor() { this(true,true,false,true); } public StringEscapeEditor(boolean escapeHTML, boolean escapeJavaScript) { this(true,true,escapeHTML,escapeJavaScript); } public StringEscapeEditor(boolean emptyAsNull,boolean trimmed, boolean escapeHTML, boolean escapeJavaScript) { super(); this.emptyAsNull = emptyAsNull; this.trimmed = trimmed; this.escapeHTML = escapeHTML; this.escapeJavaScript = escapeJavaScript; } @Override public String getAsText() { Object value = getValue(); if(Objects.nonNull(value)) { return value.toString(); } return value != null ? value.toString() : null; } @Override public void setAsText(String text) throws IllegalArgumentException { 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, "UTF-8"); } if (escapeJavaScript) { //javascript轉義(防止XSS攻擊) value = JavaScriptUtils.javaScriptEscape(value); } setValue(value); } }
加上@Bean注解,交給spring容器管理。
@Configuration public class WebBindingInitializerConfiguration { @Bean public ConfigurableWebBindingInitializer getConfigurableWebBindingInitializer() { ConfigurableWebBindingInitializer initializer = new ConfigurableWebBindingInitializer(); FormattingConversionService conversionService = new DefaultFormattingConversionService(); //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 -> { propertyEditorRegistry.registerCustomEditor(String.class, new StringEscapeEditor()); }); return initializer; } }
使用SpringBoot使用過濾器去除@RequestBody參數兩端的空格;一般我們去普通的請求我們都會對請求參數進行驗證。
Java也提供了@notNull和@notBlank這種驗證方式,但是對@RequestBody 這種只能驗證是不是非空,對數據兩端的空格未進行處理,同時大家也不想遍歷一遍參數然后再處理再封裝到對象中,正好項目中有這個需要,所以就參考別的做了Post請求中針對application/json格式的有@RequestBody注解的參數進行了去空格處理
2.1 新建一個過濾器
@Component @WebFilter(urlPatterns = "/**", filterName = "ParamsFilter", dispatcherTypes = DispatcherType.REQUEST) public class ParamsFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { ParameterRequestWrapper parmsRequest = new ParameterRequestWrapper((HttpServletRequest) request); chain.doFilter(parmsRequest, response); } @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void destroy() { } }
2.2 實現ParameterRequestWrapper
import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.ReadListener; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import com.alibaba.fastjson.JSON; /** * @author : * @description * @date : 2021/4/22 */ public class ParameterRequestWrapper extends HttpServletRequestWrapper { private Map<String , String[]> params = new HashMap<>(); public ParameterRequestWrapper(HttpServletRequest request) { super(request); Map<String, String[]> requestMap=request.getParameterMap(); this.params.putAll(requestMap); this.modifyParameterValues(); } @Override public ServletInputStream getInputStream() throws IOException { if(!super.getHeader(HttpHeaders.CONTENT_TYPE).equalsIgnoreCase(MediaType.APPLICATION_JSON_VALUE)){ return super.getInputStream(); } String json = IOUtils.toString(super.getInputStream(), "utf-8"); if (StringUtils.isEmpty(json)) { return super.getInputStream(); } Map<String,Object> map= jsonStringToMap(json); ByteArrayInputStream bis = new ByteArrayInputStream(JSON.toJSONString(map).getBytes("utf-8")); return new MyServletInputStream(bis); } public void modifyParameterValues(){ Set<String> set = params.keySet(); Iterator<String> it = set.iterator(); while(it.hasNext()){ String key= it.next(); String[] values = params.get(key); values[0] = values[0].trim(); params.put(key, values); } } @Override public String getParameter(String name) { String[]values = params.get(name); if(values == null || values.length == 0) { return null; } return values[0]; } @Override public String[] getParameterValues(String name) { return params.get(name); } class MyServletInputStream extends ServletInputStream { private ByteArrayInputStream bis; public MyServletInputStream(ByteArrayInputStream bis){ this.bis=bis; } @Override public boolean isFinished() { return true; } @Override public boolean isReady() { return true; } @Override public void setReadListener(ReadListener listener) { } @Override public int read(){ return bis.read(); } } public static Map<String, Object> jsonStringToMap(String jsonString) { Map<String, Object> map = new HashMap<>(); JSONObject jsonObject = JSONObject.parseObject(jsonString); for (Object k : jsonObject.keySet()) { Object o = jsonObject.get(k); if (o instanceof JSONArray) { List<Map<String, Object>> list = new ArrayList<>(); Iterator<Object> it = ((JSONArray) o).iterator(); while (it.hasNext()) { Object obj = it.next(); list.add(jsonStringToMap(obj.toString())); } map.put(k.toString(), list); } else if (o instanceof JSONObject) { map.put(k.toString(), jsonStringToMap(o.toString())); } else { if (o instanceof String) { map.put(k.toString(), o.toString().trim()); } else { map.put(k.toString(), o); } } } return map; } }
參數前后空格完美去除!
到此,相信大家對“springboot清除字符串前后空格的方法”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。