You need to enable JavaScript to run this app. Spring Boot实现Rest Controller URL非法后缀字符校验咨询
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot实现Rest Controller URL非法后缀字符校验咨询

实现路径严格校验返回JSON报错的步骤

首先明确两个需要解决的核心问题:

  • Spring Boot默认规则下,URL中?后面的内容会被识别为查询参数,完全不影响接口匹配,哪怕你访问/add?xxx=123都能正常进入add接口,完全不会触发报错
  • 路径匹配失败时,Spring默认返回HTML格式的Whitelabel错误页,不符合你需要返回带错误码JSON的要求

1. 开启Spring严格路径匹配配置

在你的项目配置文件(application.properties或application.yml)中添加以下配置,关闭Spring的宽松路径适配逻辑,让路径不匹配时直接抛异常而不是跳默认页:
如果使用application.properties:

# 开启Ant路径匹配模式
spring.mvc.pathmatch.matching-strategy=ant-path-matcher
# 路径找不到对应接口时直接抛异常,不跳转默认错误页
spring.mvc.throw-exception-if-no-handler-found=true
# 关闭默认静态资源映射,避免请求被错误路由到静态资源路径
spring.web.resources.add-mappings=false

如果使用application.yml,对应配置为:

spring:
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher
    throw-exception-if-no-handler-found: true
  web:
    resources:
      add-mappings: false

注意:如果你的项目配置了服务上下文路径(比如server.servlet.context-path=/app),后续所有路径判断需要和这个前缀保持一致。


2. 自定义轻量拦截器做路径严格校验

默认配置依然会把/add?这类带查询串的请求判定为合法的add接口请求,因此需要加一个简单的拦截器,专门校验请求是否是完全无额外字符的正确路径:
首先在项目中新建拦截器类:

@Component
public class InsurancePathValidateInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 配置允许的合法路径,和Controller上的映射完全对齐
        String allowedPath = "/insurance/service/add";
        // 获取当前请求的路径部分
        String pathPart = request.getRequestURI();
        // 获取查询串部分
        String queryPart = request.getQueryString();
        // 拼接成完整的请求目标字符串
        String fullRequestTarget = pathPart + (queryPart == null ? "" : "?" + queryPart);
        // 只要完整请求和合法路径有任何差异,也就是在正确路径后面追加了任意非空白字符,就判定非法
        if (!allowedPath.equals(fullRequestTarget)) {
            throw new InvalidRequestPathException("请求路径非法,仅允许无额外字符访问/insurance/service/add接口");
        }
        return true;
    }
}

接着把这个拦截器注册到SpringMVC配置中,只对你的add接口生效,不影响其他业务接口:

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Autowired
    private InsurancePathValidateInterceptor pathValidateInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(pathValidateInterceptor)
                .addPathPatterns("/insurance/service/add");
    }
}

3. 统一全局异常处理,返回带错误码的JSON

用Spring Boot自带的全局异常处理器,把所有路径相关的错误、业务异常都转换成统一的JSON格式返回,不需要自己写复杂的响应逻辑:

@RestControllerAdvice
public class GlobalExceptionHandler {

    // 捕获拦截器抛出的路径非法异常
    @ExceptionHandler(InvalidRequestPathException.class)
    public ResponseEntity<Map<String, Object>> handleInvalidPath(InvalidRequestPathException e) {
        Map<String, Object> errorRes = new HashMap<>();
        errorRes.put("errorCode", "400_INVALID_PATH");
        errorRes.put("errorMessage", e.getMessage());
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorRes);
    }

    // 捕获Spring原生的路径不匹配异常
    @ExceptionHandler(NoHandlerFoundException.class)
    public ResponseEntity<Map<String, Object>> handleNoHandler(NoHandlerFoundException e) {
        Map<String, Object> errorRes = new HashMap<>();
        errorRes.put("errorCode", "404_PATH_NOT_FOUND");
        errorRes.put("errorMessage", "请求路径不存在");
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(errorRes);
    }

    // 捕获你原有代码里的MissingQueryParam异常
    @ExceptionHandler(MissingQueryParam.class)
    public ResponseEntity<Map<String, Object>> handleMissingParam(MissingQueryParam e) {
        Map<String, Object> errorRes = new HashMap<>();
        errorRes.put("errorCode", "400_MISSING_REQUEST_BODY");
        errorRes.put("errorMessage", "请求体不能为空");
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorRes);
    }
}

配套的自定义异常类只需要简单继承RuntimeException即可,不用写复杂逻辑:

// 路径非法异常
public class InvalidRequestPathException extends RuntimeException {
    public InvalidRequestPathException(String message) {
        super(message);
    }
}

测试验证

所有配置完成后,你可以用Postman分别测试以下场景,符合预期:

  • 正常请求POST localhost:8080/insurance/service/add,带合法请求体 -> 正常返回成功提示
  • 请求POST localhost:8080/insurance/service/add? -> 触发拦截器校验,返回400_INVALID_PATH错误码的JSON
  • 请求POST localhost:8080/insurance/service/add* -> 被严格路径匹配判定为路径不存在,返回404对应的JSON错误
  • 请求POST localhost:8080/insurance/service/add/123 -> 同样返回路径错误的JSON

内容的提问来源于stack exchange,提问作者Sayantan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.27 21:06:04