首页 > 代码库 > struts2 使用filter解决中文乱码问题

struts2 使用filter解决中文乱码问题

1、编写fliter的代码

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 FilterEncoding implements Filter {
protected String encoding=""; // 接收字符编码
protected FilterConfig filterConfig; // 初始化配置
public void init(FilterConfig filterConfig) throws ServletException {
// 从web.xml文件中读取encoding的值
encoding = filterConfig.getInitParameter("encoding");
}
// doFilter方法
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if(!encoding.equals("utf-8"))
{
encoding="utf-8";
}
request.setCharacterEncoding(encoding);
chain.doFilter(request, response);
}
public void destroy() {

}
}

2、修改web.xml文件

在文件所有filter之前加入以下内容

<filter>
<filter-name>encoding</filter-name>
<filter-class>com.FilterEncoding</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>

 

3、在jsp文件开头加入如下几行

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ page pageEncoding="UTF-8" %>

 

注:1、<filter-class>路径要完整,以免找不到

 

struts2 使用filter解决中文乱码问题