当前位置:首页 > 数据库

Spring居然还提供了这么好用的URL工具类

1. 前言

开发中我们经常会操作 URL,居然具类比如提取端口、还提提取路径以及最常用的供好L工提取参数等等。很多时候需要借助于一些第三方类库或者自己编写工具类来实现,居然具类今天胖哥给大家介绍一种方法,还提无需新的供好L工类库引入,只要你使用了 Spring Web 模块都可以轻松来完成对 URL 的居然具类组装和分解提取。

2. UriComponents

JDK 虽然提供了java.net.URI,还提但是供好L工终归还是不够强大,所以 Spring 封装了一个不可变量的居然具类 URI 表示org.springframework.web.util.UriComponents。

UriComponentsBuilder

我们可以利用其构造类UriComponentsBuilder从URI、还提Http 链接、供好L工URI 路径中初始化UriComponents。居然具类以 Http 链接为例:

String httpUrl= "https://felord.cn/spring-security/{ article}?还提version=1&timestamp=123123325"; UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(httpUrl).build(); 

如果不是 Http 就不能使用上面的方法了,需要使用fromUriString(String uri)。供好L工

我们也可以直接构造一个UriComponents:

UriComponents https = UriComponentsBuilder.newInstance()         .scheme("https")         .host("www.felord.cn")         .port("8080")         .path("/spring-boot/{ article}")         .queryParam("version","9527")         .encode(StandardCharsets.UTF_8)         .build(); // https://www.felord.cn:8080/spring-boot/{ article}?version=9527 

3. 操作 UriComponents

提取协议头

如果想提取协议头,如上面的例子我们想提取https。云服务器提供商

String scheme = uriComponents.getScheme(); // scheme = https System.out.println("scheme = " + scheme); 

提取 Host

获取host也是很常见的操作。

String host = uriComponents.getHost(); // host = felord.cn System.out.println("host = " + host); 

提取 Port

获取 uri 的端口。

int port = uriComponents.getPort(); // port = -1 System.out.println("port = " + port); 

但是很奇怪的是上面的是 -1,很多人误以为会是80。其实 Http 协议确实是80,但是java.net.URL#getPort()规定,若 URL 的实例未申明(省略)端口号,则返回值为-1。所以当返回了-1就等同于80,但是 URL 中不直接体现它们。

提取 Path

提取路径,这个还是经常用做判断的香港云服务器

String path = uriComponents.getPath(); // path = /spring-security/{ article} System.out.println("path = " + path); 

提取 Query

提取路径中的 Query 参数可以说是我们最常使用的功能了。

String query = uriComponents.getQuery(); // query = version=1&timestamp=123123325 System.out.println("query = " + query); 

更加合理的提取方式:

MultiValueMap<String, String> queryParams = uriComponents.getQueryParams(); // queryParams = { version=[1], timestamp=[123123325]} System.out.println("queryParams = " + queryParams); 

填充路径参数

假如我们想填充章节 2中代码中声明的的httpUrl中的路径参数{ article},我们可以这样:

UriComponents expand = uriComponents.expand("oauth2-authorization-request.html"); //expand = https://felord.cn/spring-security/oauth2-authorization-request.html?version=1&timestamp=123123325 System.out.println("expand = " + expand); 

4. 总结

Spring 作为目前 Java Web 开发中几乎不可避免的框架其实已经提供了很多有用的工具来方便我们操作。UriComponents只是其中一个用于操作URI的工具,今天我们对它的一些常用功能进行了演示,希望能够帮你解决一些相关的操作难题。

本文转载自微信公众号「码农小胖哥」,可以通过以下二维码关注。转载本文请联系码农小胖哥公众号。

分享到:

滇ICP备2023006006号-16