Spring 中 UriComponentsBuilder 类示例
文本我们主要介绍Spring 中 UriComponentsBuilder 类。通过多个示例让你理解不同实现。UriComponentsBuilder构建器与UriComponents类(不可变的URI组件容器)一起工作。通过细粒度的控制URI的各个要素,如构建、扩展模板变量以及编码,UriComponentsBuilder 类用于创建UriComponents实例。
Maven依赖
为了使用构建器,我们需要增加下面依赖:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.4.RELEASE</version>
</dependency>
读者根据需要引用最新版本。
使用示例
我们几个UriComponentsBuilder实战示例,包括对URI组件中不允许字符进行编码开始,然后动态地替换URL的部分等。使用UriComponentsBuilder类的最大好处是方便地注入到Controller中:
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity createCustomer(UriComponentsBuilder builder) {
// implementation
}
下面开始逐个示例说明,我们使用JUnit框架进行测试。
构建URI
先从最简单的开始,使用UriComponentsBuilder 构建简单链接:
@Test
public void constructUri() {
UriComponents uriComponents = UriComponentsBuilder.newInstance()
.scheme("http").host("www.baeldung.com").path("/junit-5").build();
assertEquals("/junit-5", uriComponents.toUriString());
}
首先我们创建UriComponentsBuilder类新的实例,然后给目标请求提供 scheme 类型、 host以及path 。该示例在执行请求转发时非常有用。
构建编码的URI
为了创建简单链接,我们有时需要最最终结果进行编码,请看示例:
@Test
public void constructUriEncoded() {
UriComponents uriComponents = UriComponentsBuilder.newInstance()
.scheme("http").host("www.baeldung.com").path("/junit 5").build().encode();
assertEquals("/junit%205", uriComponents.toUriString());
}
与上面示例不同的是,我们在单词之间增加空格。根据RFC 3986规范,这是不允许。我们需要使用encode方法对链接进行编码得到有效链接。
从模板构建URI
URI模板可用于URI中大多数元素组件,但它们值被限定于我们称为模板的特定元素,通过示例进行说明:
@Test
public void constructUriFromTemplate() {
UriComponents uriComponents = UriComponentsBuilder.newInstance()
.scheme("http").host("www.baeldung.com").path("/{article-name}")
.buildAndExpand("junit-5");
assertEquals("/junit-5", uriComponents.toUriString());
}
本例不同的是声明path并构建最终的URI。在path方法中模板中的{…}被替换。请注意,可以有多个关键字进行模板替换,同时path可以是相对路径。
当传递model对象给Spring Controller并构建URI时,该示例非常有帮助。
使用查询参数构建URI
使用查询参数构建URI非常常见。使用UriComponentsBuilder类的query方法指定查询参数。请看下面示例:
@Test
public void constructUriWithQueryParameter() {
UriComponents uriComponents = UriComponentsBuilder.newInstance()
.scheme("http").host("www.google.com")
.path("/").query("q={keyword}").buildAndExpand("baeldung");
assertEquals("http://www.google.com/?q=baeldung", uriComponents.toUriString());
}
查询将被加到链接的主体部分。我们可以使用{…}提供多个查询参数,然后在buildAndExpand方法中被给定的关键字替换。UriComponentsBuilder的这个实现可以用于构建REST API的查询语言。
使用正则表达式扩展URI
最后我们看如何使用正则表达式验证URI,仅当正则验证通过才扩展 uriComponents:
@Test
public void expandWithRegexVar() {
String template = "/myurl/{name:[a-z]{1,5}}/show";
UriComponents uriComponents = UriComponentsBuilder.fromUriString(template)
.build();
uriComponents = uriComponents.expand(Collections.singletonMap("name", "test"));
assertEquals("/myurl/test/show", uriComponents.getPath());
}
在上面的示例中,我们可以看到链接的中间部分需要a-z的字母,长度范围在1-5之间。此外,我们正在使用singletonMap,将关键字名称替换为value test。
当我们允许用户动态地指定链接时,这个示例特别有用,但是我们希望提供一种只有有效链接才能在web应用程序中工作的安全性。
总结
本教程展示了UriComponentsBuilder几个实际常用示例。UriComponentsBuilder的主要优点是灵活地使用URI模板变量,以及可以将其直接注入Spring控制器方法。