springboot 增加过滤器方法操作示例

本文实例讲述了springboot 增加过滤器方法操作。分享给大家供大家参考,具体如下:

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

在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确定。

更多关于java相关内容感兴趣的读者可查看本站专题:《Spring框架入门与进阶教程》、《Java数据结构与算法教程》、《Java操作DOM节点技巧总结》、《Java文件与目录操作技巧汇总》和《Java缓存操作技巧汇总》

希望本文所述对大家java程序设计有所帮助。

以上是 springboot 增加过滤器方法操作示例 的全部内容, 来源链接: utcz.com/z/318193.html

回到顶部