论坛首页 入门技术论坛

过滤器解决乱码

浏览 3826 次
该帖已经被评为新手帖
作者 正文
   发表时间:2008-05-30  

web.xml加配置

<!--   过滤器 -->
 <filter>
  <filter-name>Filter</filter-name>
  <filter-class>
   com.util.EncodingFilter<!-- 过滤器类 -->
  </filter-class>
  <init-param>
   <param-name>Encoding</param-name>
   <param-value>gb2312</param-value>
  </init-param>
 </filter>
 <filter-mapping>
  <filter-name>Filter</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>

 

EncodingFilter.java

package com.hibernate.util;

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 {
 protected FilterConfig config;

 protected String Encoding = null;

 public void init(FilterConfig config) throws ServletException {

  this.config = config;
  this.Encoding = config.getInitParameter("Encoding");

 }

 public void doFilter(ServletRequest request, ServletResponse response,
   FilterChain chain) throws IOException, ServletException {

  if (request.getCharacterEncoding() == null) {
   if (Encoding != null) {
    request.setCharacterEncoding(Encoding);
    response.setCharacterEncoding(Encoding);
   }
  }
  chain.doFilter(request,response);
 }
 public void destroy() {}
}

OK!!!

 

注:

 

n过滤器都必须实现javax.servlet.Filter接口,该接口定义了init()、doFilter()和destroy()三个方法 ,这三个方法也分别对应Servlet过滤器生命周期中的初始化、处理请求和销毁这三个阶段,Filter接口的这三个方法的完整声明如下:
 //初始化过滤器时调用此方法,常用来读取一些系统配置参数
 public void init(FilterConfig filterConfig)throwsServletException;
 
 //当客户端请求服务资源或是发回响应时候调用该方法进行过滤处理
 public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain)throwsIOException,ServletException;
 
 //销毁过滤器时调用此方法,常用来做资源的释放操作
public void destroy();
论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics