@PathVariable获取路径变量的值
控制器方法拦截的请求地址可以设置变量,那么该控制器方法就可以拦截一批url。
控制器方法拦截的url占位符用{}表示,比如/users/{userId}可以拦截/users/ccc、/users/aaa、/users/ddd等请求,当控制器方法需要获取准确的请求url就需要使用@PathVariable修饰方法参数。
方法参数和url既可以基于同名映射,也可以为@PathVariable指定属性value或者name表示被修饰的参数对应的路径名(占位符名字)
栗子:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>title</title>
<link rel="stylesheet"
href="${pageContext.request.contextPath}/resource/bootstrap-4.3.1/css/bootstrap.css"/>
<script src="${pageContext.request.contextPath}/resource/jquery-3.4.1.min.js"></script>
<script src="${pageContext.request.contextPath}/resource/bootstrap-4.3.1/js/bootstrap.js"></script>
</head>
<body>
<img src="${pageContext.request.contextPath}/images/东华理工大学.jpg"><br/>
<a href="${pageContext.request.contextPath}/users/lyx/books/fkjava" class="btn btn-primary">用户1</a> 
<a href="${pageContext.request.contextPath}/users/sqq/books/ToLive" class="btn btn-primary">用户2</a><br/>
</body>
</html>
@Controller
@RequestMapping("/users/{userId}")
public class UserController
{
@RequestMapping(path = "/books/{bookId}")
public String queryUser(@PathVariable String userId,@PathVariable("bookId") String book, Model model)
{
model.addAttribute("user",userId);
model.addAttribute("book",book);
return "queryResult";
}
}
@PathVariable处理正则表达式
控制器方法拦截的url不仅可包含占位符,还可以用正则表达式(其实正则表达式也相当于占位符)
直接看栗子把:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>title</title>
<link rel="stylesheet"
href="${pageContext.request.contextPath}/resource/bootstrap-4.3.1/css/bootstrap.css"/>
<script src="${pageContext.request.contextPath}/resource/jquery-3.4.1.min.js"></script>
<script src="${pageContext.request.contextPath}/resource/bootstrap-4.3.1/js/bootstrap.js"></script>
</head>
<body>
<img src="${pageContext.request.contextPath}/images/东华理工大学.jpg" width="320px" height="80px"><br/><br/>
<a href="${pageContext.request.contextPath}/spring-web-5.1.9.jar" class="btn btn-primary">spring</a> 
<a href="${pageContext.request.contextPath}/mybatis-3.5.2.zip" class="btn btn-primary">mybatis</a><br/>
</body>
</html>
@Controller
public class UserController
{
@RequestMapping(path = "{arName:[a-zA-Z-]+}-{version:\\d\\.\\d\\.\\d}{extension:\\.[a-z]+}")
public String queryUser(@PathVariable String arName,@PathVariable String version,
@PathVariable String extension, Model model)
{
model.addAttribute("arName",arName);//spring-web
model.addAttribute("version",version);//5.1.9
model.addAttribute("extension",extension);//.jar
return "queryResult";
}
}