Skip to Content
JavaSpring MVC

Spring MVC

<dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>6.1.0</version> </dependency>

传统XML配置形式

DispatcherServlet替换掉Tomcat自带的Servlet,并为Web程序配置一个Spring上下文环境

<servlet> <servlet-name>mvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:application.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>mvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>

全注解配置方式

Tomcat将会在类路径中查找实现ServletContainerInitializer接口的类,若发现则用来配置ServletSpring提供了这个接口的实现类SpringServletContainerInitializer

SpringServletContainerInitializer将会反过来查找实现WebApplicationInitializer的类,在SpringAbstractAnnotationConfigDispatcherServletInitializer实现了这个接口,使用注解配置时直接继承既可

public class MainInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { return new Class[]{WebConfiguration.class}; } @Override protected Class<?>[] getServletConfigClasses() { return new Class[0]; } @Override protected String[] getServletMappings() { return new String[]{"/"}; } }

其中WebConfigurationSpring的配置类

@Configuration @EnableWebMvc // 快速配置SpringMVC @ComponentScan("com.controller") public class WebConfiguration { }
Last updated on