springboot整合filter方式一

1.创建一个springboot项目

package com.test;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;

@SpringBootApplication
@ServletComponentScan//会扫描@WebServlet的类并实例化该类
public class App {
	public static void main(String[] args) {
		SpringApplication.run(App.class, args);
	}
}

2.创建一个filter类

package com.test.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;
/**
 * 
 * 		first
 * 		com.test.filter.FirstFilter
 * 
 * 
 * 		first
 * 		/hello
 * 
 * @author 26920
 */
@WebFilter(filterName="first",urlPatterns="/hello")
public class FirstFilter implements  Filter{
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
	}
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		System.out.println("servlet执行之前=========");
		chain.doFilter(request, response);
		System.out.println("servlet执行之后============");
	}
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
	}
}

3.在filter类上加上一个@WebFilter注解,其中filterName属性是个标识而且唯一,urlPatterns是filter的拦截路径。

4.启动类中与整合servlet不同的是还是需要使用@ServletComponentScan注解进行扫描,它也会扫描@WebFilter注解修饰的类。

你可能感兴趣的:(spring,boot)