springboot 增加过滤器方法

时间:2024-09-14 17:04:50

在访问服务器时,我们需要控制用户是否允许权限,这个时候可以使用过滤器。

在springboot 配置过滤器的方法如下:

编写过滤器代码:

package com.neo.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.http.HttpServletRequest;
public class MyFilter implements Filter { @Override
public void destroy() {
} @Override
public void doFilter(ServletRequest srequest, ServletResponse sresponse, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) srequest;
System.out.println("this is MyFilter,url :"+request.getRequestURI());
filterChain.doFilter(srequest, sresponse);
} @Override
public void init(FilterConfig arg0) throws ServletException {
} }

编写加载过滤器代码:

package com.neo.conf;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import com.neo.filter.MyFilter;
import com.neo.filter.MyFilter2; @Configuration
public class WebConfiguration { @Bean
public FilterRegistrationBean registerFilter() { FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new MyFilter());
registration.addUrlPatterns("/*");
registration.addInitParameter("paramName", "paramValue");
registration.setName("MyFilter");
registration.setOrder(1);
return registration;
} @Bean
public FilterRegistrationBean registerFilter2() { FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new MyFilter2());
registration.addUrlPatterns("/*");
registration.addInitParameter("paramName", "paramValue");
registration.setName("MyFilter2");
registration.setOrder(2);
return registration;
}
}

这里我们看到我们注册了两个过滤器,过滤器的执行顺序通过setOrder确定。