Home > Java > javaTutorial > body text

How Can I Bind a Complex Object as a GET @RequestParam in Spring MVC?

Mary-Kate Olsen
Release: 2024-11-20 15:48:13
Original
743 people have browsed it

How Can I Bind a Complex Object as a GET @RequestParam in Spring MVC?

Spring MVC: Binding Complex Objects as GET @RequestParam

Problem:

Consider a scenario where you have a page listing objects from a table. You need to add a form to filter the table using Ajax GET requests sent to a URL similar to:

http://foo.com/system/controller/action?page=1&prop1=x&prop2=y&prop3=z
Copy after login

Instead of using numerous @RequestParam parameters on the controller method, you'd like to bind the entire filter object directly.

Example:

Assuming you have a MyObject class defined as:

public class MyObject {
    private String prop1;
    private String prop2;
    private String prop3;

    // Getters and setters
    // ...
}
Copy after login

Your ideal controller method would look like this:

@RequestMapping(value = "/action")
public @ResponseBody List<MyObject> myAction(
    @RequestParam(value = "page", required = false) int page,
    MyObject myObject)
Copy after login
Copy after login

Solution:

Spring provides the capability to bind complex objects as @RequestParam parameters. To achieve this, simply remove the @RequestParam annotation from your method argument:

@RequestMapping(value = "/action")
public @ResponseBody List<MyObject> myAction(
    @RequestParam(value = "page", required = false) int page,
    MyObject myObject)
Copy after login
Copy after login

Spring will automatically bind the request parameters to your MyObject instance.

The above is the detailed content of How Can I Bind a Complex Object as a GET @RequestParam in Spring MVC?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template