Home > AI > Backend > SpringBoot > spring-web >

UriComponentsBuilder

Step 1: include the dependency

1
2
3
4
5
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>5.3.8</version>
</dependency>

Step 2: example codes

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
@SpringBootTest
class DemoApplicationTests {
 
    @Test
    void contextLoads() {
    }
 
    // Constructing a URI
    @Test
    public void constructURI() {
        UriComponents uriComponents = UriComponentsBuilder
                .newInstance()
                .scheme("http")
                .host("www.jobyme88.com")
                .path("/junit-5")
                .build();
 
        assertEquals("http://www.jobyme88.com/junit-5", uriComponents.toUriString());
    }
 
 
    // Constructing an Encoded URI
    @Test
    public void constructURIEncoded() {
        UriComponents uriComponents = UriComponentsBuilder
                .newInstance()
                .scheme("http")
                .host("www.jobyme88.com")
                .path("/junit 5")
                .build()
                .encode();
 
        assertEquals("http://www.jobyme88.com/junit%205", uriComponents.toUriString());
    }
 
 
    // Constructing a URI from a Template
    @Test
    public void constructURIFromTemplate() {
        UriComponents uriComponents = UriComponentsBuilder
                .newInstance()
                .scheme("http")
                .host("www.jobyme88.com")
                .path("/{article-name}")
                .buildAndExpand("junit-5"); // fill the path template
 
        assertEquals("http://www.jobyme88.com/junit-5", uriComponents.toUriString());
    }
 
    // Constructing a URI With Query Parameters
    @Test
    public void constructUriWithQueryParameter() {
        UriComponents uriComponents = UriComponentsBuilder
                .newInstance()
                .scheme("http")
                .host("www.google.com")
                .path("/")
                .query("q={keyword}")
                .buildAndExpand("jobyme88.com");
 
        assertEquals("http://www.google.com/?q=jobyme88.com", uriComponents.toUriString());
    }
 
 
    // Expanding a URI With Regular Expressions
    @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());
    }
 
}

Leave a Reply