springboot-过滤器

整体概览

先来看整体的结构图:(广东人:丢你老味)

在Spring Boot中,我们可以使用Servlet过滤器来实现以下功能:
1. 认证和授权:通过拦截请求并验证用户的身份信息,从而实现认证和授权功能。
2. 日志记录:通过拦截请求和响应,记录用户的操作行为和系统的运行状态。
3. 数据压缩和解压缩:通过拦截请求和响应,对数据进行压缩和解压缩,从而提高网络传输的效率。
4. 缓存控制:通过拦截请求和响应,控制缓存的使用和更新,从而提高系统的性能和响应速度。
5. 跨域资源共享:通过拦截请求和响应,实现跨域资源共享,从而实现不同域名之间的数据传输。

具体操作

新建filter文件夹,写一个简单的Filter类,这里限制了访问的url只能是"/hcy",如果不是,就抛异常,实现简单的认证:

@Component
public class SimpleFilter extends HttpFilter {
    @Override
    public void destroy() {}

    @Override
    public void doFilter(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain)
            throws IOException, ServletException {

        String url = httpServletRequest.getRequestURI();
     
        if(!url.equals("/hcy")) {
            throw new RuntimeException();
        }

        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {}
}

在 Spring Boot 主应用程序类文件中,我们添加了返回"hello world"字符串的简单 REST 端点:

@SpringBootApplication
@RestController
public class SpringbootFilterApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootFilterApplication.class, args);
    }
    @RequestMapping(value = "/hcy")
    public String hello() {
        return "hello world";
    }

}

效果展示

正常情况:

被过滤的情况下,可以看到当请求的url是"/hcys"时,访问不通:

懂了没,大番薯(帅哥的意思)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值