21.7 URI构造

在Spring MVC中,使用了UriComponentsBuilderUriComponents两个类来提供一种构造和加密URI的机制。

比如,你可以通过一个URI模板字符串来填充并加密一个URI:

  1. UriComponents uriComponents = UriComponentsBuilder.fromUriString(
  2. "http://example.com/hotels/{hotel}/bookings/{booking}").build();
  3. URI uri = uriComponents.expand("42", "21").encode().toUri();

请注意UriComponents是不可变对象。因此expand()encode()操作在必要的时候会返回一个新的实例。

你也可以使用一个URI组件实例对象来实现URI的填充与加密:

  1. UriComponents uriComponents = UriComponentsBuilder.newInstance()
  2. .scheme("http").host("example.com").path("/hotels/{hotel}/bookings/{booking}").build()
  3. .expand("42", "21")
  4. .encode();

在Servlet环境下,ServletUriComponentsBuilder类提供了一个静态的工厂方法,可以用于从Servlet请求中获取URL信息:

  1. HttpServletRequest request = ...
  2. // 主机名、schema, 端口号、请求路径和查询字符串都重用请求里已有的值
  3. // 替换了其中的"accountId"查询参数
  4. ServletUriComponentsBuilder ucb = ServletUriComponentsBuilder.fromRequest(request)
  5. .replaceQueryParam("accountId", "{id}").build()
  6. .expand("123")
  7. .encode();

或者,你也可以选择只复用请求中一部分的信息:

  1. // 重用主机名、端口号和context path
  2. // 在路径后添加"/accounts"
  3. ServletUriComponentsBuilder ucb = ServletUriComponentsBuilder.fromContextPath(request)
  4. .path("/accounts").build()

或者,如果你的DispatcherServlet是通过名字(比如,/main/*)映射请求的,you can also have the literal part of the servlet mapping included:

  1. // Re-use host, port, context path
  2. // Append the literal part of the servlet mapping to the path
  3. // Append "/accounts" to the path
  4. ServletUriComponentsBuilder ucb = ServletUriComponentsBuilder.fromServletMapping(request)
  5. .path("/accounts").build()