自定义Filter拦截器
通过实现Filter接口,覆盖doFilter方法决定是否拦截
package com.example.test_demo.filter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
/**
* @program: test_demo
*
* @description: filter
**/
public class SysFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
ParamServletRequest paramServletRequest = new ParamServletRequest((HttpServletRequest) servletRequest);
filterChain.doFilter(paramServletRequest, servletResponse);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
Filter.super.init(filterConfig);
}
@Override
public void destroy() {
Filter.super.destroy();
}
}
自定义拦截方法,实现去数据前后空格等功能
package com.example.test_demo.filter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.Map;
/**
* @program: test_demo
*
* @description:
*
**/
public class ParamServletRequest extends HttpServletRequestWrapper {
public ParamServletRequest(HttpServletRequest servletRequest) {
super(servletRequest);
Map<String, String[]> parameterMap = servletRequest.getParameterMap();
for (Map.Entry<String, String[]> stringEntry : parameterMap.entrySet()) {
System.out.println(stringEntry.getKey()+stringEntry.getValue());
}
}
}
将自定义拦截器通过配置FilterRegistrationBean实例进行注册
创建一个cofiguration类
package com.example.test_demo.filter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.servlet.DispatcherType;
/**
* @program: test_demo
*
* @description: filter注册器
*
**/
@Configuration
public class FilterRegister {
@Bean
public FilterRegistrationBean getFilterRegist(){
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setDispatcherTypes(DispatcherType.REQUEST);
bean.setFilter(new SysFilter());//注册自定义过滤器
bean.addUrlPatterns("/*");//过滤所有路径
bean.setName("sysFilter");//过滤器名称
bean.setOrder(6);//优先级,数字越小,优先级越高
return bean;
}
}