Spring MVC----@EnableWebMvc原理(一)

本文详细介绍了如何在Spring框架中配置MVC,包括使用@EnableWebMvc注解进行Java配置和通过XML使用mvc:annotation-driven元素进行配置的方法。同时,探讨了HandlerMapping和HandlerAdapter的自动注册过程。

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

1 启用MVC配置

1.1 @EnableWebMvc配置

1、启用MVC Java config 或 MVC XML namespace

想要启用MVC Java config,只需要将@EnableWebMvc添加到你的一个@Configuration class即可。

@Configuration
@EnableWebMvc
public class WebConfig {

}

1.2 XML配置

2 在XML中,需要在你的DispatcherServlet context (或你的root context – 如果没有定义DispatcherServlet context的话)内使用 mvc:annotation-driven 元素:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    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">

    <mvc:annotation-driven/>

</beans>

2 @EnableWebMvc

本文主要以@EnableWebMvc java配置为主,一下为相关类图和代码:
在这里插入图片描述
在这里插入图片描述

想要以Java形式定制默认的配置,你可以简单的实现WebMvcConfigurer接口,或者继承WebMvcConfigurerAdapter并重写需要的方法:

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

    // Override configuration methods...

}

2.1 HandlerMapping

@EnableWebMvc 会自动向Spring容器注入HanleMapping子类
在这里插入图片描述
在这里插入图片描述

HandlerMapping类图,如下图所示:
在这里插入图片描述

2.2 HandlerAdapter

@EnableWebMvc 会自动向Spring容器注入HandlerAdapter子类
在这里插入图片描述

HandlerAdapter类图,如下图所示:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值