好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

使用@PathVariable注解如何实现动态传值

@PathVariable注解实现动态传值

动态传值

?

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;

}

动态参数使用@PathVariable解析

现在有如下的一条超链接

?

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请求中的动态参数。

在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}" ;

     /**

      * 去文章详情页面

      * 根据URL路径中指定的文章ID号,去获取制定文章的内容

      *

      * @param articleId 指定的文章的ID号

      * @return          获取此文章的数据,并去文章详情页面

      */

     @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

查看更多关于使用@PathVariable注解如何实现动态传值的详细内容...

  阅读:18次