Shellbye.github.io
Shellbye.github.io copied to clipboard
Spring Boot 必填参数缺失 rest 提示
在多年不接触Java
系,尤其是Spring
之后,最近因为转岗需要用到Spring Boot
,才突然发现原来Java
系的Web开发现在也这么友好了,终于不用在配置各种个样的xml
文件和各种XXO.java
文件了。但是因为对Spring Boot
不是很熟,所以有些东西还是需要记录一下。
问题描述
比如最近遇到的一个小问题,就是当GET
请求时,如果有一些url
参数是必填而用户忘记填写的话,Spring Boot
默认的返回是直接400 Bad Request
(如下图)
这个原则上来说是没有问题的,但是当你写的是restful
格式的接口时,这个提示就不是很友好了,需要改成比如这个样式的:
{"code":"400200","data":{},"message":"parameter p1 is required"}
解决方案
其实从上面的图中可以发现,Spring Boot
其实做完了我们需要的工作,只是它的展示样式不是我们需要的,那么我们需要做的,其实就是把Spring Boot
的工作封装一下就好了。具体的思路就是找到参数缺失的异常(MissingServletRequestParameterException
),然后自己捕捉到它就好了。
项目目录结构
关键代码
Controller.java
package com.example.demo;
import org.springframework.web.bind.annotation.*;
@RestController
public class Controller {
@RequestMapping(value = "/demo", method = RequestMethod.GET)
public @ResponseBody
String demo(@RequestParam(value = "p1") String p1,
@RequestParam(value = "p2") String p2,
@RequestParam(value = "p3") String p3,
@RequestParam(value = "p4") String p4,
@RequestParam(value = "p5") String p5) {
return "OK";
}
}
MissingServletRequestParameterExceptionHandler.java
package com.example.demo;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
@ControllerAdvice
public class MissingServletRequestParameterExceptionHandler extends ResponseEntityExceptionHandler {
@Override
protected ResponseEntity<Object> handleMissingServletRequestParameter(
MissingServletRequestParameterException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
String msg = String.format("{\"code\":\"400200\",\"data\":{},\"message\":\"parameter %s is required\"}", ex.getParameterName());
return new ResponseEntity<>(msg, HttpStatus.OK);
}
}
如上代码,MissingServletRequestParameterExceptionHandler
扩展了ResponseEntityExceptionHandler
并重写了其中处理参数缺失的方法handleMissingServletRequestParameter
,然后就进入到了我们自己的代码中,然后就效果如下图