Spring MCV基于注解的控制器

一 Controller类的实现

package org.fkit.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

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

二 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.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd     
        http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context.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>

三 测试

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值