package com.example.demo;
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 org.springframework.core.annotation.Order;
@Order(1)
@WebFilter(filterName = “myfilter”,urlPatterns = “/aa”)
public class MyFilter implements Filter{
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
Filter.super.init(filterConfig);
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request1 = (HttpServletRequest) request;
System.out.println(request1.getRequestURI()+"MyName");
chain.doFilter(request,response);
}
@Override
public void destroy() {
// TODO Auto-generated method stub
Filter.super.destroy();
}
第二种:
这里
启动类
下面是自定义的一个MyFilter
package com.example.demo;
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 init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
Filter.super.init(filterConfig);
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request1 = (HttpServletRequest) request;
System.out.println(request1.getRequestURI()+"MyName");
chain.doFilter(request,response);
}
@Override
public void destroy() {
// TODO Auto-generated method stub
Filter.super.destroy();
}
}
下面是一个fitler的一个注册类
package com.example.demo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class TestFilter {
@Bean
public FilterRegistrationBean testFilterRegistrationBean(){
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(new MyFilter());
List a = new ArrayList<>();
a.add("/bb");
registrationBean.setUrlPatterns(a);
Map map = new HashMap<>();
map.put("111","222");
registrationBean.setInitParameters(map);
registrationBean.setName("filter");
return registrationBean;
}
}