使用过滤器设置编码格式

简介:

通常如果浏览器客户端向服务端发送ISO-8859-1的中文编码的时候,服务端可能会解析处乱码.
所以通常在web.xml中配置一个过滤器,设置请求的编码格式的过滤器,用来拦截每个客户端发送的请求.
不能统一的将请求的编码格式强制设置为UTF-8,因为Get请求发过来的是ISO-8859-1,所以需要通过new String(value.getBytes(“ISO-8859-1”), “UTF-8”)来转化编码格式.

过滤器代码:

package com.zgd.learn.servlet.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;
/**
 * 过滤所有请求,将请求和响应的编码格式统一转化为UTF8 将响应编码格式
 */
public class EncodingFilter implements Filter
{
    @Override
    public void destroy()
    {
    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException
    {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String method = httpRequest.getMethod();
        // 设置响应编码格式
        response.setContentType("text/html;charset=utf-8");
        if ("GET".equals(method))
        {
            // 因为不知道具体哪个请求参数需要转换编码格式,所以使用装饰类进行处理
            EncodingServletRequest encodingServletRequest = new EncodingServletRequest(httpRequest);
            chain.doFilter(encodingServletRequest, response);
        } else if ("POST".equals(method))
        {
            request.setCharacterEncoding("UTF-8");
            chain.doFilter(request, response);
        }
    }

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

装饰的HttpRequest代码

package com.zgd.learn.servlet.filter;
import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
public class EncodingServletRequest extends HttpServletRequestWrapper
{
    private HttpServletRequest request;
    public EncodingServletRequest(HttpServletRequest request)
    {
        super(request);
        this.request = request;
    }

    @Override
    public String getParameter(String name)
    {
        String value = request.getParameter(name);
        try
        {
            return new String(value.getBytes("ISO-8859-1"), "UTF-8");
        } catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
            throw new RuntimeException("Encoding is not ISO-8859-1");
        }
    }
}

web.xml中配置

<filter>
	<filter-name>EncodingFilter</filter-name>
	<filter-class>com.zgd.learn.servlet.filter.EncodingFilter</filter-class>
</filter>
<filter-mapping>
	<filter-name>EncodingFilter</filter-name>
	<url-pattern>/*

你可能感兴趣的:(Web)