码迷,mamicode.com
首页 > 编程语言 > 详细

SpringBoot:学习笔记(4)——添加自定义的过滤器

时间:2017-12-14 23:54:51      阅读:230      评论:0      收藏:0      [点我收藏+]

标签:void   code   contain   参考   send   redirect   ide   embed   web   

SpringBoot:学习笔记(4)——添加自定义的过滤器

引入自定义过滤器

为什么添加自定义过滤器

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

参考资料:官方文档

SpringBoot添加过滤器的注解方式

1.编写过滤器代码

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() {

    }
}

说明:

  重点在于两个注解!

  When using an embedded container, automatic registration of @WebServlet@WebFilter, and @WebListener annotated classes can be enabled using @ServletComponentScan.

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

@ServletComponentScan will have no effect in a standalone container, where the container’s built-in discovery mechanisms will be used instead.

  如果使用外置容器的话,容器的内置发现机制将会被使用,而不需要使用这条注解。

2.添加@ServletComponentScan注解

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

}

 

SpringBoot:学习笔记(4)——添加自定义的过滤器

标签:void   code   contain   参考   send   redirect   ide   embed   web   

原文地址:http://www.cnblogs.com/MrSaver/p/8040390.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!