当前位置: 首页 > 科技观察

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

时间:2023-03-12 12:45:09 科技观察

1。前言在开发中,我们经常对URL进行操作,比如提取端口、提取路径,以及最常用的提取参数。很多时候需要借助一些第三方类库或者自己编写工具类。今天胖哥给大家介绍一个方法,不需要引入新的类库。只要使用SpringWeb模块,就可以轻松完成URL。组装和拆卸提取。2、UriComponentsJDK虽然提供了java.net.URI,但是还是不够强大,所以Spring封装了一个不可变的URI来表示org.springframework.web.util.UriComponents。UriComponentsBuilder我们可以使用它的构造类UriComponentsBuilder从URI、Http链接和URI路径来初始化UriComponents。以Http链接为例:StringhttpUrl="https://felord.cn/spring-security/{article}?version=1×tamp=123123325";UriComponentsuriComponents=UriComponentsBuilder.fromHttpUrl(httpUrl).build();如果不是Http,则不能使用上面的方法后,需要使用fromUriString(Stringuri)。我们也可以直接构造一个UriComponents:UriComponentshttps=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=95273。操作UriComponents提取协议头如果要提取协议头,如上例,我们要提取https。Stringscheme=uriComponents.getScheme();//scheme=httpsSystem.out.println("scheme="+scheme);ExtractingHost获取host也是一个很常见的操作。Stringhost=uriComponents.getHost();//host=felord.cnSystem.out.println("host="+host);ExtractPort得到uri的端口。intport=uriComponents.getPort();//port=-1System.out.println("port="+port);但是很奇怪上面是-1,很多人误以为会是80。其实Http协议确实是80,但是java.net.URL#getPort()规定如果URL实例没有声明(省略)端口号,返回值为-1。所以当返回-1时,它相当于80,但它们并没有直接反映在URL中。ExtractPath提取路径,常用于判断。Stringpath=uriComponents.getPath();//path=/spring-security/{article}System.out.println("path="+path);ExtractQuery提取路径中的Query参数可以说是我们现在最常用的功能了。Stringquery=uriComponents.getQuery();//query=version=1×tamp=123123325System.out.println("query="+query);更合理的提取方式:MultiValueMapqueryParams=uriComponents.getQueryParams();//queryParams={version=[1],timestamp=[123123325]}System.out.println("queryParams="+queryParams);填写路径参数如果我们想在第2章参数{article}的代码声明的httpUrl中填写路径,可以这样做:UriComponentsexpand=uriComponents.expand("oauth2-authorization-request.html");//expand=https://felord.cn/spring-security/oauth2-authorization-request.html?version=1×tamp=123123325System.out.println("expand="+expand);4.总结作为JavaWeb开发中几乎不可避免的框架,Spring其实已经提供了很多有用的工具来方便我们的操作。UriComponents只是操作URI的工具之一。今天我们就来演示一下它的一些常用功能,希望能帮助大家解决一些相关的操作问题。本文转载自微信公众号“码农小胖哥”,可通过以下二维码关注。转载本文请联系码农小胖公众号。

猜你喜欢