UriComponentsBuilder和UriComponents url编码

Spring MVC 提供了一种机制,可以构造和编码URI -- 使用UriComponentsBuilder和UriComponents。

功能相当于 urlencode()函数,对url进行编码, 但同时还支持变量替换

UriComponents uriComponents = UriComponentsBuilder.fromUriString(
        "http://example.com/hotels/{hotel}/bookings/{booking}").build();

URI uri = uriComponents.expand("42", "21").encode().toUri();

  

嗯,expand()是用于替换所有的模板变量,encode默认使用UTF8编码。

注意,UriComponents是不可变的,expand()和encode()都是返回新的实例。

你还可以这样做:

UriComponents uriComponents = UriComponentsBuilder.newInstance()
        .scheme("http").host("example.com").path("/hotels/{hotel}/bookings/{booking}").build()
        .expand("42", "21")
        .encode();

  

在Servlet环境中,使用子类ServletUriComponentsBuilder提供的静态工厂方法可以从一个Servlet request中获取有用的URI信息:

HttpServletRequest request = ...

// Re-use host, scheme, port, path and query string
// Replace the "accountId" query param

ServletUriComponentsBuilder ucb = ServletUriComponentsBuilder.fromRequest(request)
        .replaceQueryParam("accountId", "{id}").build()
        .expand("123")
        .encode();

  

https://www.cnblogs.com/larryzeal/p/6131664.html

扫描二维码关注公众号,回复: 1494995 查看本文章

猜你喜欢

转载自www.cnblogs.com/achengmu/p/9145647.html
今日推荐