五、解决中文乱码问题

  1. 第一种方法是自己写的Filter

建立包com.wang.web.filter      在包下建立一个servlet为MyFilter让其实现Filter接口,是javax.servlet.Filter的接口

package com.wang.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;

public class MyFilter extends HttpServlet implements Filter {

public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException {
arg0.setCharacterEncoding("utf-8");
arg2.doFilter(arg0, arg1);

}

public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub

}

}
  • web.xml中药配置啦这个Filter
<!-- 配置Filter解决中文乱码问题 -->
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>MyFilter</servlet-name>
<servlet-class>com.wang.web.filter.MyFilter</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyFilter</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>

     2.第二种方法是根据spring的Filter  。使用spring框架提供的处理中文乱码的过滤器

  • 在web.xml中配置
<filter>
<filter-name>encoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>



作者:少帅

您的支持是对博主最大的鼓励,感谢您的认真阅读。

本文版权归作者所有,欢迎转载,但请保留该声明。