filter源代码例子

package com.king.utils;

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

/**
 *

Title: 软件开发事业部实践项目


 *

Description: 设置字符集


 *

Copyright: Copyright (c) 2003


 *

Company: 东软软件股份有限公司


 * @author King
 * @version 1.0
 */
public class SetCharacterEncodingFilter extends HttpServlet implements Filter
{
    /**
     *

[字段功能描述]


     */
    private static final long serialVersionUID = 1L;

    private FilterConfig filterConfig;

    /**
     *

字符集编码


     */
    protected String encoding;

    /**
     *

是否使用字符集


     */
    protected boolean use;

    //Handle the passed-in FilterConfig
    /**
     *

初始化


     * @param filterConfig
     * @author:[创建者中文名字]
     * @update:[日期YYYY-MM-DD] [更改人姓名][变更描述]
     */
    public void init(FilterConfig filterConfig)
    {
        this.filterConfig = filterConfig;
        encoding = filterConfig.getInitParameter("encoding");
        String value = filterConfig.getInitParameter("use");

        if (value == null)
        {
            use = true;
        }
        else if (value.equalsIgnoreCase("true"))
        {
            use = true;
        }
        else if (value.equalsIgnoreCase("yes"))
        {
            use = true;
        }
        else
        {
            use = false;
        }
        this.filterConfig = filterConfig;
    }

    //Process the request/response pair
    /**
     *

Discription:转换字符集


     * @param request
     * @param response
     * @param filterChain
     * @author:[创建者中文名字]
     * @update:[日期YYYY-MM-DD] [更改人姓名][变更描述]
     */
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
    {
        try
        {
            if (use || request.getCharacterEncoding() == null)
            {
                String encoding = selectEncoding(request);
                if (encoding != null && !encoding.equals(request.getCharacterEncoding()))
                {
                    request.setCharacterEncoding(encoding);
                }
            }
            filterChain.doFilter(request, response);
        }
        catch (ServletException sx)
        {
            filterConfig.getServletContext().log(sx.getMessage());
        }
        catch (IOException iox)
        {
            filterConfig.getServletContext().log(iox.getMessage());
        }
    }

    //为子类提供扩展的能力
    protected String selectEncoding(ServletRequest request)
    {
        return encoding;
    }

    //Clean up resources
    /**
     *

销毁


     * @author:[创建者中文名字]
     * @update:[日期YYYY-MM-DD] [更改人姓名][变更描述]
     */
    public void destroy()
    {
        encoding = null;
    }

你可能感兴趣的:(Web开发)