java @RequestParam to object
javaIn 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.
Other Article on Tag java
- - after and before in java date
- - am pm java date format
- - apk minecraft java edition
- - as been blocked by CORS policy Response to preflight request doesn't pass access control check It does not have HTTP ok status
- - bubble sort in java
- - Can I compile and run a spring boot jar from inside another spring boot application
- - convert java date to localdate
- - design patterns in java
- - encrypt by java and decrypt by node
- - exception handling in java