zhaopinxinle.com

Exploring the Convenience of URI Manipulation Tools in Spring

Written on

Chapter 1: Introduction to URI Components

Spring 2.7.161 offers powerful tools for URI manipulation that make development easier. One such tool is the UriComponentsBuilder, which constructs URIs from templates that include variables. Below is an example of its usage:

UriComponents uriComponents = UriComponentsBuilder

.fromUriString("http://www.test.com/users/{name}")

.queryParam("q", "{q}")

.encode()

.build();

URI uri = uriComponents.expand("name", "pack").toUri();

System.out.println(uri);

Output:

http://www.test.com/users/name?q=pack

For even more brevity, you can directly build the URI like this:

URI uri = UriComponentsBuilder

.fromUriString("http://www.test.com/users/{name}")

.queryParam("q", "{q}")

.build("name", "pack");

System.out.println(uri);

Output:

http://www.test.com/users/name?q=pack

Utilizing the template directly can further simplify the code:

URI uri = UriComponentsBuilder

.fromUriString("http://www.pack.com/users/{name}?q={q}")

.build("name", "pack");

Chapter 2: Using UriBuilder

UriComponentsBuilder implements the UriBuilder interface. Alternatively, UriBuilderFactory can be employed to generate a UriBuilder. Together, these tools allow for a configurable way to create URIs from templates, accommodating shared settings such as base URLs and encoding preferences.

You can customize URI preparation in RestTemplate and WebClient using UriBuilderFactory. The DefaultUriBuilderFactory, which is the standard implementation, utilizes UriComponentsBuilder and provides shared configuration options. Here's how you can apply it with RestTemplate:

String baseUrl = "http://www.bing.com";

DefaultUriBuilderFactory factory = new DefaultUriBuilderFactory(baseUrl);

factory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.TEMPLATE_AND_VALUES);

RestTemplate restTemplate = new RestTemplate();

restTemplate.setUriTemplateHandler(factory);

Using it with WebClient looks like this:

DefaultUriBuilderFactory factory = new DefaultUriBuilderFactory(baseUrl);

factory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.TEMPLATE_AND_VALUES);

WebClient client = WebClient.builder().uriBuilderFactory(factory).build();

You can also create a URI directly with the DefaultUriBuilderFactory:

DefaultUriBuilderFactory uriBuilderFactory = new DefaultUriBuilderFactory(baseUrl);

URI uri = uriBuilderFactory.uriString("/users/{name}")

.queryParam("q", "{q}")

.build("name", "pack");

System.out.println(uri);

Output:

http://www.bing.com/users/name?q=pack

Chapter 3: Understanding URI Encoding

UriComponentsBuilder offers two encoding levels:

  1. `UriComponentsBuilder#encode()`: This method pre-encodes the URI template and strictly encodes URI variables during the expansion process.
  2. `UriComponents#encode()`: This method encodes URI components after the URI variables have been expanded.

Both methods replace non-ASCII and illegal characters with escaped octets. However, the first option treats URI variables as completely encoded data, while the second is useful when the variables contain reserved characters intentionally. Here’s an example:

URI uri = UriComponentsBuilder.fromPath("/users-list/{name}")

.queryParam("q", "{q}")

.encode()

.buildAndExpand("name", "pack")

.toUri();

System.out.println(uri);

Output:

/users-list/name?q=pack

A simplified version can be created as follows:

URI uri = UriComponentsBuilder.fromPath("/users-list/{name}")

.queryParam("q", "{q}")

.build("name", "pack");

A complete URI template looks like this:

URI uri = UriComponentsBuilder.fromUriString("/users-list/{name}?q={q}")

.build("name", "pack");

Chapter 4: Creating Servlet Requests

You can generate URIs relative to the current request using ServletUriComponentsBuilder:

MockHttpServletRequest request = new MockHttpServletRequest();

request.setRequestURI("/users");

URI uri = ServletUriComponentsBuilder

.fromRequest(request)

.replaceQueryParam("id", "{id}")

.build("666");

System.out.println(uri);

Output:

http://localhost/users?id=666

Creating URIs in relation to the context path can be done like this:

URI uri = ServletUriComponentsBuilder.fromContextPath(request)

.path("/users")

.build()

.toUri();

Chapter 5: Linking Controllers

Spring MVC offers a method to link to Controller actions. For instance:

MockHttpServletRequest request = new MockHttpServletRequest();

ServletRequestAttributes requestAttribute = new ServletRequestAttributes(request);

RequestContextHolder.setRequestAttributes(requestAttribute);

UriComponents uriComponents = MvcUriComponentsBuilder

.fromMethodName(UserController.class, "queryById", 666L).buildAndExpand();

URI uri = uriComponents.encode().toUri();

System.out.println(uri);

Output:

http://localhost/users/666

I hope this information proves helpful!

The first video, "201720 Excel Guided Project 4-3", provides a guided tutorial on utilizing Excel for project management tasks, demonstrating practical applications and functions.

The second video, "The 12 Best Commands of the Terminal | Developer Tips #3", highlights essential terminal commands that every developer should know to enhance productivity and efficiency.

Share the page:

Twitter Facebook Reddit LinkIn

-----------------------

Recent Post:

# Unlock Business Breakthroughs: Embrace Experimentation for Growth

Discover how adopting an experimental mindset can transform your approach to business decisions and lead to significant breakthroughs.

Titanic II: The Journey to Recreate a Historic Voyage

Titanic II is set to sail in 2022, offering a unique journey that mirrors the original RMS Titanic, with modern safety and nostalgic experiences.

# Reclaiming Balance: A Journey from Burnout to Self-Kindness

Discover how self-kindness and balance transformed a relentless pursuit of perfection into a fulfilling life.