请求拦截的几种方式

后端请求拦截的方式

使用过滤器(Filter)进行请求拦截

  • Filter过滤器是servlet中常用的技术,他可以对javaweb应用中的所有资源进行拦截,并且在拦截之后进行特定的操作。
  • 常用的场景:URL资源的访问权限;中文乱码解决等问题。
  • 实现Filter接口,配置过滤器
package com.example.config;

import javax.servlet.*;
import java.io.IOException;

public class FilterDemo  implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("拦截到请求!");
        //放行拦截请求
        //filterChain.doFilter(servletRequest,servletResponse);

    }
}
  • 在javaweb项目中,过滤器的配置需要在web-xml中完成,但是此处我创建的是springboot项目,没有此文件。通过以下方式配置过滤器。
package com.example.config;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.FilterRegistration;

@Configuration
public class FilterConfig {

    @Bean
    public FilterRegistrationBean registFilter(){
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new FilterDemo());//注册自定义过滤器
        filterRegistrationBean.addUrlPatterns("/*");//过滤所有路径
        filterRegistrationBean.setName("FilterDemo");//过滤器名称
        filterRegistrationBean.setOrder(1);//过滤器优先级
        return filterRegistrationBean;
    }


}

  • 同时创建了一个测试用的controller
package com.example.controller;

import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class FilterTestController {

    @GetMapping("/")
    public ResponseEntity<String> test1(){
        return ResponseEntity.ok("success");
    }

}

  • 启动项目,并访问路径。
    在这里插入图片描述
    在这里插入图片描述

请求已经被成功拦截,并在控制台打印输出了信息。请求被拦截,也并未放行,所以在浏览器中我们没有看到返回的success字符串。若是需要放行请求,只需要把上诉代码中FilterDemo 类的注释语句取消注释,便可放行请求。

通过springMVC中的拦截器(et技术, Interc)进行拦截

拦截器是一种动态拦截方法的调用,在指定方法执行的前后执行预先设定好的代码段,或者阻止方法的继续进行。其实也就是使用了AOP思想。
在这里插入图片描述

拦截器的具体使用方式:Spring拦截器使用

过滤器和拦截器的区别

  • 技术来源不同: Filter属于Servlet技术, Interceptor属于SpringMVC技术
  • 拦截内容不同:Filter对所有的访问都将会进行拦截,Interceptor只是对springmvc的访问进行拦截或者说是方法增强。
  • 其实不管是过滤器还是拦截器都是使用了AOP的思想来实现对请求的拦截。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值