Map GET parameters to Object in Spring

It's possbile to map GET parameters to an object in Spring. It's really useful when we need to pass lots of parameters as query string e.g. submitting a search form with many parameters.

The following controller demonstrates this.
 
@RestController
@RequestMapping("hello")

public class MyController {

    @RequestMapping(value = "data", method = RequestMethod.GET)
    public MyRequest getData(MyRequest request){
            return request;     }

    public static class  MyRequest {
        private String name; 
        private int age;
        public String getName(){return this.name;}
        public int getAge(){return this.name;}
        public void setName(String name){this.name=name;} 
        public void setAge(int age){this.age=age;}
    }
}

Following GET request will create a MyRequest object with age=10 and name=Nayan


GET hello/data?age=10&name=Nayan

As we're sending the request object as response we'll get the following JSON from our controller method:

{
    "name":"Nayan",
    "age": 10
}

Comments

Popular posts from this blog

Run tasks in background in Spring

How to configure Wildfly 10 to use MySQL

Conditional field inclusion in Jackson and Spring Boot