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

编写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>

我的博客网站:http://huyuxin.top/欢迎大家访问!评论!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值