標籤:spring mvc
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)
{
}
}
主要使用到的知識還是反射的內容,所以說沒有反射就沒有大部分的架構!