java 如何验证 @RequestParams 不为空?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42643878/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 06:47:33  来源:igfitidea点击:

How do I validate that the @RequestParams are not empty?

javaspring-bootjunit4bean-validationjsr

提问by Saakina

I have a calculator service that gets the operation type, num1 and num2 from the user. I need to validate that the user actually inputs these values and doesn't just leave it blank.

我有一个计算器服务,可以从用户那里获取操作类型 num1 和 num2。我需要验证用户是否实际输入了这些值,而不仅仅是将其留空。

@RequestMapping(value = "/calculate")
@ResponseBody
public CalculationResult calculate(@RequestParam(name = "op") String operation, @RequestParam(name = "num1") Double num1, @RequestParam(name = "num2") Double num2) {
    System.out.print("Operation:" + operation);
    Double calculate = calculatorService.calculate(operation, num1, num2);
    return new CalculationResult(calculate);
}

I have an Integration test that I need to make pass as it is currently failing with error:

我有一个需要通过的集成测试,因为它目前因错误而失败:

{\"timestamp\":1488875777084,\"status\":400,\"error\":\"Bad Request\",\"exception\":\"org.springframework.web.method.annotation.MethodArgumentTypeMismatchException\",\"message\":\"Failed to convert value of type 'java.lang.String' to required type 'java.lang.Double';

{\"时间戳\":1488875777084,\"状态\":400,\"错误\":\"错误请求\",\"异常\":\"org.springframework.web.method.annotation.MethodArgumentTypeMismatchException\ ",\"message\":\"未能将'java.lang.String'类型的值转换为所需的'java.lang.Double'类型;

Below is my Test Case:

下面是我的测试用例:

@Test
public void validates_all_parameters_are_set() throws Exception {
    ResponseEntity<String> response = template.getForEntity( "/calculate?op=&num1=&num2=",
            String.class);
    assertThat(response.getStatusCode(), equalTo(HttpStatus.BAD_REQUEST));
    assertThat(response.getBody(), equalTo("{\"error\":\"At least one parameter is invalid or not supplied\"}"));
}

I don't know how to validate this.

我不知道如何验证这一点。

采纳答案by P.J.Meisch

You do not check the values up to now; you could change your code to:

到目前为止,您没有检查值;您可以将代码更改为:

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

@RequestMapping(value = "/calculate")
@ResponseBody
public ResponseEntity<CalculationResult> calculate(@RequestParam(name = "op") String operation, 
    @RequestParam(name = "num1") Double num1, 
    @RequestParam(name = "num2") Double num2) {

    if(null == op || null == num1 || null == num2) {
        throw new IllegalArgumentException("{\"error\":\"At least one parameter is invalid or not supplied\"}")
    }

    System.out.print("Operation:" + operation);
    Double calculate = calculatorService.calculate(operation, num1, num2);

    return new ResponseEntity<>(new CalculationResult(calculate), HttpStatus.OK);
}    

@ExceptionHandler(IllegalArgumentException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public final String exceptionHandlerIllegalArgumentException(final IllegalArgumentException e) {
    return '"' + e.getMessage() + '"';
}

回答by Arpit Aggarwal

I answered similar problem long before herewhich you can follow to write your test as well , as follows:

我很久以前在这里回答过类似的问题,你也可以按照它来编写你的测试,如下:

@Validated
public class CalculationController {

    @RequestMapping(value = "/calculate")
    @ResponseBody
    public CalculationResult calculate(
            @Valid @NotBlank @RequestParam(name = "op") String operation,
            @Valid @NotNull @RequestParam(name = "num1") Double num1,
            @Valid @NotNull @RequestParam(name = "num2") Double num2) {
        System.out.print("Operation:" + operation);
        Double calculate = calculatorService.calculate(operation, num1, num2);
        return new CalculationResult(calculate);
    }
}

Corresponding @Test should be modified to test for an array of "may not be null"message, as:

应修改相应的@Test 以测试“可能不为空”消息的数组,如:

@Test
public void validates_all_parameters_are_set() throws Exception {
    ResponseEntity<String> response = template.getForEntity( "/calculate?op=&num1=&num2=",
                String.class);
    assertThat(response.getStatusCode(), equalTo(HttpStatus.BAD_REQUEST));
    assertThat(response.getBody(), equalTo("{\"error\":[\"may not be null\",\"may not be null\"]}"));
}