关于Java:如何验证@RequestParams是否为空?

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

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

1
2
3
4
5
6
7
@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);
}

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

{\"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';

以下是我的测试用例:

1
2
3
4
5
6
7
@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"}"));
}

我不知道该如何验证。


我早在这里就回答了类似的问题,您也可以按照下面的步骤编写测试:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@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);
    }
}

应该修改相应的@Test以测试"可能不为空"消息的数组,如下所示:

1
2
3
4
5
6
7
@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"]}"));
}

您到目前为止不检查这些值; 您可以将代码更改为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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() + '"';
}