Home >Java >javaTutorial >How Can I Bind a Complex Object as a GET @RequestParam in Spring MVC?

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-20 15:48:13837browse

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

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
    // ...
}

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)

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)

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!

Statement:
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