?
?1.前言
前面幾篇介紹了SpringMVC中的控制器以及視圖之間的映射方式,這篇來解說一下SpringMVC中的注解,通過注解能夠非常方便的訪問到控制器中的某個方法.
?2.配置文件配置
2.1 注解驅動,配置掃描器
首先須要在SpringMVC中的核心文件里指定注解驅動,詳細例如以下:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"xmlns:context="http://www.springframework.org/schema/context"xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd "><!-- SpringMVC注解驅動 --><mvc:annotation-driven/><!-- SpringMVC的掃描器,假設配置了此掃描器,那么注解驅動就不用再配置了 --><context:component-scan base-package="com.url.controller"/><!-- 配置文件形式要配置的組建:Controller,handlermapping(有默認規則),viewResolver,interceptor --><!-- 視圖解析器 --><beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver"><!-- 配置從項目根文件夾到一端路徑 --><property name="prefix" value="/WEB-INF/jsp/" /><!-- 文件后綴名稱 --><property name="suffix" value=".jsp" /></bean> </beans>
2.2 詳細類定義
package com.url.controller;import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping;/*控制器的標識,當掃描器掃描的時候,會掃描到這是個控制器*/ @Controller public class TestController {/*前臺訪問此方法的路徑*/@RequestMapping("/hello")public String hello(){return "index";}/*也能夠為此方法加入參數,用來收集前臺傳過來的參數*/@RequestMapping("/hello")public String hello(String name,String id){return "index";} }
@Controller:標識當前類是控制器層的一個詳細的實現@requestMapping:放在方法上用來指定某個方法的路徑,當放在類上的時候,相當于命名空間須要組合方法上的requestmapping來訪問
在方法中也能夠任意定義方法的參數,怎樣方法參數的名稱與傳入參數的name匹配的話,就會自己主動的接收.而且轉換為我們須要的類型.
?3.小結
本篇博客簡單的介紹了SpringMVC中控制器中經常使用的注解,通過注解能夠實現高速的訪問控制器信息,方便了開發.