利用JSP中的过滤器解决中文乱码问题

时间:2021-06-26 20:00:26

首先我们创建过过滤器:

package com.gbx;

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 Zh_Filter implements Filter{ public void destroy() {
// TODO Auto-generated method stub
System.out.println("destroy ...");
} public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException { //设置内置对象的字符集
request.setCharacterEncoding("gb2312");
response.setCharacterEncoding("gb2312");
//处理过滤
chain.doFilter(request, response);
} public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
System.out.println("init .. ");
} }

  

然后再web.xml中配置过滤器:

<filter>
<filter-name>filter</filter-name>
<filter-class>com.gbx.Zh_Filter</filter-class>
</filter>
<filter-mapping>
<filter-name>filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>