In the development process of the project, request garbled is a very common thing, we hereby record how to deal with the request and response Chinese garbled problem, although the problem is easy to deal with, but sometimes one does not pay attention to a long time can not solve.
HttpServletRequest HTTP request Chinese characters are garbled
When Chinese garbled appears in the reading request parameters, first determine whether the parameters passed are garbled, and then continue to process, otherwise it will be very uncomfortable to find that the front-end parameters are garbled.
For example, HTTP Header parameters do not support Chinese characters. Therefore, transcodes are required when Chinese characters are transmitted.
JAVA: urldecoder.decode (” to parse string “, “UTF-8”)
When it is determined that the background read is garbled, the processing is very simple to set the request encoding.
request.setCharacterEncoding("UTF-8");
Copy the code
Ps: Note that this method does not take effect if it is set after reading the request parameters or after the getReader() method is called.
Ps: To Download the official document, click the method through IDEA, enter the method, and then click Download Sources in the upper right corner.
Ps: Springboot Controller request parameter Chinese garbled this article is a very special example, the reason for garbled and boot file encoding has a relationship.
HttpServletResponse Response Chinese garbled characters processing
When the data returned to the front-end is garbled, the breakpoint is used to determine whether the data is garbled when encapsulated in HttpServletResponse, and then to see what the encoding is when the request is returned.
If there is no garble, or if the encoding returned is not correct, it is basically handled by setting the HttpServletResponse encoding.
response.setCharacterEncoding("UTF-8");
Copy the code
Ps: Note that this method does not take effect if set after the getWriter() method is called, according to the official documentation.
Unified processing mode
** @author hjljy * @date 2021/10/26 */ @webfilter (urlPatterns = "/*") @order (Ordered.HIGHEST_PRECEDENCE) public class EncodeFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; System.out.println(123); request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); chain.doFilter(request, response); }}Copy the code
Then annotate the startup class with @ServletComponentScan. This largely avoids setting after calling getWriter() or getReader().