Spring MVC bean映射到HTTP GET请求参数,类似于@BeanParam

rus*_*tyx 8 rest spring spring-mvc

在Jersey中有一个@BeanParam注释,我可以将请求参数映射到bean属性.

在Spring中,我只能找到@RequestBody哪个显然适用于请求体而不是请求参数.

有没有办法让请求参数使用Spring映射到bean?

Ral*_*lph 17

只需使用名称与您的请求参数匹配的字段创建Pojo Java Bean.

然后使用此类作为请求处理程序方法的参数(不带任何其他注释)

public class Example {
   private String x;
   private Integer y;

   //Constructor without parameter needed!
   public Example(){}

   //Getter + Setter
}

@Controller
@RequestMapping("someUrl")
public class SomeController {

    @RequestMapping
    public String someHandler (Example example) {
          System.out.println(example.getX());
          return "redirect:someOtherUrl";
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 请注意,这相当于使用`@ ModelAttribute`注释参数. (2认同)