使用过滤器解决中文乱码问题

1. 创建字符编码过滤器对象,源码如下:

package com.tzy.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 CharacterFilter implements Filter {
	
	String encoding = null;
	
	@Override
	public void destroy() {
		encoding = null;
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		if (encoding != null) {
			request.setCharacterEncoding(encoding);
			response.setContentType("text/html;charset=" + encoding);
		}
		/*
		 * 在过滤器对象的doFilter()方法中,业务逻辑处理完成之后,
		 * 需要通过FilterChain对象的doFilter()方法将请求传递到下一过滤器或目标资源,否则将出现错误。
		 */
		chain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		encoding = filterConfig.getInitParameter("encoding");
	}

}
2. 在Web.xml文件中对过滤器进行配置,配置如下:


  CharacterFilter
  com.tzy.filter.CharacterFilter
    encoding
    UTF-8
  


  CharacterFilter
  /*
在Web.xml文件中,配置过滤器,其过滤器的URL映射可以使用正则表达式进行配置,如实例中使用“/*”来匹配所有请求。

3. 我们下面写实例进行测试:

3.1 编写html文件,代码如下:



  
  	
    注册
  
  
  
  	
个人信息
姓名:
性别:
联系方式:
家庭住址:

3.2 处理请求的Servlet代码如下:

package com.tzy.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class RegisterServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		String name = request.getParameter("name");
		String gender = request.getParameter("gender");
		String email = request.getParameter("email");
		String address = request.getParameter("address");
		out.print("");
		out.print("

个人信息


"); out.print("姓名:" + name + "
"); out.print("性别:" + gender + "
"); out.print("联系方式:" + email + "
"); out.print("家庭住址:" + address + "
"); out.print(""); } }

3.3 不要忘了在Web.xml中对Servlet进行配置:


    处理注册信息
    RegisterServlet
    com.tzy.filter.RegisterServlet
  

  
    RegisterServlet
    /servlet/RegisterServlet
  

OK,大功告成!


你可能感兴趣的:(#,Servlet/JSP)