gpt4 book ai didi

java - HTTP 400 的 Spring MVC 自定义消息

转载 作者:搜寻专家 更新时间:2023-10-31 08:22:26 25 4
gpt4 key购买 nike

我有几个像下面这样的 SprigMVC 方法,返回一个 ModelAndView 或一个 Responsebody。当用户向这些缺少必需参数的 URL 发出请求时,他们自然会收到消息 “必需的字符串参数‘id’不存在”

从安全角度来看,我想对用户隐藏此详细描述消息。所以黑客不容易知道丢失的参数,并且会得到一个没有任何描述的 400 错误。这是否可以通过 spring 配置/Spring Security 实现,或者我必须手动重构我的所有方法以以某种方式返回自定义消息。

@RequestMapping(value = "/payment", method = RequestMethod.GET)
public ModelAndView getReponse(@RequestParam(value = "id", required = true)) {

return model;
}

@RequestMapping(value = "/status", method = RequestMethod.GET)
public @ResponseBody String getStatus(@RequestParam(value = "id", required = true) String id) {

return "string";
}

最佳答案

您真正需要的是 MissingServletRequestParameterException 的全局处理程序,当缺少请求参数时由 Spring 抛出。解决此问题的最简单方法是使用 ControllerAdvice它将为您所有的 Controller 处理它。

import org.springframework.web.bind.MissingServletRequestParameterException;

@ControllerAdvice
class MissingServletRequestParameterExceptionHandler {
@ExceptionHandler(MissingServletRequestParameterException.class)
@ResponseBody
@ResponseStatus(HttpStatus.BAD_REQUEST)
public String handleMissingParameter() {
return "Your custom result";
}
}

如果您只想为特定 Controller 隐藏丢失的参数消息,只需将 handleMissingParameter 方法移动到此 Controller ,而无需创建 ControllerAdvice。

关于java - HTTP 400 的 Spring MVC 自定义消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33386479/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com