好得很程序员自学网

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

使用AOP拦截Controller获取@PathVariable注解传入的参数

AOP拦截Controller获取@PathVariable注解传入参数

前言:

最近项目中需要对controller传入的应用标识(appMarkId)进行校验,appMarkId@PathVariable传入到url模版中的,这里用到了aop统一拦截处理,但是在拦截的过程中发现request获取不到该参数,随后进行了研究。

示例代码:

处理:

?

1

Map map = (Map) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);

可以用这个方法获取到所有uri模版中传入的参数。

扩展: aop中获取request和response

?

1

2

3

ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();

HttpServletRequest request = servletRequestAttributes.getRequest();

HttpServletResponse response = servletRequestAttributes.getResponse();

动态参数使用@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/IM507/article/details/99823318

查看更多关于使用AOP拦截Controller获取@PathVariable注解传入的参数的详细内容...

  阅读:24次