springboot-filter filter

This section introduces the use of spring filter filters. Generally, operations such as garbled code processing and permission control can be loaded in the filter in advance. The following are the basic operations of the filter.

Create project


Introduce dependencies in pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion>   
   

   <groupId>com.example.springboot</groupId>
   <artifactId>springboot-filter</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>

   <name>springboot-filter</name>
   <description>Demo project for Spring Boot</description>

   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.5.12.RELEASE</version>
      <relativePath/> <!-- lookup parent from repository -->
</parent>   

   <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
      <java.version>1.7</java.version>
   </properties>

   <dependencies>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
      </dependency>
   </dependencies>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>
</project>

Create custom filters

Write a class, implement the Filter filter, and implement its methods, as follows:

package com.example.springboot.filter.filter;

import javax.servlet.*;
import java.io.IOException;

/**
 * @desc 自定义过滤器,可以在这里处理中文乱码等问题
 * @Author wangsh
 * @date 2018/5/6 15:44
 * @return
 */
public class CharacterFilter implements Filter {

   /**
    * 服务启动,调用初始化方法
    *
    * @param filterConfig
    * @throws ServletException
    */
   @Override
   public void init(FilterConfig filterConfig) throws ServletException {

      System.out.println("服务启动,调用过滤器Filter初始化方法init()..........");
   }


   /**
    * 请求时调用
    *
    * @param servletRequest
    * @param servletResponse
    * @param filterChain
    * @throws IOException
    * @throws ServletException
    */
   @Override
   public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

      System.out.println("发送请求时,调用过滤器Filter的doFilter()方法..........");
      //放行通过
      filterChain.doFilter(servletRequest, servletResponse);
   }

   /**
    * 销毁调用
    */
   @Override
   public void destroy() {

      System.out.println("服务关闭,调用过滤器Filter的销毁方法destroy()..........");
   }
}
 
 

将过滤器添加到过滤器链中

package com.example.springboot.filter.config;

import com.example.springboot.filter.filter.CharacterFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.ArrayList;
import java.util.List;

/**
 * @desc 注册bean, 将自定义过滤器添加到过滤器链中
 * @Author wangsh
 * @date 2018/5/6 15:48
 * @return
 */
@Configuration
public class WebConfig {

   /**
    * 注册过滤器,有两种方式:
    * 1) 使用 @Component 注解<br>
    * 2) 添加到过滤器链中,此方式适用于使用第三方的过滤器。将过滤器写到 WebConfig 类中,如下:
    */
   @Bean
   public FilterRegistrationBean filterRegistrationBean() {

      FilterRegistrationBean registrationBean = new FilterRegistrationBean();

      CharacterFilter filter = new CharacterFilter();
      registrationBean.setFilter(filter);

      //设置过滤器拦截请求
      List<String> urls = new ArrayList<>();
      urls.add("/*");
      registrationBean.setUrlPatterns(urls);

      return registrationBean;
   }

}

创建controller类

package com.example.springboot.filter.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @desc
 * @Author wangsh
 * @date 2018/5/6 15:49
 * @return
 */
@RestController
public class FilterController {
   /**
    * 请求映射:http://localhost:8080/hello
    *
    * @return
    */
   @RequestMapping("/hello")
   public String hello() {
      System.out.println("测试filter过滤器...........");
      return "hello";
   }
}
创服务启动类

package com.example.springboot.filter;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringbootFilterApplication {

   public static void main(String[] args) {
      SpringApplication.run(SpringbootFilterApplication.class, args);
   }
}

//针对自定义 Servlet、Filter 和 Listener 的配置另一种方式:
//@SpringBootApplication
//public class SpringbootWebApplication implements ServletContextInitializer {
//
// @Override
// public void onStartup(ServletContext servletContext) throws ServletException {
//    // 配置 Servlet
//    servletContext.addServlet("servletTest",new xxxxServlet())
//          .addMapping("/servletTest");
//    // 配置过滤器
//    servletContext.addFilter("timeFilter",new xxxxFilter())
//          .addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST),true,"/*");
//    // 配置监听器
//    servletContext.addListener(new xxxxListener());
// }
//
// public static void main(String[] args) {
//    SpringApplication.run(SpringbootWebApplication.class, args);
// }
//}

启动服务测试

在浏览器访问:http://localhost:8080//hello, 从日志可以看出,当服务启动时,首先调用filter初始化方法init(), 当浏览器发送请求时调用dofilter()方法,如下:


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325572326&siteId=291194637