1. 程式人生 > >/----------關鍵字:springmvc註解

/----------關鍵字:springmvc註解

.cn 技術 多個 ng- 分享 創建 adapt handler welcome

M1:這篇內容是在上一篇的基礎上進行的修改。具體步驟如下:

M2:新建項目Dynamic Web Project 項目annotation

M3:其它地方不變只需要對springmvc_config,xml 和HelloController進行修改

M4:springmvc_config.xml修改內容 

<?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掃描對應包下面的註解,掃描到註冊為spring的bean --> <context:component-scan base-package="com.mollen.controller"/> <!-- 配置annotation類型的處理映射器 --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
<!-- 配置annotation類型的處理器適配器 --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/> <!-- 視圖解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"/> </beans>

M5:HelloController修改如下

package com.mollen.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;
/**
 * HelloCotroller是一個基於註解的控制器
 * 可以同時處理多個請求,並且不用實現任何接口
 * org.springframework.stereotype.Controller註解用於只是該類是一個控制器
 */
@Controller
public class HelloCotroller {
    private static final Log log = LogFactory.getLog(HelloCotroller.class);
    
    /**
     * org.springframework.web.bind.annotation.RequestMapping註解
     * 用來映射請求的url和請求的方法,本例用來映射"/hello"
     * hello只是一個簡單的方法
     * 該方法返回一個視圖名或視圖名和模型對象
     */
    @RequestMapping(value="/hello")
    public ModelAndView hello(){
        //打印日誌
        log.info("HelloController 被調用");
        //創建視圖模型,該對象包含視圖名,模型名稱,模型對象
        ModelAndView mv = new ModelAndView();
        //添加模型數據,可以是pojo對象
        mv.addObject("message", "hello world.");
        //視圖解析器根據名字將數據解析到指定url頁面
        mv.setViewName("/WEB-INF/view/welcome.jsp");
        return mv;
    }
}

M6:部署並訪問

技術分享

/----------關鍵字:springmvc註解