应用场景
自动登录
统一设置编码格式
访问权限控制
敏感字符过滤等


首先需要在导入依赖

<dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.3</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet.jsp.jstl</groupId>
            <artifactId>jstl-api</artifactId>
            <version>1.2</version>
        </dependency>

        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>

创建Filter

在Servlet中我们一般都会对request和response中的字符集编码进行配置,如果Servlet过多字符集编码发生变化时修改起码会很麻烦,这些通用的字符集编码配置等工作我们可以放到Filter中来实现。
下面我们来创建一个处理字符集编码的Filter。

package com.likefr.Filter;

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

public class CeFilter implements Filter {

    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.print("CeFilter已经初始化");
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            servletResponse.setCharacterEncoding("utf-8");
            servletResponse.setContentType("text/html ");
            servletRequest.setCharacterEncoding("utf-8");
            System.out.print("执行前");
            filterChain.doFilter( servletRequest,servletResponse);
            System.out.print("执行后");
    }

    public void destroy() {
        System.out.print("CeFilter已经销毁了");
    }
}

演示

public class ShowServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().println("你好 世界"); //不设编码 中文字符会出现乱码的情况 我们使用过滤器来设置中文编码
    }

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

最后配置

<servlet>
        <servlet-name>show</servlet-name>
        <servlet-class>com.likefr.servlet.ShowServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>show</servlet-name>
        <url-pattern>/servlet/show</url-pattern>
    </servlet-mapping>

    /*
    <servlet-mapping>
        <servlet-name>show</servlet-name>
        <url-pattern>/show</url-pattern>
    </servlet-mapping>
*/
    
    <filter>
        <filter-name>filter</filter-name>
        <filter-class>com.likefr.Filter.CeFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>filter</filter-name>
        <url-pattern>/servlet/*</url-pattern>//拦截servlet下的所有
    </filter-mapping>
最后修改:2020 年 11 月 05 日
如果觉得我的文章对你有用,请随意赞赏