编写servlet 中web.xml 编码过滤问题

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>

    <!--
      设置编码过滤器
    -->
    <filter>
        <description>CharacterEncodingFilter</description>
        <filter-name>CharacterEncodingFilter</filter-name>
        <filter-class>com.yin.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!--

    -->

    <servlet>
        <servlet-name>MyFirstServlet</servlet-name>
        <servlet-class>com.yin.servlet.MyFirstServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>MyFirstServlet</servlet-name>
        <url-pattern>/MyFirstServlet</url-pattern>
    </servlet-mapping>
    
    <!--<servlet>-->
        <!--<servlet-name>EX61</servlet-name>-->
        <!--<servlet-class>com.yin.servlet.EX61</servlet-class>-->
    <!--</servlet>-->
    <!--<servlet-mapping>-->
        <!--<servlet-name>EX61</servlet-name>-->
        <!--<url-pattern>/ex6</url-pattern>-->
    <!--</servlet-mapping>-->
</web-app>

过滤类编写

package com.yin.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;

public class CharacterEncodingFilter implements Filter {

    protected FilterConfig filterConfig = null;
    protected String encoding = "";

    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
        this.encoding = filterConfig.getInitParameter("encoding");
    }
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {

        request.setCharacterEncoding(this.encoding);
        response.setCharacterEncoding(this.encoding);
        response.setContentType("text/html;charset="+this.encoding);

        chain.doFilter(request, response);
    }
    public void destroy() {
        this.encoding = null;
        this.filterConfig = null;
    }
}
最后修改:2021 年 05 月 11 日 09 : 35 AM
如果觉得我的文章对你有用,请随意赞赏