当前位置 : 主页 > 编程语言 > c++ >

HttpFilter仿照HttpServlet写的,可以提高开发效率

来源:互联网 收集:自由互联 发布时间:2021-07-03
HttpFilter package xin.sun.controller.filter;import javax.servlet.*;import javax.servlet.FilterConfig;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;/** * * 仿照HttpSe
HttpFilter
package xin.sun.controller.filter;

import javax.servlet.*;
import javax.servlet.FilterConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 *
 * 仿照HttpServlert,自定义HttpFilter,简化开发,
 */
public abstract class HttpFilter implements Filter {

    private FilterConfig filterConfig;

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

    /**
     * 获取过滤器配置对象
     * @return
     */
    public FilterConfig getFilterConfig(){
        return this.filterConfig;
    }

    /**
     * 获取初始化参数
     * @param key
     * @return
     */
    public String getInitParameter(String key){
        return  getFilterConfig().getInitParameter(key);
    }

    /**
     * 获取应用上下文
     * @return
     */
    public ServletContext getServletContext() {
        return this.getFilterConfig().getServletContext();
    }

    /**
     * 提供用户初始化方法
     * @throws ServletException
     */
    public void init() throws ServletException {
    }

    /**
     * 重写doFilter(),把Servlert***转换为HttpServlert***
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request;
        HttpServletResponse response;
        try {
            request = (HttpServletRequest)servletRequest;
            response = (HttpServletResponse)servletResponse;
        } catch (ClassCastException var6) {
            throw new ServletException("non-HTTP request or response");
        }
        this.doFilter(request,response,filterChain);
    }

    /**
     * 提供一个doFilter()方法,用户必须实现
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    protect abstract void doFilter(HttpServletRequest servletRequest, HttpServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException ;

    @Override
    public void destroy() {

    }
}
网友评论