Spring MVC POST中文亂碼解決方案

POST中文亂碼解決方案web

1.本身編寫一個filter,來實現編碼,代碼以下:spring

 1 public class CharacterEncodingFilter implements Filter {
2
3     private final static Logger log= LoggerFactory.getLogger(CharacterEncodingFilter.class);
4
5     private String characterEncoding; //編碼方式配置在web.xml文件中
6     private boolean enabled;   //是否啓用此Filter,配置在web.xml中
7
8     @Override
9     public void destroy() {
10         characterEncoding = null;
11     }
12
13     @Override
14     public void doFilter(ServletRequest request, ServletResponse response,
15                          FilterChain chain) throws IOException, ServletException {
16         if (enabled || characterEncoding != null) {
17             request.setCharacterEncoding(characterEncoding);
18             response.setCharacterEncoding(characterEncoding);
19         }
20         chain.doFilter(request, response);
21     }
22
23     @Override
24     public void init(FilterConfig config) throws ServletException {
25         characterEncoding = config.getInitParameter("characterEncoding");
26         enabled = "true".equalsIgnoreCase(config.getInitParameter("enabled").trim());
27     }
28 }
app

而後本身在web.xml文件中作以下配置框架

1  <filter>
2         <filter-name>characterEncodingFilter</filter-name>
3         <filter-class>com.qunar.training.model.filter.CharacterEncodingFilter</filter-class>
4         <init-param>
5             <param-name>characterEncoding</param-name>
6             <param-value>UTF-8</param-value>
7         </init-param>
8         <init-param>
9             <param-name>enabled</param-name>
10             <param-value>true</param-value>
11         </init-param>
12     </filter>
13     <filter-mapping>
14         <filter-name>characterEncodingFilter</filter-name>
15         <url-pattern>/*</url-pattern>
16     </filter-mapping>
ide

第2種方案:spring Web MVC框架提供了org.springframework.web.filter.CharacterEncodingFilter用於解決POST方式形成的中文亂碼問題,具體配置以下:編碼

 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> 
url

相關文章
相關標籤/搜索