SpringBoot學習筆記:自定義的過濾器

SpringBoot學習筆記:自定義的過濾器

快速開始

  SpringBoot提供的前端控制器沒法知足咱們產品的需求時,咱們須要添加自定義的過濾器。html

  在SpringBoot的開發中,咱們應該還據說過攔截器,他們的效果是同樣的,都是對請求和響應進行過濾,但仍是有一點區別:前端

  • 過濾器是Servlet概念中定義的,須要收到容器的支持,如Tomcat;攔截器是Spring定義的,有Spring框架支持。
  • Filter只能用於Web開發,攔截器既能夠用在Web開發,也能夠用在App、Swing開發中。
  • 攔截器更加靈活,在Spring環境中更適合使用攔截器。

  因此,本片文章僅僅是講解過濾器的使用,SpringBoot開發中建議使用攔截器,請看http://www.javashuo.com/article/p-djjjgquy-db.htmljava

編寫過濾器web

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

    }
}

說明:spring

  這裏使用了註解@ WebFilter來代表這是一個過濾器,這是Servlet 3.0引入的新註解,一樣還有@WebFilter 和 @WebListener,這就相似於咱們傳統的WebServlet開發了session

註冊過濾器框架

  使用嵌入式容器時,能夠使用@ServletComponentScan啓用@WebServlet,@ WebFilter和@WebListener註釋類的自動註冊。ide

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

}
相關文章
相關標籤/搜索