欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring Boot使用过滤器过滤非法URL

程序员文章站 2022-05-23 08:35:17
...

一、场景

使用Spring Boot框架,通过过滤器过滤不存在的URL,将这些非法URL转发或重定向到自定义错误页面。

二、实现

API:

  • WebApplicationContext:用于获取全局信息
  • ServletRequest:用于获取请求地址的URI

补充:
URL和URI的区别
示例:https://www.tomyres.com/soft/?page=2&show_page=15

其中,URL为 https://www.tomyres.com/soft/,URI为 /soft/,即URL包含URI,URI没有host部分,也不包含参数部分。

1.获取全局配置

@Resource
WebApplicationContext applicationContext;

2.获取所有方法的请求路径URI(如:@RequestMapping)

RequestMappingHandlerMapping mapping = applicationContext
  .getBean(RequestMappingHandlerMapping.class);
// 获取url与类和方法的对应信息
Map<RequestMappingInfo, HandlerMethod> map = mapping
        .getHandlerMethods();

List<String> urls = new ArrayList<>();
for (RequestMappingInfo info : map.keySet()) {
    // 获取每个方法的url的Set集合,一个方法可能对应多个url
    Set<String> patterns = info.getPatternsCondition().getPatterns();
    //将所有url添加到urls集合
    urls.addAll(patterns);
}

3.获取客户端请求URI,过滤非法URI,跳转到自定义错误页面

HttpServletRequest request = (HttpServletRequest) servletRequest;

if (urls.contains(request.getRequestURI()))
    filterChain.doFilter(servletRequest,servletResponse);
else
    servletRequest.getRequestDispatcher("/failed")
            .forward(servletRequest,servletResponse);

4.完整代码

package com.example.hw3.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;


@WebFilter(filterName = "commonFilter",urlPatterns = "/*")
public class CommonFilter implements Filter {

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Resource
    WebApplicationContext applicationContext;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        logger.info("init方法执行了");

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        logger.info("doFilter方法执行了");
        RequestMappingHandlerMapping mapping = applicationContext
                .getBean(RequestMappingHandlerMapping.class);
        // 获取url与类和方法的对应信息
        Map<RequestMappingInfo, HandlerMethod> map = mapping
                .getHandlerMethods();

        List<String> urls = new ArrayList<>();
        for (RequestMappingInfo info : map.keySet()) {
            // 获取每个方法的url的Set集合,一个方法可能对应多个url
            Set<String> patterns = info.getPatternsCondition().getPatterns();
            //将所有url添加到urls集合
            urls.addAll(patterns);
        }

        HttpServletRequest request = (HttpServletRequest) servletRequest;

        if (urls.contains(request.getRequestURI()))
            filterChain.doFilter(servletRequest,servletResponse);
        else
            servletRequest.getRequestDispatcher("/failed")
                    .forward(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {
        logger.info("destroy方法执行了");

    }
}

三、测试

正常访问

Spring Boot使用过滤器过滤非法URL
输入不存在的URL
Spring Boot使用过滤器过滤非法URL