补充:SpringBoot启动日志

SpringBoot2.x过滤器Filter和使用Servlet3.0配置自定义Filter实战-LMLPHP

1、深入SpringBoot2.x过滤器Filter和使用Servlet3.0配置自定义Filter实战(核心知识)
  简介:讲解SpringBoot里面Filter讲解和使用Servlet3.0配置自定义Filter实战

  filter简单理解:人--->检票员(filter)---> 景点

  1、SpringBoot启动默认加载的Filter
    characterEncodingFilter
    hiddenHttpMethodFilter
    httpPutFormContentFilter
    requestContextFilter

  2、Filter优先级

    Ordered.HIGHEST_PRECEDENCE
    Ordered.LOWEST_PRECEDENCE

    低位值意味着更高的优先级 Higher values are interpreted as lower priority
    自定义Filter,避免和默认的Filter优先级一样,不然会冲突

    注册Filter的bean FilterRegistrationBean
    同模块里面有相关默认Filter
    web->servlet->filter

  3、自定义Filter
    1)使用Servlet3.0的注解进行配置
    2)启动类里面增加 @ServletComponentScan,进行扫描
    3)新建一个Filter类,implements Filter,并实现对应的接口
    4) @WebFilter 标记一个类为filter,被spring进行扫描
      urlPatterns:拦截规则,支持正则

    5)控制chain.doFilter的方法的调用,来实现是否通过放行
    不放行,web应用resp.sendRedirect("/index.html");
    场景:权限控制、用户登录(非前端后端分离场景)等

    1、官网地址:https://docs.spring.io/spring-boot/docs/2.1.0.BUILD-SNAPSHOT/reference/htmlsingle/#boot-features-embedded-container-servlets-filters-listeners

   代码示例:

  启动类中加入@ServletComponentScan注解

  SpringBoot2.x过滤器Filter和使用Servlet3.0配置自定义Filter实战-LMLPHP

  LoginFilter.java:

 package net.xdclass.demo.Filter;

 import java.io.IOException;

 import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; @WebFilter(urlPatterns = "/api/*", filterName = "loginFilter")
public class LoginFilter implements Filter{ /**
* 容器加载的时候调用
*/
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("init loginFilter");
} /**
* 请求被拦截的时候进行调用
*/
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("doFilter loginFilter"); HttpServletRequest req = (HttpServletRequest) servletRequest;
HttpServletResponse resp = (HttpServletResponse) servletResponse;
String username = req.getParameter("username"); if ("xdclass".equals(username)) {
filterChain.doFilter(servletRequest,servletResponse);
} else {
resp.sendRedirect("/index.html");
return;
} } /**
* 容器被销毁的时候被调用
*/
@Override
public void destroy() {
System.out.println("destroy loginFilter");
} }

  controller:

SpringBoot2.x过滤器Filter和使用Servlet3.0配置自定义Filter实战-LMLPHP

浏览器输入:http://localhost:8083/api/v1/account?username=xdclass

前台显示:

SpringBoot2.x过滤器Filter和使用Servlet3.0配置自定义Filter实战-LMLPHP

控制台显示:

SpringBoot2.x过滤器Filter和使用Servlet3.0配置自定义Filter实战-LMLPHP

输入错误的username情况:

浏览器输入:http://localhost:8083/api/v1/account?username=xdclasss

跳转到index.html(可用于提示用户进行登录操作)

SpringBoot2.x过滤器Filter和使用Servlet3.0配置自定义Filter实战-LMLPHP

04-26 12:24