码迷,mamicode.com
首页 > 编程语言 > 详细

SpringMVC实战(注解)

时间:2015-07-14 18:21:40      阅读:108      评论:0      收藏:0      [点我收藏+]

标签:

 

 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 -->
	<!-- 视图解析器 -->
	<bean
		class="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中控制器中常用的注解,通过注解可以实现快速的访问控制器信息,方便了开发.


版权声明:本文为博主原创文章,未经博主允许不得转载。

SpringMVC实战(注解)

标签:

原文地址:http://blog.csdn.net/luckyzhoustar/article/details/46878099

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!