@PathVariable注解實現(xiàn)動態(tài)傳值
動態(tài)傳值
1
2
3
4
|
@RequestMapping (value= "/Test/{id}" ) public void Test( @PathVariable Integer id){ ............. } |
用法
在頁面表單的action中,寫controller中對應的方法名
1
2
3
4
5
|
TestController.java @RequestMapping (value= "/{methodName}" ) public String TZ( @PathVariable String methodName){ return methodName; } |
動態(tài)參數(shù)使用@PathVariable解析
現(xiàn)在有如下的一條超鏈接
1
2
|
< a href = "<c:url value=" rel = "external nofollow" /actions/article/readArticle/${article.id}"/> " target="_blank">${article.title}</ a > |
這條超鏈接的特點就是在URL路徑中添加了EL表達式解析出來的id值。
因此,在SpringMVC的Controller層中,需要解析它,使用@PathVariable("articleId") Long articleId 來解析。
@PathVariable是專門用來解析URL請求中的動態(tài)參數(shù)。
在Controller層的代碼如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
public static final String URL_ARTICLE_READ = "article/readArticle/{articleId}" ; /** * 去文章詳情頁面 * 根據(jù)URL路徑中指定的文章ID號,去獲取制定文章的內容 * * @param articleId 指定的文章的ID號 * @return 獲取此文章的數(shù)據(jù),并去文章詳情頁面 */ @RequestMapping (value = {URL_ARTICLE_READ} ) public ModelAndView readArticle( @PathVariable ( "articleId" ) Long articleId){ LOGGER.info( "enter article detail page, articleId = {}" ,articleId); final Article article = articleService.getArticleById(articleId); ... } |
這樣,頁面上的${article.id}的值,就最終映射到了Java中的Long articleId 上了。
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/JaydenWang5310/article/details/78110002