当你在Java中使用中文的时候,一个不小心没注意到编码中文就会变成乱码,有些时候,哪怕你所有的页面都设置了UTF-8编码,也经常莫名其妙的变成乱码,乱码真的很令人头疼啊,我在数据库课程设计跟这学期的综合设计中都遇到了这种莫名其妙的乱码问题,经查阅资料,查询了各种解决方法,还就是属这种“过滤器”的方法好用。我们在”web.xml”中配置加载过滤器——嘿 all Done!
[codesyntax lang=”java”]
package com.kaisir.util.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; public class EncodingFilter implements Filter{ private String charset; @Override public void destroy() { // TODO Auto-generated method stub } @Override public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException { // TODO Auto-generated method stub arg0.setCharacterEncoding(this.charset); arg1.setCharacterEncoding(this.charset); arg2.doFilter(arg0, arg1); } @Override public void init(FilterConfig arg0) throws ServletException { // TODO Auto-generated method stub System.out.println("编码过滤器已加载!"); this.charset=arg0.getInitParameter("charset"); System.out.println("当前编码:"+this.charset); } }
[/codesyntax]
之后我们在”web.xml”中配置过滤器,代码如下:
[codesyntax lang=”xml”]
<filter> <filter-name>encoding</filter-name> <filter-class> com.kaisir.util.filter.EncodingFilter </filter-class> <init-param> <param-name>charset</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
[/codesyntax]
嘿嘿 :)