Spring 4 官方文档学习(十一)Web MVC 框架之URI Builder
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-uri-building
Spring MVC 提供了一种机制,可以构造和编码URI -- 使用UriComponentsBuilder和UriComponents。
例:
UriComponents uriComponents = UriComponentsBuilder.fromUriString(
"http://example.com/hotels/{hotel}/bookings/{booking}").build(); URI uri = uriComponents.expand("42", "21").encode().toUri();
嗯,expand()是用于替换所有的模板变量,encode默认使用UTF8编码。
注意,UriComponents是不可变的,expand()和encode()都是返回新的实例。
你还可以这样做:
UriComponents uriComponents = UriComponentsBuilder.newInstance()
.scheme("http").host("example.com").path("/hotels/{hotel}/bookings/{booking}").build()
.expand("42", "21")
.encode();
在Servlet环境中,使用子类ServletUriComponentsBuilder提供的静态工厂方法可以从一个Servlet request中获取有用的URI信息:
HttpServletRequest request = ... // Re-use host, scheme, port, path and query string
// Replace the "accountId" query param ServletUriComponentsBuilder ucb = ServletUriComponentsBuilder.fromRequest(request)
.replaceQueryParam("accountId", "{id}").build()
.expand("123")
.encode();
或者,你还可以选择复制这些可用信息的一个子集:
// Re-use host, port and context path
// Append "/accounts" to the path ServletUriComponentsBuilder ucb = ServletUriComponentsBuilder.fromContextPath(request)
.path("/accounts").build()
或者,当DispatcherServlet按名字被映射时(如 /main/*),你也可以拥有servlet映射的字面部分(???什么鬼):
// Re-use host, port, context path
// Append the literal part of the servlet mapping to the path
// Append "/accounts" to the path ServletUriComponentsBuilder ucb = ServletUriComponentsBuilder.fromServletMapping(request)
.path("/accounts").build()
1、构造连接到controllers和methods的URIs
Spring MVC也提供了一种机制,以构造到controller methods的连接。例如,当给定以下controller时:
@Controller
@RequestMapping("/hotels/{hotel}")
public class BookingController { @GetMapping("/bookings/{booking}")
public String getBooking(@PathVariable Long booking) { // ...
}
}
你可以通过名字引用该方法,来准备一个连接:
UriComponents uriComponents = MvcUriComponentsBuilder
.fromMethodName(BookingController.class, "getBooking", 21).buildAndExpand(42); URI uri = uriComponents.encode().toUri();
中上面的例子中,我们提供了实际的方法参数值,21。更进一步,我们还提供了42以填补剩余的URI变量,例如”hotel”。如果该方法拥有更多参数,你可以为那些不需要出现在URI中的参数提供null。一般来说,只有@PathVariable和@RequestParam参数与构建URL相关。
还有其他方式来使用MvcUriComponentsBuilder。例如,你可以使用一种技术族来模拟测试 -- 通过代理以避免通过名字引用controller name (下例假定已静态导入了MvcUriComponentsBuilder.on):
UriComponents uriComponents = MvcUriComponentsBuilder
.fromMethodCall(on(BookingController.class).getBooking(21)).buildAndExpand(42); URI uri = uriComponents.encode().toUri();
上例中,使用了MvcUriComponentsBuilder中的静态方法。在内部,他们依赖于ServletUriComponentsBuilder 来准备一个base URL -- 基于当前request的scheme、host、port、context path以及 servlet path。大多数时候这样很有效,然而,有时候也是不够的。例如,你可能在request的context之外(例如,准备links的批处理),或者你需要插入一个path前缀 (例如,locale前缀 -- 从request path中被移除过的,且需要被重新插入连接)。
这些情况下,你可以使用静态的”fromXxx”方法的重载 -- 那些接收一个UriComponentsBuilder的方法,来使用base URL。或者,你可以使用一个base URL来创建MvcUriComponentsBuilder的实例,然后使用该实例的”withXxx”方法。 例如:
UriComponentsBuilder base = ServletUriComponentsBuilder.fromCurrentContextPath().path("/en");
MvcUriComponentsBuilder builder = MvcUriComponentsBuilder.relativeTo(base);
builder.withMethodCall(on(BookingController.class).getBooking(21)).buildAndExpand(42);
URI uri = uriComponents.encode().toUri();
2、从views构建连接到controllers和methods的URIs
你还可以从views(如JSP、Thymeleaf、FreeMarker)构建到注解controllers的连接。使用MvcUriComponentsBuilder的fromMappingName(..)方法即可。
每个@RequestMapping都被给定了一个默认的名字 -- 基于class的大写字母和全方法名。例如,FooController中的getFoo方法,被赋予了名字”FC#getFoo”。这种策略可以被替换或定制--通过创建一个HandlerMethodMappingNamingStrategy实例,再将其插入你的RequestMappingHandlerMapping即可。默认的策略实现还要看一下@RequestMapping的name attribute,如果有则使用。这意味着,如果默认被赋予的映射名字与其他的发生了冲突(例如,重载的方法),你可以给该@RequestMapping显式的赋予一个name。
被赋予的请求映射名字,在启动时会被以TRACE级别记录。
Spring JSP tag库 提供了一个功能,叫做mvcUrl,可被用于基于该机制准备到controller methods的连接。
例如,当给定以下controller时:
@RequestMapping("/people/{id}/addresses")
public class PersonAddressController {
@RequestMapping("/{country}")
public HttpEntity getAddress(@PathVariable String country) { ... }
}
你可以准备一个连接--从JSP中,如下:
<%@ taglib uri="http://www.springframework.org/tags" prefix="s" %>
...
<a href="${s:mvcUrl('PAC#getAddress').arg(0,'US').buildAndExpand('123')}">Get Address</a>
上面的例子依赖于Spring 标签库(如 META-INF/spring.tld)中声明的mvcUrl JSP功能。
-- 好吧, 看完了,明白功能,但是,干嘛用的???测试吗?还是类似HttpClient或者RestTemplate的功能?
Spring 4 官方文档学习(十一)Web MVC 框架之URI Builder的更多相关文章
- Spring 4 官方文档学习(十一)Web MVC 框架之配置Spring MVC
内容列表: 启用MVC Java config 或 MVC XML namespace 修改已提供的配置 类型转换和格式化 校验 拦截器 内容协商 View Controllers View Reso ...
- Spring 4 官方文档学习(十一)Web MVC 框架之resolving views 解析视图
接前面的Spring 4 官方文档学习(十一)Web MVC 框架,那篇太长,故另起一篇. 针对web应用的所有的MVC框架,都会提供一种呈现views的方式.Spring提供了view resolv ...
- Spring 4 官方文档学习(十一)Web MVC 框架
介绍Spring Web MVC 框架 Spring Web MVC的特性 其他MVC实现的可插拔性 DispatcherServlet 在WebApplicationContext中的特殊的bean ...
- Spring 4 官方文档学习(十二)View技术
关键词:view technology.template.template engine.markup.内容较多,按需查用即可. 介绍 Thymeleaf Groovy Markup Template ...
- Spring Boot 官方文档学习(一)入门及使用
个人说明:本文内容都是从为知笔记上复制过来的,样式难免走样,以后再修改吧.另外,本文可以看作官方文档的选择性的翻译(大部分),以及个人使用经验及问题. 其他说明:如果对Spring Boot没有概念, ...
- Spring boot官方文档学习(一)
个人说明:本文内容都是从为知笔记上复制过来的,样式难免走样,以后再修改吧.另外,本文可以看作官方文档的选择性的翻译(大部分),以及个人使用经验及问题. 其他说明:如果对Spring Boot没有概念, ...
- Spring Framework 官方文档学习(四)之Validation、Data Binding、Type Conversion(二)
接前一篇 Spring Framework 官方文档学习(四)之Validation.Data Binding.Type Conversion(一) 本篇主要内容:Spring Type Conver ...
- Spring Framework 官方文档学习(四)之Validation、Data Binding、Type Conversion
本篇太乱,请移步: Spring Framework 官方文档学习(四)之Validation.Data Binding.Type Conversion(一) 写了删删了写,反复几次,对自己的描述很不 ...
- Spring Framework 官方文档学习(四)之Validation、Data Binding、Type Conversion(一)
题外话:本篇是对之前那篇的重排版.并拆分成两篇,免得没了看的兴趣. 前言 在Spring Framework官方文档中,这三者是放到一起讲的,但没有解释为什么放到一起.大概是默认了读者都是有相关经验的 ...
- Spring 4 官方文档学习(十一)Web MVC 框架之编码式Servlet容器初始化
在Servlet 3.0+ 环境中,你可以编码式配置Servlet容器,用来代替或者结合 web.xml文件.下面是注册DispatcherServlet : import org.springfra ...
随机推荐
- js面向对象编程:this究竟代表什么?
在js中this的使用方法非常让人迷惑.有些像Java或者C#中的this,但又不全然一样.依照流行的说法this总是指向调用方法的对象. 1.纯粹函数调用. function ListCommon2 ...
- win10 U盘安装ubuntu16.04双系统
所需工具U盘,软件ultralISO.ubuntu16.04,自己使用的系统是win10 一.制作U盘启动盘 打开ultraISO软件 2 2 3 4 开始写入—>直到完成大概五分的样子 二. ...
- cocos2dx 3.3多相机下_transformUpdated bug
uint32_t Node::processParentFlags(const Mat4& parentTransform, uint32_t parentFlags) { if(_using ...
- 【Android】3.1 创建本章示例项目
分类:C#.Android.VS2015.百度地图应用: 创建日期:2016-02-04 注意:本节是在完成了 3.0节介绍的预备知识的基础上继续实现的. 示例1--显示地图并为后续内容做准备 1.运 ...
- SourceInsight-显示文件完整路径
使用Source insight的时候想看文件的全路径,但是默认的是中间省略的路径,所以可以通过: 1.Options-->Preferences-->Display 设置Trim lon ...
- 新手MySQL工程师必备命令速查手册
MySQL的基本操作可以包括两个方面:MySQL常用语句如高频率使用的增删改查(CRUD)语句和MySQL高级功能,如存储过程.触发器.事务处理等.而这两个方面又可以细分如下: 1.MySQL常用语句 ...
- C#修改GIF大小同时保持GIF仍然可动和背景透明
/// <summary> /// 设置GIF大小 /// </summary> /// <param name="path">图片路径< ...
- gulp——myself配置
var gulp = require('gulp'), uglify = require('gulp-uglify'), concat = require('gulp-concat'); var pu ...
- 解析html文档的java库及范例
用这个工具jsoup <groupId>org.jsoup</groupId> <artifactId>jsoup</artifactId> <v ...
- 【转】VMware虚拟机中CentOS设置固定IP
因为需要配置固定IP,在网上找了很久终于找到一个可行的例子,自己配置成功了. 1.首先获取你的GATEWAY 方便后面在cento系统配置里使用选取菜单栏:Edit->Virtual Netwo ...