如何将PageRequest对象转换为查询字符串?

3
我正在编写一个RESTful API,该API会消费另一个RESTful数据API,并且我正在使用Spring Data。
客户端使用查询参数发送页面请求,例如:
http://api.mysite.com/products?page=1&size=20&sort=id,asc&sort=name,desc 然后我将这些参数转换为PageRequest对象,并传递给服务层。
在服务层中,我想使用TestTemplate与使用URL的数据API进行交互,并且我需要如何将PageRequest对象转换为查询字符串,例如: page=1&size=20&sort=id,asc&sort=name,desc
然后我可以像下面这样请求数据:
restTemplate.getForEntity("http://data.mysite.com/products?page=1&size=20&sort=id,asc&sort=name,desc",String.class)                    
4个回答

3

我知道我的回答有点晚了,但是我也没有找到已经实现的方法来做到这一点。最终,我自己开发了一种例程来完成这个任务:

public static String encodeURLComponent(String component){
    try {
        return URLEncoder.encode(component, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException("You are dumm enough that you cannot spell UTF-8, are you?");
    }
}

public static String queryStringFromPageable(Pageable p){
    StringBuilder ans = new StringBuilder();
    ans.append("page=");
    ans.append(encodeURLComponent(p.getPageNumber() + ""));

    // No sorting
    if (p.getSort() == null)
        return ans.toString();

    // Sorting is specified
    for(Sort.Order o : p.getSort()){
        ans.append("&sort=");
        ans.append(encodeURLComponent(o.getProperty()));
        ans.append(",");
        ans.append(encodeURLComponent(o.getDirection().name()));
    }

    return ans.toString();
}

这并不完整,可能有一些细节我遗漏了,但对于我的用户案例(以及我认为大多数用户),这是有效的。


0

你可以将其视为新的:

new PageRequest(int page, int size)

在存储库层中,您可以这样编写:

Page<User> findByName(String name,Pageable page)

Pageable page 的位置,你需要传递 new PageRequest(int page, int size)

如果需要升序排序,请参考以下内容:

List<Todo> findByTitleOrderByTitleAsc(String title);

我觉得你没有理解我的问题,我的API需要将请求参数传递给另一个RESTful API。 - Harry

0

我认为您只需要遍历来自其他 API 请求的请求参数,然后将所有参数值传递到新 API 请求的新 URL 中。

伪代码可能是:

//all query params can be found in Request.QueryString
var queryParams = Request.QueryString; 

private string ParseIntoQuery(NameValueCollection values)
{
   //parse the identified parameters into a query string format 
   // (i.e. return "?paramName=paramValue&paramName2=paramValue2" etc.)
}

在你的代码中,你将会这样做:

restTemplate.getForEntity(urlAuthority + ParseIntoQuery(Request.QueryString));

就这么简单。希望回答了您的问题?


0
UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromHttpUrl("http://data.mysite.com/products");

    addRequestParam(uriComponentsBuilder, "page", pageable.getPageNumber());
    addRequestParam(uriComponentsBuilder, "size", pageable.getPageSize());

    String uri = uriComponentsBuilder.toUriString() + sortToString(pageable.getSort());

addRequestParam 方法:

private static void addRequestParam(UriComponentsBuilder uriBuilder, String parameterName, Object parameter) {
    if (parameter != null) {
        uriBuilder.queryParam(parameterName, parameter);
    }
}

实现sortToString(Sort sort)方法,如@Shalen所述。您需要获得类似于这样的内容:&sort=name,asc&sort=name2,desc。如果Sort为null,则返回"";


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接