您的位置:首页 > 移动开发

srping mvc RequestMapping实现

2014-05-10 23:11 141 查看
spring mvc中定义请求的url只需要在方法上添加注解: @RequestMapping("aa.mvc")即可定义访问的url地址,但是你是否有考虑过为什么添加这个注解就可以实现url访问地址的定义了呢?下面解析下他的实现原理!

首先定义注解RequestMapping

@Retention(RetentionPolicy.RUNTIME)

@Target(value = { ElementType.METHOD, ElementType.TYPE })

public @interface RequestMapping

{
public String value();

}

mvc中常需要对输入值进行合法性校验,所以也定义了校验的注解MyValid

@Retention(RetentionPolicy.RUNTIME)

@Target(ElementType.PARAMETER)//在参数中使用

public @interface MyValid

{
public String value();

}

在测试类中:

package com.cml.mvc;

import java.lang.annotation.Annotation;

import java.lang.reflect.Method;

import java.lang.reflect.Type;

public class Parameters

{
public static void main(String[] args) throws Exception
{
Class clz = Parameters.class;
Method[] methods = clz.getDeclaredMethods();

for (Method method : methods)
{
// 是方法上是否有注解@RequestMapping
if (method.isAnnotationPresent(RequestMapping.class))
{
RequestMapping re = method.getAnnotation(RequestMapping.class);
System.out.println("请求的url:" + re.value());
// 获取方法上的所有注解
Annotation[][] annotations = method.getParameterAnnotations();

for (Annotation[] parameters : annotations)
{
for (Annotation an : parameters)
{
if (an.annotationType() == MyValid.class)
{
System.out.println("进入自定义校验!");
}
}
}
}
}
}

@RequestMapping("aa.mvc")
public void test(@MyValid("test") String name, int type)
{
}

}

主要使用到的知识还是反射的内容,所以说没有反射就没有大部分的框架!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: