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

问题描述 投票:2回答:3

我正在编写一个RESTful API,它使用另一个RESTful Data API,而我正在使用Spring Data。

客户端使用查询参数发送页面请求,如: http://api.mysite.com/products?page=1&size=20&sort=id,asc&sort=name,desc

我将params转换为PageRequest对象并将其传输到服务层。

在服务中,我想使用TestTemplate与使用URL的Data API进行交互,如何将PageRequest对象转换为类似的查询字符串

页= 1&大小= 20&排序= ID,ASC&排序=名,降序

然后我可以请求如下数据:

restTemplate.getForEntity("http://data.mysite.com/products?page=1&size=20&sort=id,asc&sort=name,desc",String.class)                    
rest spring-data spring-data-jpa
3个回答
0
投票

你可以传递新的:

new PageRequest(int page,int size)

在存储库层中,您可以写为:

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

代替Pageable页面,你必须传递新的PageRequest(int page,int size)

对于升序,您可以参考:

List<Todo> findByTitleOrderByTitleAsc(String title);

0
投票

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

sudo代码可能是:

//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
投票

我知道我对这个答案有点迟,但我也无法找到已经实现过的方法。我最终开发了自己的例行程序:

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();
}

它不完整,可能有一些我缺少的细节,但对于我的用户案例(我认为对于他们中的大多数)这是有效的。

© www.soinside.com 2019 - 2024. All rights reserved.