Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spring validation for requestparam not working

I am trying to validate my parameter in controller using @Min(1) annotation. When I test it in unit test, it comes as 200. I am not sure what I am doing wrong. Here is my code:

Controller:

@GetMapping(produces = "application/json")
    public Response search(@RequestParam(name = "firstname", required = false) String firstName,
        @RequestParam(name = "lastname", required = false) String lastName, @RequestParam("ibid") @Min(1) long ibId,
        @RequestParam(name = "workstationids", required = false) List<Long> workstationIds,
        @RequestParam("timerange") int timeRange,
        @RequestParam(name = "receivingstatus", required = false) String receivingStatus,
        @RequestParam(name = "displaystart", required = false) Integer displayStart,
        @RequestParam(name = "displaylength", required = false) Integer displayLength,
        @RequestParam("timezone") @NotBlank String timeZone) {
        ...
        ...

Test:

@Test
    public void searchWithInvalidParams() throws Exception {
        mockMvc.perform(get(BASE_URL)
            .param(COLUMN_IB_ID, INVALID_IB_ID_VALUE) //invalid ib id is "-1"
            .param(COLUMN_TIME_RANGE, TIME_RANGE_VALUE)
            .param(COLUMN_TIME_ZONE, TIME_ZONE)
            .andExpect(status().isBadRequest());
    }

I am expecting it to return 400, but result is 200.

Update: So I added @Validated in controller and added dependency to pom and it still doesn't work(still 200)

my pom:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.nuance.powershare</groupId>
        <artifactId>psh-app-dispatch-reporter</artifactId>
        <version>1.0.0-SNAPSHOT</version>
    </parent>

    <artifactId>psh-app-dispatch-reporter-service</artifactId>
    <properties>
        <sqljdbc4.version>4.0.0</sqljdbc4.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>com.nuance.powershare</groupId>
            <artifactId>psh-lib-dispatch-reporter-model</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>sqljdbc4</artifactId>
            <version>${sqljdbc4.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate.validator</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>6.0.10.Final</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.assertj</groupId>
            <artifactId>assertj-core</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

like image 771
Jonathan Hagen Avatar asked Jun 25 '20 16:06

Jonathan Hagen


People also ask

How do I validate a request body in Spring?

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.

How do I use RequestParam Spring?

In Spring MVC, the @RequestParam annotation is used to read the form data and bind it automatically to the parameter present in the provided method. So, it ignores the requirement of HttpServletRequest object to read the provided data.

What is the difference between PathVariable and RequestParam?

1) The @RequestParam is used to extract query parameters while @PathVariable is used to extract data right from the URI.


2 Answers

You have done the following 2 steps correctly:

  1. Included the hibernate validator to the pom.xml
  2. Added @Validated annotation to the controller

Two more steps are required. Can you do these two in addition to above:

  1. Add one more entry to the pom.xml (not sure about why the javax.el is needed)

     
     
         <dependency>
             <groupId>org.glassfish </groupId>
             <artifactId>javax.el </artifactId>
             <version>3.0.1-b11 </version>
         </dependency>   
     
     
  2. Add the following to your Java Configuration class

     
     
         @Bean
         public MethodValidationPostProcessor methodValidationPostProcessor() {      
              return new MethodValidationPostProcessor();
         }
     
     

(refer - https://www.baeldung.com/spring-validate-requestparam-pathvariable)

like image 101
Alwaysexploring Avatar answered Oct 03 '22 19:10

Alwaysexploring


Starting with Boot 2.3, the required steps for @RequestParam and @PathVariable validation are:

  1. Add dependency:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>
  1. Add @Validated to controller class

Source: https://www.baeldung.com/spring-boot-bean-validation

like image 44
user11153 Avatar answered Oct 03 '22 18:10

user11153