zoukankan      html  css  js  c++  java
  • SpringBoot学习笔记:自定义的过滤器

    SpringBoot学习笔记:自定义的过滤器

    快速开始

      SpringBoot提供的前端控制器无法满足我们产品的需求时,我们需要添加自定义的过滤器。

      在SpringBoot的开发中,我们应该还听说过拦截器,他们的效果是一样的,都是对请求和响应进行过滤,但还是有一点区别:

    • 过滤器是Servlet概念中定义的,需要收到容器的支持,如Tomcat;拦截器是Spring定义的,有Spring框架支持。
    • Filter只能用于Web开发,拦截器既可以用在Web开发,也可以用在App、Swing开发中。
    • 拦截器更加灵活,在Spring环境中更适合使用拦截器。

      所以,本片文章仅仅是讲解过滤器的使用,SpringBoot开发中建议使用拦截器,请看https://www.cnblogs.com/MrSaver/p/11201867.html

    编写过滤器

    package com.mrsaber.security;
    
    import org.springframework.core.annotation.Order;
    
    import javax.servlet.*;
    import javax.servlet.annotation.WebFilter;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    import java.io.IOException;
    
    @Order(1)
    @WebFilter(filterName = "MSecurity",urlPatterns = {"*.html"})
    public class MSecurityFilter implements Filter {
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
    
        }
    
        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            HttpServletResponse response= (HttpServletResponse) servletResponse;
            System.out.println(request.getRequestURI());
            //检查是否是登录页面
            if(request.getRequestURI().equals("/web/index.html"))
                filterChain.doFilter(servletRequest,servletResponse);
    
            //检测用户是否登录
            HttpSession session =request.getSession();
            String status= (String) session.getAttribute("isLogin");
            if(status==null || !status.equals("true"))
            {
                try{  response.sendRedirect("/web/index.html");}catch (Exception e){}
            }
            filterChain.doFilter(servletRequest,servletResponse);
        }
    
        @Override
        public void destroy() {
    
        }
    }

    说明:

      这里使用了注解@ WebFilter来表明这是一个过滤器,这是Servlet 3.0引入的新注解,同样还有@WebFilter 和 @WebListener,这就类似于我们传统的WebServlet开发了

    注册过滤器

      使用嵌入式容器时,可以使用@ServletComponentScan启用@WebServlet,@ WebFilter和@WebListener注释类的自动注册。

    @SpringBootApplication
    @ServletComponentScan(basePackages = "com.mrsaber.security")
    public class MsSupplyAndSaleApplication {
        public static void main(String[] args) {
            SpringApplication.run(MsSupplyAndSaleApplication.class, args);
        }
    
    }

     

  • 相关阅读:
    python字符串
    php设计模式 ---单例模式.
    PHP设计模式---策略模式
    PHP设计模式---适配器模式
    PHP设计模式---抽象工厂模式
    windows下安装redis
    PHP基础知识汇总(四)
    PHP面向对象整理
    PHP基础知识汇总(三)
    PHP基础知识汇总(二)
  • 原文地址:https://www.cnblogs.com/MrSaver/p/8040390.html
Copyright © 2011-2022 走看看