用filter解决jsp web project中文问题

用filter解决jsp web project
 
同样是这周的实训内容,基本原理就是用filter对页面编码进行过滤,输出过虑之后的结果,实用的东西,呵呵。
 
不知道没做出来的人在网上搜索的话会不会搜到我的博客里来,哈哈~
 
过程如下:
 
一、将SetCharacterEncodingFilter.java放至com.buptsse.filter包下
 
二、修改web.xml配置文件,在其中加入
Copy code
  <filter>
    <filter-name>SetCharacterEncoding</filter-name>
    <filter-class>com.buptsse.filter.SetCharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>utf-8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>SetCharacterEncoding</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
 
 
//下面是SetCharacterEncodingFilter.java
Copy code
package com.buptsse.filter;
 
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 SetCharacterEncodingFilter implements Filter {
     protected String encoding = null;
     protected FilterConfig filterConfig = null;
     protected boolean ignore = false;
     
     public void destroy() {
           this.encoding = null;
           this.filterConfig = null;
     }
 
     public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain )
                 throws IOException, ServletException {
           // Conditionally select and set the character encoding to be used
           if ( !ignore || (request.getCharacterEncoding() == null) ) {
                 String encoding = selectEncoding(request);
                 if (encoding != null) request.setCharacterEncoding(encoding);
           }
           // Pass control on to the next filter
           chain.doFilter(request, response);
     }
 
     public void init(FilterConfig filterConfig) throws ServletException {
           this.filterConfig = filterConfig;
           this.encoding = filterConfig.getInitParameter(”encoding”);
           String value = filterConfig.getInitParameter(”ignore”);
           if (value == null) this.ignore = false;
           else if (value.equalsIgnoreCase(”false”)) this.ignore = true;
           else if (value.equalsIgnoreCase(”no”)) this.ignore = true;
           else this.ignore = false;
     }
 
     protected String selectEncoding(ServletRequest request) {
           return (this.encoding);
     }
}
 

相关帖子:
  • Java读取文件中含有中文的解决办法[转]
  • 中文问题
  • micas Jun 27th 2007 11:11 am tomcat No Comments yet Trackback URI Comments RSS

    Leave a Reply

    You must be logged in to post a comment.