整体概览
先来看整体的结构图:(广东人:丢你老味)
在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"时,访问不通:
懂了没,大番薯(帅哥的意思)