Spring中如何实现请求拦截呢?
下文笔者讲述Spring中编写一个拦截器的方法分享
配置过滤器的示例
拦截器的功能简介说明
拦截器的功能:
用于拦截一些资源的请求
使用过滤器(Filter)进行请求拦截
Filter过滤器是servlet中常用的技术
可对javaweb应用中的所有资源进行拦截
且在拦截之后进行特定的操作
Spring中拦截器的实现思路
实现Filter接口,配置过滤器
Spring中拦截器常用场景:
URL资源的访问权限
中文乱码解决等问题
Spring中实现Filter接口配置过滤器的示例
package com.java265.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中完成 但在pringboot项目 可使用以下方式配置过滤器
package com.java265.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.java265.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");
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


