srping mvc RequestMapping實現

來源:互聯網
上載者:User

標籤: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)
{
}
}

主要使用到的知識還是反射的內容,所以說沒有反射就沒有大部分的架構!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.