Shellbye.github.io icon indicating copy to clipboard operation
Shellbye.github.io copied to clipboard

Spring Boot 必填参数缺失 rest 提示

Open Shellbye opened this issue 6 years ago • 0 comments

在多年不接触Java系,尤其是Spring之后,最近因为转岗需要用到Spring Boot,才突然发现原来Java系的Web开发现在也这么友好了,终于不用在配置各种个样的xml文件和各种XXO.java文件了。但是因为对Spring Boot不是很熟,所以有些东西还是需要记录一下。

问题描述

比如最近遇到的一个小问题,就是当GET请求时,如果有一些url参数是必填而用户忘记填写的话,Spring Boot默认的返回是直接400 Bad Request(如下图)

bad request

这个原则上来说是没有问题的,但是当你写的是restful格式的接口时,这个提示就不是很友好了,需要改成比如这个样式的:

{"code":"400200","data":{},"message":"parameter p1 is required"}

解决方案

其实从上面的图中可以发现,Spring Boot其实做完了我们需要的工作,只是它的展示样式不是我们需要的,那么我们需要做的,其实就是把Spring Boot的工作封装一下就好了。具体的思路就是找到参数缺失的异常(MissingServletRequestParameterException),然后自己捕捉到它就好了。

项目目录结构

tree

关键代码 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,然后就进入到了我们自己的代码中,然后就效果如下图

final

Shellbye avatar Jan 29 '19 10:01 Shellbye