欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

EncodingFilter.java

程序员文章站 2022-03-10 13:04:25
...
package com.itheima.web.filter;

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

//使用注解filter 不要用xml配置文件
@WebFilter(filterName = "EncodingFilter" , urlPatterns = "/*")
public class EncodingFilter implements Filter {
    public void destroy() {
    }

    /**
     * 处理编码
     * @param req
     * @param resp
     * @param chain
     * @throws ServletException
     * @throws IOException
     */
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {

        try {
            HttpServletRequest request = (HttpServletRequest)req;
            HttpServletResponse response = (HttpServletResponse) resp;

            //在放行之前处理编码
            request.setCharacterEncoding("utf-8");
            response.setHeader("content-type" , "text/html;charset=utf-8");



            //整个代码必须有放行  这个filter只负责编码 没有逻辑
            chain.doFilter(request, response);
        }catch (Exception e){

        }

    }

    public void init(FilterConfig config) throws ServletException {

    }

}

 

相关标签: Filter