简体   繁体   English

Spring MVC绑定请求参数到POJO字段

[英]Spring MVC Binding Request parameters to POJO fields

I want a controller with the following mapping (incomplete): 我想要具有以下映射(不完整)的控制器:

@GetMapping(/searchitems)
public @ResponseBody Page<Item> get(Item probe)

From the Item probe parameter I want to query by example in a repository of items and return the result. 我想从Item probe参数中通过示例在项目存储库中进行查询并返回结果。

Question: 题:

How can I complete the mapping above for a search URL? 如何完成上面的搜索URL映射? As search URL I was thinking something like /searchitems?itemAttributeA=foo&itemAttributeB=bar&...itemAttributeZ=xyz . 作为搜索URL,我在想类似/searchitems?itemAttributeA=foo&itemAttributeB=bar&...itemAttributeZ=xyz东西。 How can I tell spring to inject the passed request parameters into the Item probe fields with the same names? 如何告诉spring将传递的请求参数注入到具有相同名称的Item probe字段中?

添加@ModelAttribute应该将各个请求参数绑定到您的Item POJO中。

public @ResponseBody Page<Item> get(@ModelAttribute Item probe)

You can create a POJO and pass as a parameter in the controller class. 您可以创建一个POJO并作为参数传递给控制器​​类。 Pojo should have the fields which you want to read and set. Pojo应该具有您要阅读和设置的字段。 Spring will read and map those attributes in the Pojo which you will define as the request. Spring将在Pojo中读取并映射这些属性,您将它们定义为请求。

 @GetMapping(/searchitems)
 public ResponseEntity<List<Items>> searchItems(ItemRequest       itemRequest) {
 }

Only thing needs to be taken care is to check for binding result. 唯一需要注意的是检查绑定结果。 If there are errors, we need to stop the request and handle or throw. 如果有错误,我们需要停止请求并处理或抛出。

For eg All of the below attributes in the URL will be set in the Pojo. 例如,URL中的以下所有属性都将在Pojo中设置。

https://domain/search-items?pageNumber=1&sortOrder=ascending&itemName=test&itemType=apparel&sortField=itemId&pageSize=5 https:// domain / search-items?pageNumber = 1&sortOrder = ascending&itemName = test&itemType = apparel&sortField = itemId&pageSize = 5

You can use @RequestParam for this. 您可以为此使用@RequestParam

public @ResponseBody Page<Item> get(@RequestParam("itemAttributeA") String itemAttributeA , 
                                    @RequestParam("itemAttributeB") String itemAttributeB,...)

i have a question. 我有个问题。 I am moving from JAX RS which has java.ws.rs.QueryParam classes to accept param A into Set/Get . 我从具有java.ws.rs.QueryParam类的JAX RS迁移,将参数A接受到Set / Get中。 Can you advise is there any equivalent in Spring Boot? 你能告诉我Spring Boot中有什么等效的东西吗?

I tried with @named,@AliasFor(value="documentId ") but no luck 我尝试使用@ named,@ AliasFor(value =“ documentId”),但没有运气

@QueryParam("paramA") @FormParam("paramA") @QueryParam(“ paramA”)@FormParam(“ paramA”)

public void setDocumentId(String paramB) {
    this.documentId = paramB;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM