Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use filter to check request body parameters in Springboot

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly shows you "Springboot how to use filter to verify request body parameters", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "Springboot how to use filter to verify request body parameters" this article.

Use filter to verify @ Slf4jpublic class ParameterCheckServletRequestWrapper extends HttpServletRequestWrapper {private byte [] requestBody; private Charset charSet; public ParameterCheckServletRequestWrapper (HttpServletRequest request) {super (request); / / cache request body try {String requestBodyStr = getRequestPostStr (request); if (StringUtils.isNotBlank (requestBodyStr)) {JSONObject resultJson = JSONObject.fromObject (requestBodyStr.replace ("\", "'")) Object [] obj = resultJson.keySet (). ToArray (); for (Object o: obj) {resultJson.put (o, StringUtils.trimToNull (resultJson.get (o). ToString ();} requestBody = resultJson.toString (). GetBytes (charSet);} else {requestBody = new byte [0] } catch (IOException e) {log.error (", e);}} public String getRequestPostStr (HttpServletRequest request) throws IOException {String charSetStr = request.getCharacterEncoding (); if (charSetStr = = null) {charSetStr =" UTF-8 ";} charSet = Charset.forName (charSetStr) Return StreamUtils.copyToString (request.getInputStream (), charSet);} / * * rewrite getInputStream () * / @ Override public ServletInputStream getInputStream () {if (requestBody = = null) {requestBody = new byte [0];} final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream (requestBody) Return new ServletInputStream () {@ Override public boolean isFinished () {return false;} @ Override public boolean isReady () {return false @ Override public void setReadListener (ReadListener readListener) {} @ Override public int read () {return byteArrayInputStream.read ();}} } / * rewrite getReader () * / @ Override public BufferedReader getReader () {return new BufferedReader (new InputStreamReader (getInputStream ();}} public class ParameterCheckFilter implements Filter {@ Override public void init (FilterConfig filterConfig) throws ServletException {} @ Override public void doFilter (ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {ParameterCheckServletRequestWrapper myWrapper = new ParameterCheckServletRequestWrapper ((HttpServletRequest) servletRequest); filterChain.doFilter (myWrapper, servletResponse) } @ Override public void destroy () {} @ Configurationpublic class FilterConfig {@ Bean public FilterRegistrationBean authFilterRegistrationBean () {FilterRegistrationBean registrationBean = new FilterRegistrationBean (); registrationBean.setName ("parameterCheckFilter"); registrationBean.setFilter (new ParameterCheckFilter ()); registrationBean.setOrder (1); registrationBean.addUrlPatterns ("/ *"); return registrationBean;}} how to modify body parameters through filter

1 、 HttpServletRequestWrapper

2 、 filter

Steps

1. Create a new MyHttpServletRequestWrapper to inherit HttpServletRequestWrapper

2. Assign the passed body to your own body (as follows)

Package com.orisdom.modules.common.filter;import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONObject;import com.orisdom.modules.monitor.dto.input.MonitorPointQueryPara;import javax.servlet.ReadListener;import javax.servlet.ServletInputStream;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletRequestWrapper;import java.io.BufferedReader;import java.io.ByteArrayInputStream;import java.io.IOException;import java.io.InputStreamReader;import java.nio.charset.Charset / * * @ author xiaokang * @ description * @ date, 2021-6-11 10:56 * / public class MyHttpServletRequestWrapper extends HttpServletRequestWrapper {private String tempBody; public MyHttpServletRequestWrapper (HttpServletRequest request) {super (request); this.tempBody = getBody (request); System.out.println (tempBody) } / * get request body * @ param request request * @ return request body * / private String getBody (HttpServletRequest request) {try {ServletInputStream stream = request.getInputStream (); String read = ""; StringBuilder stringBuilder = new StringBuilder (); byte [] b = new byte [1024]; int lens =-1 While ((lens = stream.read (b)) > 0) {stringBuilder.append (new String (b, 0, lens));} return stringBuilder.toString ();} catch (IOException e) {throw new RuntimeException (e) }} / * get request body * @ return request body * / public String getBody () {MonitorPointQueryPara para = JSON.parseObject (tempBody, MonitorPointQueryPara.class); para.setName ("1232321321"); tempBody = JSONObject.toJSONString (para); return tempBody } / * this method needs to be overridden * @ return * @ throws IOException * / @ Override public BufferedReader getReader () throws IOException {return new BufferedReader (new InputStreamReader (getInputStream () } / * need to override this method * @ return * @ throws IOException * / @ Override public ServletInputStream getInputStream () throws IOException {/ / create byte array input stream final ByteArrayInputStream bais = new ByteArrayInputStream (tempBody.getBytes (Charset.defaultCharset () Return new ServletInputStream () {@ Override public boolean isFinished () {return false;} @ Override public boolean isReady () {return false @ Override public void setReadListener (ReadListener readListener) {} @ Override public int read () throws IOException {return bais.read ();};}}

1. New MyFilter inherits Filter

two。 Add @ WebFilter comment

3. Add @ ServletComponentScan to the startup class (as follows)

Package com.orisdom.modules.common.filter;import org.springframework.core.annotation.Order;import javax.servlet.*;import javax.servlet.annotation.WebFilter;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletRequestWrapper;import java.io.BufferedReader;import java.io.IOException;import java.util.HashMap;import java.util.Map / * @ author xiaokang * @ description * @ date, 2021-6-11 9:47 * / @ WebFilterpublic class MyFilter implements Filter {@ Override public void init (FilterConfig filterConfig) throws ServletException {} @ Override public void doFilter (ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {MyHttpServletRequestWrapper myHttpServletRequestWrapper = new MyHttpServletRequestWrapper ((HttpServletRequest) servletRequest); / / equivalent to myHttpServletRequestWrapper.getBody () / / self-defined MyHttpServletRequestWrapper filterChain.doFilter (myHttpServletRequestWrapper, servletResponse); System.out.println (11111111);} @ Override public void destroy () {}}

Before adding it.

After adding it.

The above is all the contents of the article "how Springboot uses filter to verify request body parameters". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report