strtus中使用filter实现中文编码

strtus中使用filter实现中文编码


1.首先建立一个类文件:

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class MyFilter implements Filter {
private FilterConfig fc;


public void init(FilterConfig fc) throws ServletException {
  // TODO Auto-generated method stub
  this.fc=fc;
}

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
  // TODO Auto-generated method stub
  request.setCharacterEncoding("gb2312");
  response.setCharacterEncoding("gb2312");
  chain.doFilter(request,response);
}

public void destroy() {
  // TODO Auto-generated method stub
 
}

}

2.其次在Web.xml文件里</servlet-mapping>后面写上如下:

<filter>
   <filter-name>Set Character Encoding</filter-name>
   <filter-class>com.xxxx.MyFilter</filter-class>
   <init-param>
    <param-name>encoding</param-name>
    <param-value>GB2312</param-value>
   </init-param>
   <init-param>
    <param-name>enable</param-name>
    <param-value>true</param-value>
   </init-param>
  </filter>
   
  <filter-mapping>
   <filter-name>Set Character Encoding</filter-name>
   <url-pattern>/*</url-pattern>  
  </filter-mapping>
  <filter-mapping>
   <filter-name>Set Character Encoding</filter-name>
   <servlet-name>Action Servlet</servlet-name>
  </filter-mapping>
  <filter-mapping>
   <filter-name>Set Character Encoding</filter-name>
   <servlet-name>Faces Servlet</servlet-name>
  </filter-mapping>

还需要说明的一点是:
   <init-param>
    <param-name>encoding</param-name>
    <param-value>GB2312</param-value>
   </init-param>

需要在页面中使用<%@page language="java" contentType="text/html; charset=GB2312"%>才行。如果换成其他编码,那么这个<param-value>的值也需要更换。

你可能感兴趣的:(java,html,Web,xml,servlet)