gpt4 book ai didi

java - 如何更好地处理@RequestParam(required=true)

转载 作者:行者123 更新时间:2023-11-30 10:45:19 26 4
gpt4 key购买 nike

在springmvc项目的controller中,代码为:

@Controller
@RequestMapping("/detail")
public class FileDetailController {
@RequestMapping("/add_detail")
@ResponseBody
public Object addDetailWithVersionId(@RequestParam(required=true)String versionId,
String description) {

if(hasVersion(versionId)) {
FileDetail fileDetail = new FileDetail();
fileDetail.setId(UUIDUtil.getUUID());
fileDetail.setDescription(description);
fileDetail.setVersionId(versionId);
// detailService.insert(fileDetail);
return JsonUtil.SUCCESS;
}
return JsonUtil.ERROR;
}

在我的浏览器上,我输入 http://localhost:8080/file_server/detail/add_detail 然后收到消息:HTTP Status 400 - Required String parameter 'versionId' is not present 。哦代码@RequestParam(required=true)String versionId起到了作用。但是有没有合适的方法,这种情况下返回json给前端?

最佳答案

(OPTION 1)如果你想改变返回到前端,你可以实现自定义org.springframework.boot.autoconfigure.web.ErrorController

例如:

@RestController
public class MyErrorController extends AbstractErrorController {

private static final String PATH = "/error";

@Autowired
public MyErrorController(ErrorAttributes errorAttributes) {
super(errorAttributes);
}

@RequestMapping(value = PATH)
public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
Map<String, Object> body = getErrorAttributes(request, false);
HttpStatus status = getStatus(request);
return new ResponseEntity<Map<String, Object>>(body, status);
}

@Override
public String getErrorPath() {
return PATH;
}

}

你现在总是会得到类似这样的 json:

{
"timestamp": 1462600073772,
"status": 400,
"error": "Bad Request",
"exception": "org.springframework.web.bind.MissingServletRequestParameterException",
"message": "Required String parameter 'versionId' is not present",
"path": "/add_detail"
}

如果你愿意,可以随意定制它。只需更改 Controller 中的错误方法即可。


(选项 2) 在您的 Controller 中使用自定义 @ExceptionHandler。可以阅读此以获取更多信息 https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc

只需在您的 FileDetailController 中添加类似的内容

@Autowired
private ErrorAttributes errorAttributes;

@ExceptionHandler(MissingServletRequestParameterException.class)
public ResponseEntity<Map<String, Object>> handle(HttpServletRequest request, Exception exception) {
RequestAttributes requestAttributes = new ServletRequestAttributes(request);
Map body = this.errorAttributes.getErrorAttributes(requestAttributes,false);

return new ResponseEntity<Map<String, Object>>(body, HttpStatus.BAD_REQUEST);
}

关于java - 如何更好地处理@RequestParam(required=true),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37084065/

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