Http乱码过滤器

Http协议中默认的编码字符集和平台字符集都不是中文的,所以 Web项目中经常会遇到中文乱码问题。

为防止中文乱码出现,首先我们要把项目中每个网页的编码形式改成中文的, HTML网页中的 charset改成 UTF-8 JSP网页中的 pageEncoding改成 UTF-8

然后我们做一个过滤器,每次对网页的请求都会进入到过滤器,并且把 request response都改成 UTF-8编码形式,这样防止了中文乱码的出现。

源代码如下:

package com.dr.servletform;

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.jsp.jstl.core.Config;

public class MyFilter implements Filter{

       String encoding="";

       public void destroy() {

       }

       public void doFilter(ServletRequest request, ServletResponse response,

                     FilterChain chain) throws IOException, ServletException {

              System.out.println("pass here-------");

              request.setCharacterEncoding(encoding);

              response.setCharacterEncoding(encoding);

              chain.doFilter(request, response);

       }

       public void init(FilterConfig config) throws ServletException {

              String encoding=config.getInitParameter("encoding");

              this.encoding=encoding;

              System.out.println(encoding);

       }

}

web.xml中配置如下:

< filter >

  < filter-name > MyFilter </ filter-name >

  < filter-class > com.dr.servletform.MyFilter </ filter-class >

- < init-param >

  < param-name > encoding </ param-name >

  < param-value > UTF-8 </ param-value >

  </ init-param >

  </ filter >

- < filter-mapping >

  < filter-name > MyFilter </ filter-name >

  < url-pattern > /* </ url-pattern >

  </ filter-mapping >

原文:http://womendu.iteye.com/blog/843659

你可能感兴趣的:(jsp,xml,Web,servlet,Blog)