Spring Boot实现过滤器

1.过滤器

在SpringBoot中使用过滤器不需要在xml文件中配置filter,只需要添加注解@WebFilter同时实现Filter接口

注意:@WebFilter注解为声明此类为filter,第一个参数为该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(filterName = "test", urlPatterns = "/*")//可以省略
public class UrlFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		System.out.println("----------------------->过滤器被创建");
		
	}
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;   
		HttpServletResponse res = (HttpServletResponse) response;   
		String requestURI = req.getRequestURI();     
		System.out.println("--------------------->过滤器:请求地址"+requestURI);
		
		if(!requestURI.contains("index")){   //contains判断是否包含
			
			request.getRequestDispatcher("/noindex").forward(request, response); //转发。。。
			
			}else{       
				chain.doFilter(request, response);    
			
				}
	}

	@Override
	public void destroy() {
		System.out.println("----------------------->过滤器被销毁");
		
	}

}

2.在启动类上面添加@ServletComponentScan(basePackages = {“com.example.filter”})

@ServletComponentScan(basePackages = {"com.example.filter"})
@SpringBootApplication
public class SpringbootfilterApplication {

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

3.测试controller层

@RestController
public class ControllerFilter {
	@RequestMapping("/noindex")
	public Map<String, String> requestFailed(){
		Map<String, String> map = new HashMap<>();
		map.put("msg", "请求错误");
		map.put("code", "-1");
		return map;
	}
	@RequestMapping("/index")
	public Map<String, String> userIndex(){
		Map<String, String> map = new HashMap<>();
		map.put("1", "2");
		map.put("2", "1");
		return map;
		}
}

4.测试结果

当地址不是index的时候 跳转到noindex
在这里插入图片描述

当地址是index时,跳转到index

在这里插入图片描述

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页