SpringJava处理无效的请求映射URL,包括编码
在我的apiController中,我有
@Controller
@RequestMapping("api/v1/myservice")
@Slf4j
public class APIController {
@RequestMapping(value = "/validAPI1", method = RequestMethod.GET)
@ResponseBody
public String validAPI1() {
return "success";
}
}
我想捕获无效的传入API请求,例如/api/v1/myservice/random124
,这可以通过在末尾添加一个方法来实现:
@RequestMapping(value = "/**", method = RequestMethod.GET)
@ResponseBody
public String handleInvalidAPIReq() {
return "watched and handled";
}
这有两个问题,不能捕获URL中的%
等特殊字符,也不能处理输入URL。我试图反对的一个例子:/api/v1/myservice/%uff0e%uff0e%u2215%7bFILE%7d/abc12
请问,我是否可以使用现有的库或方法来捕获无效的传入API请求?你能帮我举个例子吗?估计吨
# 1 楼答案
处理错误请求的常见解决方案是在
org.springframework.web.servlet.DispatcherServlet
类中设置throwExceptionIfNoHandlerFound
。您没有提到您编写了哪种类型的应用程序,是带有spring mvc依赖项的简单war归档,还是spring boot风格的应用程序对于简单的spring mvc应用程序,您可以在web中设置该属性。xml文件:
对于spring boot应用程序,只需设置config属性:
在这两种情况下,
DispatcherServlet
将抛出NoHandlerFoundException
异常,为了处理此异常,您需要添加ExceptionHandler
类,如下所示:注意:当您启用
throwExceptionIfNoHandlerFound
属性时,您应该记住有关静态资源的信息,并为它们添加自定义映射,否则将找不到资源。 配置静态资源(Spring Boot):或者,如果没有静态资源: