You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用@PathVariable时请求返回400 Bad Request问题排查求助

Fixing 400 Bad Request with @PathVariable for URLs Containing Encoded Slashes

Hey there, let's break down why you're hitting that 400 error and how to fix it quickly!

The Root Cause

Your request URL includes an encoded target URL (http%3A%2F%2Fwww.bildarchivaustria.at%2FPreview%2F15620341.jpg) as a @PathVariable. The problem is that Spring's default path matching engine (PathPatternMatcher) treats the encoded slash (%2F) as an actual path separator (/).

So instead of seeing two path segments (w200 and the full encoded URL), Spring interprets your request as having multiple segments: w200, http:, www.bildarchivaustria.at, Preview, 15620341.jpg. This doesn't match your mapped path /{size}/{url}, hence the 400 Bad Request.

A quick side note: your size parameter has required=false set, but since it's part of the path structure, this setting doesn't actually work—path variables are always required unless you adjust the path pattern to make them optional (but that's not your immediate issue here).


Solution 1: Switch to Query Parameters (Simplest Fix)

The easiest way to avoid path separator conflicts is to move the url parameter from the path to a query string. Here's how to adjust your code and request:

Updated Controller Code

@RestController
@RequestMapping("/testing/v3")
public class ControllerV3 {
    @GetMapping(value = "/{size}")
    public ResponseEntity<byte[]> testByUrl(
            @PathVariable(name="size") String size,
            @RequestParam("url") String url, // Changed to @RequestParam
            WebRequest webRequest,
            HttpServletResponse response) {
        long startTime = 0;
        if (LOG.isDebugEnabled()) {
            startTime = System.nanoTime();
            LOG.debug("url = {}, size = {}", url, size);
        }
        // Rest of your processing logic
    }
}

Updated Request URL

http://localhost:8085/testing/v3/w200?url=http%3A%2F%2Fwww.bildarchivaustria.at%2FPreview%2F15620341.jpg

Query parameters handle encoded special characters seamlessly, so you won't run into path matching issues here.


Solution 2: Configure Spring to Allow Encoded Slashes in Path Variables

If you absolutely need to keep the url as a path variable, you'll need to switch Spring's path matcher to AntPathMatcher (which supports encoded slashes) and configure Tomcat to relax path character restrictions.

Option A: Using Application Properties

Add these lines to your application.properties (or equivalent YAML):

# Use AntPathMatcher instead of default PathPatternMatcher
spring.mvc.pathmatch.matching-strategy=ant_path_matcher

# Allow encoded slashes in Tomcat's path processing
server.tomcat.relaxed-path-chars=/,\\

Option B: Java Configuration

If you prefer code-based config, create a WebMvcConfigurer bean:

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        AntPathMatcher pathMatcher = new AntPathMatcher();
        // Enable support for encoded slashes in path variables
        pathMatcher.setAllowEncodedSlash(true);
        configurer.setPathMatcher(pathMatcher);
    }
}

After applying either of these, Spring will treat %2F as part of the url path variable instead of splitting it into new path segments.


Final Notes

  • The query parameter approach is generally safer and more maintainable, especially if your url parameter might contain other special characters.
  • If you stick with path variables, be aware that allowing encoded slashes has minor security implications (though it's usually fine for internal/testing services).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:18:13