SpringMvc组件与注解配置

本文详细介绍了SpringMVC框架的核心组件,包括DispatchServlet、HandlerMapping、HandlerAdapter和ViewResolver的功能与作用。同时,深入探讨了SpringMVC与Spring容器的关系,并提供了web.xml和springMvc.xml的配置示例。此外,还展示了如何使用注解创建控制器类。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、 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";
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值