In this post, I am going to explain how to bind query parameter to a list.
For example,
to-upper?str=myValue1&str=myValue2&str=myValue3
In the above example, query parameter str is repeated thrice, I want to bind all the values associated with query parameter str to a list of strings. I can do this by mapping RequestParam to list of strings like below.
@RequestMapping("/to-upper")
public List<String> home(@RequestParam(name = "str") List<String> strs) {
.......
.......
}
Find the below working application.
Step 1: Create new maven project ‘map-query-param-to-list’.
Step 2: Update pom.xml with maven dependencies.
pom.xml
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.sample.app</groupId>
<artifactId>map-query-param-to-list</artifactId>
<version>1</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
</parent>
<name>springbootApp</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>
Step 3: Create a package ‘com.sample.app.controller’ and define the class StringController.
StringController.java
package com.sample.app.controller;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class StringController {
@RequestMapping("/to-upper")
public List<String> home(@RequestParam(name = "str") List<String> strs) {
if (strs == null || strs.isEmpty()) {
return Collections.EMPTY_LIST;
}
List<String> upperCaseStrings = new ArrayList<>();
for (String str : strs) {
upperCaseStrings.add(str.toUpperCase());
}
return upperCaseStrings;
}
}
Step 4: Define main application class.
App.java
package com.sample.app;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
Total project structure looks like below.
Run App.java.
Open the url 'http://localhost:8080/to-upper?str=ram&str=ptr&str=krishna' in browser, you will see the strings converted to uppercase in browser output.
["RAM","PTR","KRISHNA"]
You can download complete working application from below link.
https://github.com/harikrishna553/springboot/tree/master/rest/map-query-param-to-list
No comments:
Post a Comment