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

过滤器Filter

程序员文章站 2022-06-21 14:50:23
...
标准版
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

@WebFilter("/*")
public class Filter implements javax.servlet.Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {

        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}

字符过滤
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

@WebFilter("/*")
public class EncodingFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        servletRequest.setCharacterEncoding("UTF-8");
        servletResponse.setContentType("text/html;charset=UTF-8");
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}

登录过滤

每次运行Tomcat,如果没有登录,自动跳转到登录页面

Constants接口,常量为访问Servlet的路径

import util.Constants;

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

@WebFilter("/*")
public class LoginFilter implements Filter {
    //不需要登陆就能访问的地址
    private static final String[] IGNORE_LOGIN_URL = {"/login", "/index.jsp", "/vcode"};

    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        String path = request.getServletPath();
        if (check(path)) {
            chain.doFilter(request, response);
            return;
        }
        if (request.getSession().getAttribute(Constants.MANAGER) == null) {
            response.sendRedirect("index.jsp");
        } else {
            chain.doFilter(request, response);
        }
        chain.doFilter(req, resp);
    }

    private boolean check(String path) {
        for (String s : IGNORE_LOGIN_URL) {
            if (s.equals(path)) {
                return true;
            }
        }
        return false;
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
相关标签: 工具代码