Spring Boot URL短链服务自定义404页面配置问题求助
解决Spring Boot短链服务自定义404页面的问题
你的核心问题是@GetMapping("/**")会匹配所有GET请求,包括访问自定义404页面的请求——这就导致要么404页面被控制器拦截处理,抛出异常后显示白标错误页;要么请求在控制器和404页面之间循环调用,最终触发StackOverflowException。
以下是具体解决方案:
方案1:限定控制器的请求映射范围(推荐)
用路径变量+正则表达式,只匹配符合短链格式的请求,避免拦截静态资源和错误页面的请求。比如假设你的短链由字母和数字组成,修改控制器方法如下:
@GetMapping("/{shortCode:[a-zA-Z0-9]+}") public ResponseEntity<Void> redirect(@PathVariable String shortCode) { String source = shortCode.toLowerCase(); ShortUrl shortUrl = shortUrlService.getShortUrlBySource(source); if (shortUrl == null) throw new ShortUrlNotFoundException(); // 抛出404异常 HttpHeaders headers = new HttpHeaders(); headers.setLocation(URI.create(shortUrl.getDestination())); return new ResponseEntity<>(headers, HttpStatus.FOUND); }
之后按照Spring Boot默认规则配置自定义404页面:
- 如果用模板引擎(如Thymeleaf),在
src/main/resources/templates/error目录下创建404.html; - 如果用静态页面,在
src/main/resources/static/error目录下创建404.html;
Spring Boot会自动在捕获404异常时加载这个页面。
方案2:保留/**映射,排除错误页面请求
如果必须保留/**的映射范围,需要在控制器中排除错误相关的请求路径,避免循环:
@GetMapping("/**") public ResponseEntity<Void> redirect(HttpServletRequest request) { String source = request.getRequestURI().toLowerCase(); // 排除错误页面和Spring Boot默认错误路径 if (source.equals("/404.html") || source.equals("/error")) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } if (source.startsWith("/")) source = source.substring(1); ShortUrl shortUrl = shortUrlService.getShortUrlBySource(source); if (shortUrl == null) throw new ShortUrlNotFoundException(); HttpHeaders headers = new HttpHeaders(); headers.setLocation(URI.create(shortUrl.getDestination())); return new ResponseEntity<>(headers, HttpStatus.FOUND); }
同时配合全局异常处理器,将ShortUrlNotFoundException转发到自定义404页面:
@ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(ShortUrlNotFoundException.class) public String handleShortUrlNotFound() { return "error/404"; // 对应模板路径下的404页面 } }
关键注意点
- 不要让短链的路径规则覆盖静态资源或错误页面的路径;
- Spring Boot的默认错误页面规则是在
error目录下按状态码命名文件(如404.html),无需额外配置拦截器或过滤器。
内容的提问来源于stack exchange,提问作者LoreSchaeffer
相关产品推荐
相关产品推荐

