Usage Analysis of Springmvc @ PathVariable

  • 2021-12-04 10:10:41
  • OfStack

The usage of directory @ PathVariable parsing problem description parsing process dynamic parameters using @ PathVariable in Controller layer code is as follows

Usage Analysis of @ PathVariable

Problem description


    @RequestMapping(value = "/auth1/{uuid}/xxx", method = RequestMethod.GET)
    public void imageCode1(@PathVariable (value = "uuid") String uuid) {
        logger.info(uuid);
    }

See the above code, how uuid in url is parsed as a parameter and passed in.

Analytic process

(Request received: eg./auth1/xxxx-xxx-xxx/xxx)

1. Disassemble/auth1/{uuid}/xxx into auth1, {uuid}, xxx according to/

2. Replace {uuid} with (. *) and record key as uuid

3. Split/auth1/xxxx-xxx-xxx/xxx into auth1, xxxx-xxx-xxx and xxx as well

4. Regular matching is performed, and uuid=xxxx-xxx-xxx is obtained according to group.

5. Place uuid=xxxx-xxx-xxx into one attribute of request.

6. According to reflection and labeling, the name of pathvariable is uuid

7. Go to request to get this uuid, and then make a method call.

The following is the parsing code for testing springmvc.


    public static void main(String[] args) {
        AntPathMatcher matcher = new AntPathMatcher();
        System.out.println(matcher.match("{uuid}", "xxxx"));
        Map<String, String> result = matcher.extractUriTemplateVariables("{uuid}", "xxx");
        System.out.println(result);
    }

When the above question is written as:


    @RequestMapping(value = "/auth1/{uuid}/xxx", method = RequestMethod.GET)
    public void imageCode1(@PathVariable String uuid) {
        logger.info(uuid);
    }

The following code simulates the process of testing the reflection to obtain uuid


    public static void main(String[] args) throws Exception {
        BeanInfo beanInfo = Introspector.getBeanInfo(A.class);
        MethodDescriptor[] methodDescriptors = beanInfo.getMethodDescriptors();
        for (MethodDescriptor methodDescriptor : methodDescriptors) {
            System.out.println("method:" + methodDescriptor.getName());
            ParameterDescriptor[] params = methodDescriptor.getParameterDescriptors();
            if (params != null) {
                for (ParameterDescriptor param : params) {
                    System.out.println("param:" + param.getName());
                }
            }
        }
        Method[] methods = A.class.getMethods();
        for (Method method : methods) {
            if (method.getName().equals("hello")) {
                LocalVariableTableParameterNameDiscoverer discoverer =
                        new LocalVariableTableParameterNameDiscoverer();
                String[] methodNames = discoverer.getParameterNames(method);
                for (String methodName : methodNames) {
                    System.out.println(methodName);
                }
            }
        }
    }

Dynamic parameters use @ PathVariable

There is now 1 hyperlink as follows


<a href="<c:url value="/actions/article/readArticle/${article.id}"/> "
                                                 target="_blank">${article.title}</a>

The characteristic of this hyperlink is that the id value parsed from the EL expression is added to the URL path.

Therefore, in the Controller layer of SpringMVC, it needs to be parsed using @ PathVariable ("articleId") Long articleId.

@ PathVariable is designed to resolve dynamic parameters in URL requests.

The code in the Controller layer is as follows


public static final String URL_ARTICLE_READ = "article/readArticle/{articleId}";
    /**
     *  Go to the article details page 
     *  According to URL Article specified in the path ID Number, to get the content of the article 
     *
     * @param articleId  Of the specified article ID No. 
     * @return           Get the data for this article and go to the Article Details page 
     */
    @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);
 ...
    }

Thus, the value of ${article. id} on the page is finally mapped to Long articleId in Java.


Related articles: