Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

@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';

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.

like image 940
Saakina Avatar asked Mar 07 '17 08:03

Saakina


People also ask

How do you validate a PATH variable?

Validating a PathVariable Let's consider an example where we validate that a String parameter isn't blank and has a length of less than or equal to 10: @GetMapping("/valid-name/{name}") public void createUsername(@PathVariable("name") @NotBlank @Size(max = 10) String username) { // ... }

How do you validate a method in Java?

A backing bean method that performs validation must accept a FacesContext , the component whose data must be validated, and the data to be validated, just as the validate method of the Validator interface does. A component refers to the backing bean method by using its validator attribute.

How do I validate a body request in Spring boot?

Spring offers an elegant way to validate the user input. The @RequestBody annotation is used to bind the HTTP request body with a domain object in the method parameter and also this annotation internally uses the HTTP Message converter to convert the body of the HTTP request to a domain object.


Video Answer


2 Answers

I answered similar problem long before here which 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
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\"]}"));
}
like image 164
Arpit Aggarwal Avatar answered Sep 21 '22 05:09

Arpit Aggarwal


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() + '"';
}
like image 45
P.J.Meisch Avatar answered Sep 22 '22 05:09

P.J.Meisch