一. @MatrixVariable的使用
/owners/42;q=11/pets/21;s=23;q=22
上述url需要使用springmvc的矩阵变量注解 - @MatrixVariable
springmvc的配置文件里添加 :<mvc:annotation-driven enable-matrix-variables=\"true\"/>
方式(一):
@ResponseBody
@RequestMapping(value = \"/owners/{ownerId}/pets/{petId}\")
public String test2(@PathVariable String ownerId, @MatrixVariable(pathVar = \"ownerId\", value = \"q\", required = false) String q1,
@PathVariable String petId, @MatrixVariable(pathVar = \"petId\", value = \"q\", required = false) String q2) {
System.out.println(ownerId);
System.out.println(q1);
System.out.println(petId);
System.out.println(q2);
return \"success\";
}
@PathVariable : 获取 {ownerId} 和 {petId} 这样的参数。
System.out.println(ownerId) ---- 输出:42
System.out.println(petId) ----- 输出:21
@MatrixVariable:矩阵变量
(1). pathVar = \"ownerId\" ,意味着处理范围为: 42;q=11
(2). value = \"q\", 指定pathVar里的 变量q。
(3). required = false , url可以没有这个变量q,默认是true。
上述程序将输出:42 11 21 22
方式(二):
@ResponseBody
@RequestMapping(value = \"/owners/{ownerId}/pets/{petId}\")
public String test2(@MatrixVariable Map<String, String> matrixVars,
@MatrixVariable(pathVar = \"petId\") Map<String, String> petMatrixVars) {
Iterator<Map.Entry<String, String>> iterator = matrixVars.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> mapEntries = iterator.next();
System.out.println(mapEntries.getKey() + \":\" + mapEntries.getValue());
}
Iterator<Map.Entry<String, String>> iterator = petMatrixVars.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> mapEntries = iterator.next();
System.out.println(mapEntries.getKey() + \":\" + mapEntries.getValue());
}
return \"success\";
}
用Map的方式接收参数。
不指定pathVar。将接收全部的{。。}参数。记录参数从左往右第一次出现的值。
比如:第一个Map输出:q = 11 s = 23
指定pathVar 为 {petId}。 将只接收其值。
比如第二个Map输出:s=23 q=22
二. Map的遍历方式
1. 迭代器方式:
public static void testMap() {
Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Integer> mapEntries = iterator.next();
System.out.println(mapEntries.getKey() + \"=\" + mapEntries.getValue());
}
}
2. 增强for循环:
public static void testMap2() {
for (Map.Entry<String, Integer> map : map.entrySet()) {
System.out.println(map.getKey() + \"=\" + map.getValue());
}
}
3. 增加for循环,分别遍历key value
public static void testMap3() {
for (String key : map.keySet()) {
System.out.println(key);
}
for (Integer value : map.values()) {
System.out.println(value);
}
}
4.遍历key,通过key找value,极不推荐的方式。
public static void testMap4() {
for (String key : map.keySet()) {
Integer value = map.get(key);
System.out.println(key + value);
}
}
继续阅读与本文标签相同的文章
上一篇 :
Gulp压缩问题整理及解决
下一篇 :
数据智能助力智慧航空:阿里云双十一特别访谈
-
Cassandra全球使用的公司及场景
2026-05-18栏目: 教程
-
如何创建云数据库RDS?
2026-05-18栏目: 教程
-
基于Selenium+Python的web自动化测试框架
2026-05-18栏目: 教程
-
阿里云MaxCompute 2019-8月刊
2026-05-18栏目: 教程
-
最佳 Linux 发行版汇总
2026-05-18栏目: 教程
