Filter 过滤器

Filter

  使用Implements Filter实现Filter接口,实现Filter的抽象方法。

   实现用过滤器对servlet使用“utf-8"编码

首先是servlet代码

public class ServletDemo01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().write("你好");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}

然后是Filter代码

public class FilterDemo01 implements Filter {
    @Override
//    初始化
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("初始化");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        servletResponse.setCharacterEncoding("utf-8");
        servletRequest.setCharacterEncoding("utf-8");
        servletResponse.setContentType("text/html");
        System.out.println("执行前");
        filterChain.doFilter(servletRequest,servletResponse);//让请求继续执行,如果不写程序到这里停止
        System.out.println("执行后");
    }

    @Override
//    销毁
    public void destroy() {
        System.out.println("销毁");
    }
}

然后是对web.xml配置servlet以及servlet

    <filter>
        <filter-name>filterDemo01</filter-name>
        <filter-class>com.zhang.filter.FilterDemo01</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>filterDemo01</filter-name>
        <url-pattern>/f1</url-pattern>
    </filter-mapping>


    <servlet>
        <servlet-name>servletDemo01</servlet-name>
        <servlet-class>com.zhang.servlet.ServletDemo01</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>servletDemo01</servlet-name>
        <url-pattern>/s1</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>servletDemo01</servlet-name>
        <url-pattern>/f1</url-pattern>
    </servlet-mapping>

  访问/f1不会乱码,访问/s1会乱码

Filter 过滤器

上一篇:Q:su命令无法切换用户问题,密码正确可登录


下一篇:image组件动画问题