First, the limitations of using servlet processing
able to pass:
request.setCharacterEncoding("UTF-8");
Correctly obtain UTF-8 encoded Chinese, but if there are many servlets that need to obtain Chinese, then this code must be added to each servlet.
There is an easy way, that is to process Chinese through the Filter filter, then all Servlets do not need to be processed separately.
Second, use Filter processing
Create an EncodingFilter and set the following code:
1 package filter; 2 3 import java.io.IOException; 4 import java.text.SimpleDateFormat; 5 import java.util.Date; 6 7 import javax.servlet.Filter; 8 import javax.servlet.FilterChain; 9 import javax.servlet.FilterConfig; 10 import javax.servlet.ServletException; 11 import javax.servlet.ServletRequest; 12 import javax.servlet.ServletResponse; 13 import javax.servlet.http.HttpServletRequest; 14 import javax.servlet.http.HttpServletResponse; 15 16 public class EncodingFilter implements Filter { 17 18 @Override 19 public void destroy() { 20 21 } 22 23 @Override 24 public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) 25 throws IOException, ServletException { 26 HttpServletRequest request = (HttpServletRequest) req; 27 HttpServletResponse response = (HttpServletResponse) res; 28 29 request.setCharacterEncoding("UTF-8"); 30 31 chain.doFilter(request, response); 32 } 33 34 @Override 35 public void init(FilterConfig arg0) throws ServletException { 36 37 } 38 39 }
The first parameter req of the doFilter method is of type ServletRequest and does not support setCharacterEncoding, so it must be converted to HttpServletRequest first.
3. Configure web.xml
1 <filter> 2 <filter-name>EncodingFilter</filter-name> 3 <filter-class>filter.EncodingFilter</filter-class> 4 </filter> 5 6 <filter-mapping> 7 <filter-name>EncodingFilter</filter-name> 8 <url-pattern>/*</url-pattern> 9 </filter-mapping>
In SpringMVC, the web.xml configuration is similar to the above:
1 <filter> 2 <filter-name>CharacterEncodingFilter</filter-name> 3 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 4 <init-param> 5 <param-name>encoding</param-name> 6 <param-value>utf-8</param-value> 7 </init-param> 8 </filter> 9 <filter-mapping> 10 <filter-name>CharacterEncodingFilter</filter-name> 11 <url-pattern>/*</url-pattern> 12 </filter-mapping>