java @RequestParam to object

java

In Java, you can use the @RequestParam annotation to bind query string parameters or form data to method parameters in a Spring MVC controller. If you want to bind the request parameters to an object, you can use the @ModelAttribute annotation along with the object type as a parameter of the controller method.

Here’s an example:

Suppose you have an object Person with two fields, name and age. You want to bind the request parameters name and age to an instance of Person using @RequestParam.

public class Person {
    private String name;
    private int age;

    // getters and setters
}

@Controller
public class MyController {

    @GetMapping("/person")
    public String getPerson(@RequestParam String name, @RequestParam int age) {
        Person person = new Person();
        person.setName(name);
        person.setAge(age);

        // do something with person object

        return "someView";
    }
}

In the above example, @RequestParam is used to bind the request parameters name and age to the method parameters name and age. However, if you want to bind the parameters to a Person object, you can use the @ModelAttribute annotation as follows:

@Controller
public class MyController {

    @GetMapping("/person")
    public String getPerson(@ModelAttribute Person person) {

        // do something with person object

        return "someView";
    }
}

In this example, Spring MVC will create an instance of Person and bind the request parameters name and age to the corresponding fields of the Person object. Note that the field names of the Person class must match the parameter names in the request for this to work.