SpringMvc組件與註解配置

一、 SpringMvc的三大組件:

1、 DispatchServlet(攔截請求)

2、HandlerMapping (映射器控制器)

3、HandlerAdapter(適配器,執行方法)

4、ViewResolver(視圖解析器)用於解析視圖

二、SpringMvc的容器與Spring的容器

       SpringMvc的容器是Spring容器的子容器,因此可以在SpringMvc容器中調用Spring容器。Spring的容器與SpringMvc容器的關係:

Spring容器與SpringMvc容器的關係

三、web.xml文件的配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <servlet>
  <!-- 將springMvc定義的servlet配置出來 -->
  	<servlet-name>springmvc</servlet-name>
  	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  	<!-- 修改配置文件路徑和名稱 -->
  	<init-param>
  		<param-name>contextConfigLocation</param-name>
  		<param-value>classpath:springmvc.xml</param-value>
  	</init-param>
  	<load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
  	<servlet-name>springmvc</servlet-name>
  	<url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

四、配置springMvc.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.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
         http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">
      <!--   掃描註解 -->
        <context:component-scan base-package="com.test.controller"></context:component-scan>
        <!-- 註解驅動 -->
        <mvc:annotation-driven></mvc:annotation-driven>
       <!-- 由於/可以攔截靜態資源 因此需要配置釋放靜態資源 css   jsp   image 
			location爲資源所在的文件夾,與對應的mapping對應的地址相對應   -->
        <mvc:resources location="/WEB-INF/image/" mapping="/image/**"></mvc:resources>
</beans>

五、編寫控制器類

package com.test.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 用註解的形式配置mvc環境
 * @author QuLei
 *
 */
@Controller
public class DemoController {
	@RequestMapping("/demo")
	public String demo() {
		System.out.println("執行控制器的demo!!!");
		return "main.jsp";
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章