Java 如何使用 Spring HATEOAS 添加查询字符串参数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22614854/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 16:52:23  来源:igfitidea点击:

How to add query string parameters with Spring HATEOAS?

javaspringspring-hateoas

提问by Neuquino

I'm trying to generate a link to search resources. So, I want to create a resource that provides a link to my search:

我正在尝试生成搜索资源的链接。所以,我想创建一个资源来提供我的搜索链接:

POST /resourcesearch
{param1: "value1",param2:"value2"}

The response should be:

响应应该是:

{"links":[
  {
    "rel":"self",
    "href":"http://localhost:8080/resourcesearch"
  },
  {
    "rel":"resources",
    "href":"http://localhost:8080/resources?param1=value1&param2=value2"
  }
}

Here is my code:

这是我的代码:

@Controller
@RequestMapping("/resourcesearch")
public class ResourceSearchController{
  @RequestMapping(method = RequestMethod.POST) 
  public ResponseEntity<ResourceSupport> createResourceSearch(@RequestBody ResourceDTO dto){
    ResourceSupport resource = new ResourceSupport();
    //... do something here to build query string based on "dto"
    resource.add(linkTo(ResourceController.class).withRel("resources"));
    return new ResponseEntity<ResourceSupport>(resource, HttpStatus.CREATED);
  }
}
===========================================
@Controller
@RequestMapping("/resources")
public class ResourceController{
  @RequestMapping(method = RequestMethod.GET)
  public ResponseEntity<CollectionDTO> listResources(@RequestParam("param1") String param1, @RequestParam("param2") String param2){
    ...
  }
}

The thing is that I can't figure out how to add query string parameters to the url in the line:

问题是我无法弄清楚如何将查询字符串参数添加到该行中的 url:

resource.add(linkTo(ResourceController.class).withRel("resources"));

Because the result of that line is:

因为该行的结果是:

{
  "links" : [
    {
      "rel":"resources",
      "href":"http://localhost:8080/resources"
    }
  ]
}

Any ideas?

有任何想法吗?

采纳答案by TJ-

There are a couple of (potential) mismatches between the names that you have used in your resources and desired output, hence I am not able to map that very well.

您在资源中使用的名称与所需的输出之间存在一些(潜在的)不匹配,因此我无法很好地映射。

Anyway, you need to use the methodOnof ControllerLinkBuilder. Here'sa good example that should get you going.

无论如何,您需要使用methodOnof ControllerLinkBuilder这是一个很好的例子,应该可以帮助你前进。

For more complex examples, the unit testsfor Spring HATEOAS are a good source of examples.

对于更复杂的示例,Spring HATEOAS的单元测试是一个很好的示例来源。