Springmvc @PathVariable解析过程

问题描述:

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

见以上代码,url中的uuid如何解析成为参数传递进来。

解析过程:(接收请求:如/auth1/xxxx-xxx-xxx/xxx)
1. 将/auth1/{uuid}/xxx根据/拆成 auth1、{uuid}、xxx
2. 将{uuid}替换成(.*),并纪录key为uuid
3. 同样将/auth1/xxxx-xxx-xxx/xxx拆成auth1、xxxx-xxx-xxx、xxx
4. 进行正则匹配,并根据group得到uuid=xxxx-xxx-xxx.
5. 将uuid=xxxx-xxx-xxx放入request的一个attribute中。
6. 根据反射和标注得到pathvariable名为uuid
7. 去request得到这个uuid,然后进行方法调用。

下面是测试springmvc的解析代码。

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

当上述问题写成:

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

时,以下代码模拟测试了反射获取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);
                }

            }

        }
    }

你可能感兴趣的:(Spring)