Construct or build URI from request

Unlike constructing or building a URI in a console or client app, it could be redundent setting root elements if you are working in a servlet environment. Luckly in Spring there is ServletUriComponentsBuilder sub-class that provides static factory methods to copy available URL information from a Servlet requests.

Append path

@Test
public void create_URI_from_http_request () {
    
    MockHttpServletRequest request = new MockHttpServletRequest();
    
    UriComponents ucb =
            ServletUriComponentsBuilder
                .fromContextPath(request)
                .path("/examples/java")
                .build();

    URI uri = ucb.toUri();
    
    assertEquals("http://localhost/examples/java", uri.toString());
}

Replace query parameter

@Test
public void replace_query_parameter () {
    
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setQueryString("primaryKey=987");
    
    UriComponents ucb =
            ServletUriComponentsBuilder
                .fromRequest(request)
                .replaceQueryParam("primaryKey", "{id}")
                .build()
                .expand("123")
                .encode();
    
    assertEquals("http://localhost?primaryKey=123", ucb.toString());
}

Replace path

@Test
public void replace_path () {

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setPathInfo("/java/examples");

    UriComponents ucb =
            ServletUriComponentsBuilder
                .fromRequest(request)
                .replacePath("/java/exercises")
                .build()
                .encode();
    
    URI uri = ucb.toUri();
    
    assertEquals("http://localhost/java/exercises", uri.toString());
}