请求拦截的几种方式

2年前 (2022) 程序员胖胖胖虎阿
125 0 0

后端请求拦截的方式

使用过滤器(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的思想来实现对请求的拦截。
版权声明:程序员胖胖胖虎阿 发表于 2022年11月9日 下午11:16。
转载请注明:请求拦截的几种方式 | 胖虎的工具箱-编程导航

相关文章

暂无评论

暂无评论...