配置字符集过滤器(Filter)

配置字符集过滤器(Filter)

在进行web项目开发时,为了避免乱码,我们通常都会在servlet中的doGet()或者doPost()中重复写下面几句代码:

             req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html; charset=UTF-8");
        resp.setCharacterEncoding("utf-8");


但是重复写这几句代码不是我们想要的,为了不再做重复工作,我们可以设置Filter过滤器:

1、新建一个java类 CharsetFilter,并实现Filter接口

2、重写Filter接口中的init()、doFilter()和 destroy()方法

3、设置字符编码如下:

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html; charset=UTF-8");
        resp.setCharacterEncoding("utf-8");

4、将请求交给FilterChain

        chain.doFilter(req, resp);

5、配置web.xml(拦截所有请求)


下面贴出源码:

CharsetFilter.java


package cn.demo.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;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CharsetFilter implements Filter {

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html; charset=UTF-8");
		resp.setCharacterEncoding("utf-8");
		chain.doFilter(req, resp);

	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
	}

}

web.xml


    
        CharsetFilter
        cn.demo.filter.CharsetFilter
    

    
        CharsetFilter
        *.do
    



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