(二)、SpringBoot 自定义 filter(过滤器)
程序员文章站
2022-05-23 08:37:40
...
可以前往第一篇博客查看目录结构 --> 这里
一、在demo模块 src\main\java\com\zeke下创建 config、controller、dto、filter目录
二、在dto包下创建一个User类
public class User {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
三、controller包下创建UserController类
@RestController
public class UserController {
@GetMapping("/user")
public List<User> query(@RequestParam(value = "username",defaultValue = "666") String username){
System.out.println(username);
List<User> list = new ArrayList<>();
list.add(new User());
list.add(new User());
list.add(new User());
return list;
}
}
四、在filter包下创建TimeFilter类,用于自定义filter
@Component
public class TimeFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("filter init");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
System.out.println("filter start");
long start = new Date().getTime();
chain.doFilter(request,response);
System.out.println("filter 耗时: " + (new Date().getTime() - start));
System.out.println("filter finish");
}
@Override
public void destroy() {
System.out.println("filter destroy");
}
}
五、在config包下创建WebConfig类
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter{
/**
* 配置自定义过滤器
* @return
*/
@Bean
public FilterRegistrationBean timeFilter(){
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
TimeFilter timeFilter = new TimeFilter();
filterRegistrationBean.setFilter(timeFilter);
//自定义需要的过滤url
List<String> list = new ArrayList<>();
list.add("/*");
filterRegistrationBean.setUrlPatterns(list);
return filterRegistrationBean;
}
}
六、启动项目 输入 localhost/user ,打开IDEA控制台查看效果
下一篇: Hbase过滤器(三):附加过滤器API
推荐阅读
-
SpringBoot之过滤器Filter
-
Java:SpringBoot集成filter过滤器、interceptor拦截器
-
AngularJS使用Filter自定义过滤器控制ng-repeat去除重复功能示例
-
Spring Security之默认的过滤器链及自定义Filter操作
-
SpringBoot项目中通过MDC和自定义Filter操作traceId实现日志链路追踪
-
详解AngularJS中$filter过滤器使用(自定义过滤器)
-
springboot自定义过滤器的方法
-
详解AngularJS中$filter过滤器使用(自定义过滤器)
-
springboot整合shiro与自定义过滤器的全过程
-
Springboot模板整合(二)整合自定义属性和自定义配置文件