In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "how interceptors get body data in HttpServletRequest". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how interceptors get body data in HttpServletRequest".
First, problems
By getting the json data in request in the interceptor, we can check and rewrite the parameters. The problem is that the parameters can only be obtained once in the interceptor, and then the data cannot be obtained in the controller layer, indicating that body is empty.
After looking up information on the Internet, it is found that the input stream of request can only be read once, so why?
That's because the stream corresponds to data, which is stored in memory, and some are partially stored in memory. Read marks the current location (mark position) once at a time, and the second time read continues to read (copy) the data from the marked location. So that's why I read it once and the second time is empty. How to make it not empty? As long as the pos in the inputstream becomes 0, you can rewrite and read the data in the current memory. There is a method public void reset () in javaAPI that resets pos to the starting position, but not all IO read streams can call this method! ServletInputStream cannot call the reset method, which results in only one call to getInputStream () 2. Solution
HttpServletRequestWrapper is a wrapper class for httpServletRequest
A new class inherits HttpServletRequestWrapper implementation to decorate httpServletRequest and is used to obtain body data
Public class BodyReaderHttpServletRequestWrapper extends HttpServletRequestWrapper {private final byte [] body; private String bodyStr; public BodyReaderHttpServletRequestWrapper (HttpServletRequest request) throws IOException {super (request); String bodyString = getBodyString (request); body = bodyString.getBytes (Charset.forName ("UTF-8")); bodyStr=bodyString;} public String getBodyStr () {return bodyStr;} @ Override public ServletInputStream getInputStream () throws IOException {final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream (body) Return new ServletInputStream () {@ Override public int read () throws IOException {return byteArrayInputStream.read ();} @ Override public boolean isFinished () {return false;} @ Override public boolean isReady () {return false } @ Override public void setReadListener (ReadListener readListener) {}};} public String getBodyString (HttpServletRequest request) throws IOException {StringBuilder sb = new StringBuilder (); InputStream inputStream = null; BufferedReader reader = null; try {inputStream = request.getInputStream () Reader = new BufferedReader (new InputStreamReader (inputStream, Charset.forName ("UTF-8")); char [] bodyCharBuffer = new char [1024]; int len = 0; while ((len = reader.read (bodyCharBuffer))! =-1) {sb.append (bodyCharBuffer (bodyCharBuffer, 0, len)) }} catch (IOException e) {e.printStackTrace ();} finally {if (inputStream! = null) {try {inputStream.close ();} catch (IOException e) {e.printStackTrace () } if (reader! = null) {try {reader.close ();} catch (IOException e) {e.printStackTrace ();} return sb.toString ();}}
Create a new filter to convert the incoming httpServletRequest
@ WebFilter (filterName = "httpServletRequestWrapperFilter", urlPatterns = {"/ *"}) public class HttpServletRequestWrapperFilter implements Filter {@ Override public void init (FilterConfig filterConfig) throws ServletException {} @ Override public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {ServletRequest requestWrapper = null; if (request instanceof HttpServletRequest) {HttpServletRequest httpRequest = (HttpServletRequest) request / / wrap request when encountered with post method String methodType = httpRequest.getMethod (); if ("POST" .equals (methodType)) {requestWrapper = new BodyReaderHttpServletRequestWrapper ((HttpServletRequest) request);} if (null = = requestWrapper) {chain.doFilter (request, response) } else {chain.doFilter (requestWrapper, response);} @ Override public void destroy () {}}
Finally, the body data in request can be obtained in the interceptor.
If (request instanceof BodyReaderHttpServletRequestWrapper) {System.out.println ((BodyReaderHttpServletRequestWrapper) request) .getBodyStr ();}
After testing, it is found that it does not affect the controller layer to obtain body data.
Why do you need to convert the packaging of httpServletRequest in filter, and why not just wrap it in the interceptor?
The biggest difference between Filter and Interceptor is that filters can wrap Request and Response, and interceptors cannot describe the flow of interceptors and filters in code like this: interceptor: void run () {Request request = new Request (); preHandle (request); service (request);} preHandler (Request request) {request = new RequestWrapper (request) / / modifying the reference of Request here will not affect the request} filter void run () {Request request = new Request (); doFilter (request);} doFilter (Request request) {request = new RequestWrapper (request) of the service method; / / modifying the reference of Request here will affect the request service (request) of the service method } Thank you for your reading. The above is the content of "how interceptors get body data in HttpServletRequest". After the study of this article, I believe you have a deeper understanding of how interceptors obtain body data in HttpServletRequest, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.