Skip to content
Advertisement

Get multiple RequestParam of one variable

I’m trying to build a multifunctional search method using MongoTemplate, Query and Criteria.

Here is my RequestMapping for variable search:

public Page<Users>getUsers(
            @RequestParam(value = "name", required = false) 

String name) {
    
    Query query = new Query();
    Criteria criteria = new Criteria();
    criteria = criteria.where("name").regex(".*" + name + ".*","i");
    query.addCriteria(criteria);

I want to be able to search lastName with multiple request parameters. For example, I want to find everyone with lastname “Smith” and “Johnson”.

Something like this:

@RequestParam(value = "lastName", required = false) List<String> lastName) {

Query query = new Query();
Criteria criteria = new Criteria();
criteria = criteria.where("lastName").regex(do something different..);
query.addCriteria(criteria);

URL will be: http://localhost:8080/get?lastName=Smith&lastName=Johnson

This is where I found Mapping a Multi-Value Parameter https://www.baeldung.com/spring-request-param , but it is not clear how exactly does it work. If someone can provide a link with full example (repository, handler and stuff), please do.

Advertisement

Answer

this is how i did it:

if (CollectionUtils.isNotEmpty(lastName)) {
        Criteria lastNameCriteria = new Criteria();
        lastNameCriteria = lastNameCriteria.where("lastName").in(lastName.toArray());
        criterias.add(lastNameCriteria);
    }
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement