基于注解的控制器及其简单应用

Spring 2.5版本后开始新增了可基于注解的控制器,也就是说控制器不用实现Controller接口,通过注释类型来描述。

和上文的基于Controller接口的控制器基本类似,以下部分需要修改

1.Controller类的实现

HelloController类不需要实现Controller接口,改为使用注解类型来描述,用来处理/hello请求。

package org.fkit.controller;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;


/**
 *  HelloController是一个基于注解的控制器
 *  可以同时处理多个请求动作,并且无需实现任何接口
 *  org.springframework.stereotype.Controller注解用于指示该类是一个控制器
 */
@Controller
public class HelloController{

     private static final Log logger = LogFactory
                .getLog(HelloController.class);
     
     /**
      * org.springframework.web.bind.annotation.RequestMapping注解
      * 用来映射请求的URL和请求的方法等。本例用来映射"/hello"
      * hello只是一个普通方法
      * 该方法返回一个包含视图名或视图名和模型的ModelAndView对象
      * */
     @RequestMapping(value="/hello")
     public ModelAndView hello(){
         logger.info("hello方法被调用");
         // 创建准备返回的ModelAndView对象,该对象通常包含了返回视图名,模型的名称以及模型对象
         ModelAndView mv = new ModelAndView();
         // 添加模型数据,可以是任意的POJO对象
         mv.addObject("message", "Hello World!");  
         // 设计逻辑视图名,视图解析器会根据该名称解析到具体的视图页面
         mv.setViewName("/WEB-INF/content/welcome.jsp"); 
        // 返回ModelAndView对象
        return mv;
     }

}

2.修改Spring MVC的配置文件

<?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"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd     
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.2.xsd">
        
    <!-- spring可以自动去扫描base-pack下面的包或者子包下面的java文件,
        如果扫描到有Spring的相关注解的类,则把这些类注册为Spring的bean -->
    <context:component-scan base-package="org.fkit.controller"/>
    
    <!-- 配置处理映射器 -->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
     
     <!-- 配置处理器适配器-->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>

    <!-- 视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"/>
    
</beans>

此处还配置了一个annotion类型的处理映射器RequestMappingHandlerMapping,它根据请求查找映射;同时配置了annotation类型的处理器适配器RequestMappingHandlerAdapter,来完成对HelloController类的@RequestMapping标注方法的调用;最后配置了视图解析器InternalResourceViewResovler来解析视图。
3.测试

http://localhost:8080/AnnotationTest/hello

 

posted @ 2018-01-31 15:39  ZZUGPY  阅读(163)  评论(0编辑  收藏  举报