您的位置:首页 > 编程语言 > Java开发

配置Java Web中文乱码的过滤器

2015-11-12 18:37 585 查看
编写CharacterEncodingFilter类让其继承Filter,其中Filter导包应该为import javax.servlet.Filter;如果没有这个包需要配置服务器(可配置tomcat),具体方法百度,过滤器代码:

package com;

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 CharacterEncodingFilter implements Filter {
protected String encoding=null;          //定义编码格式变量
protected FilterConfig filterConfig=null;    //定义过滤器配置对象

public void init(FilterConfig arg0) throws ServletException {
this.filterConfig=filterConfig;         //初始化过滤器对象
this.encoding=filterConfig.getInitParameter("encoding");
//获取配置文件中指定的编码格式
}
/**
* 过滤器的接口方法,用于执行过滤业务
* 无返回值;
*/
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)  throws IOException, ServletException {
if (encoding!=null) {
request.setCharacterEncoding(encoding);   //设置请求的编码
//设置应答对象的内容类型(包括编码格式)
response.setContentType("text/html;charset="+encoding);
}
chain.doFilter(request, response);       //传递给下一个过滤器
}

public void destroy() {
this.encoding=null;
this.filterConfig=null;
}
}


在web-inf.xml文件中配置过滤器,并设置编码格式参数和过滤器的URL映射信息,代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>Library</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- 配置字符编码过滤器 -->
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>com.CharacterEncodingFilter</filter-class>  <!-- 指定过滤器的类文件 -->
<init-param>
<param-name>encoding</param-name>
<param-value>GBK</param-value>             <!-- 指定编码为GBK编码 -->
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
<!-- 设置过滤器对应的请求方式 -->
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
</web-app>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: