1. 概述

这是一个简单的 Spring MVC 教程 ,演示了如何使用 Java 和 XML 两种配置方式搭建一个 Spring MVC 项目。

有关Spring MVC 项目的Maven依赖详细描述,可以查看 Spring MVC依赖 这篇文章。

2. 什么是Spring MVC?

顾名思义,它是Spring框架中用于处理MVC模式(Model-View-Controller)的一个模块。 它结合了MVC模式的所有优点和Spring的便利性。

Spring使用DispatcherServlet通过前端控制器模式实现MVC。

简而言之, DispatcherServlet 充当主Controller,负责将请求路由到目标Controller。 Model即数据, view(视图)由 各种模板引擎表示。稍后我们将在示例中研究JSP。

3. Spring MVC 使用Java配置

通过Java配置类方式启用Spring MVC,我们只需添加@EnableWebMvc注解即可

@EnableWebMvc
@Configuration
public class WebConfig {

    /// ...
}

这将为我们MVC项目配置一些基础支持,例如注册Controller和路由映射、类型转换器、验证支持、消息转换器和异常处理。

如果要自定义此配置,则需要实现WebMvcConfigurer接口

@EnableWebMvc
@Configuration
public class WebConfig implements WebMvcConfigurer {

   @Override
   public void addViewControllers(ViewControllerRegistry registry) {
      registry.addViewController("/").setViewName("index");
   }

   @Bean
   public ViewResolver viewResolver() {
      InternalResourceViewResolver bean = new InternalResourceViewResolver();

      bean.setViewClass(JstlView.class);
      bean.setPrefix("/WEB-INF/view/");
      bean.setSuffix(".jsp");

      return bean;
   }
}

本例中,我们注册了一个ViewResolver bean,它会从/WEB-INF/view目录中查找后缀名为.jsp的视图。

上面有点比较重要,在addViewControllers()方法中,我们使用ViewControllerRegistry在URL和视图名称之间创建直接映射关系。这样我就可以不用再实现一个Controller类了

我们还可以添加@ComponentScan扫描某个包下的Controller

@EnableWebMvc
@Configuration
@ComponentScan(basePackages = { "com.baeldung.web.controller" })
public class WebConfig implements WebMvcConfigurer {
    // ...
}

为了加载我们的配置文件,我们还需要一个initializer类:

public class MainWebAppInitializer implements WebApplicationInitializer {
    @Override
    public void onStartup(final ServletContext sc) throws ServletException {

        AnnotationConfigWebApplicationContext root = 
          new AnnotationConfigWebApplicationContext();
        
        root.scan("com.baeldung");
        sc.addListener(new ContextLoaderListener(root));

        ServletRegistration.Dynamic appServlet = 
          sc.addServlet("mvc", new DispatcherServlet(new GenericWebApplicationContext()));
        appServlet.setLoadOnStartup(1);
        appServlet.addMapping("/");
    }
}

请注意,对于早于Spring 5的版本,我们必须使用WebMvcConfigurerAdapter类而不是接口。

4. Spring MVC 使用XML配置

除了上述Java配置之外,我们还可以使用纯XML配置:

<context:component-scan base-package="com.baeldung.web.controller" />
<mvc:annotation-driven />    

<bean id="viewResolver" 
      class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/view/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <mvc:view-controller path="/" view-name="index" />

</beans>

如果要使用纯XML配置,则还需要添加一个web.xml文件。 有关此方法的更多详细信息,请查看我们以前的文章

5. Controller 与 Views

定义一个基本的Controller:

@Controller
public class SampleController {
    @GetMapping("/sample")
    public String showForm() {
        return "sample";
    }

}

以及对应的jps文件,sample.jsp:

<html>
   <head></head>

   <body>
      <h1>This is the body of the sample view</h1>    
   </body>
</html>

基于JSP的视图文件位于项目的/WEB-INF文件夹下,因此它们只能由Spring底层代码访问,而不能通过URL直接访问

6. Spring MVC 与 Spring Boot

Spring Boot作为Spring平台的补充,其设计目的是用来简化新Spring应用的初始搭建以及开发过程,它使入门和创建生产级应用程序变得非常容易。Spring Boot目的并不是要取代Spring,而是使它变得更好用。

6.1. Spring Boot Starters

The new framework provides convenient starter dependencies – which are dependency descriptors that can bring in all the necessary technology for a certain functionality.

优点是我们不再需要为每个依赖项指定版本,而是让starter替我们管理依赖。

最快的开始方法是添加spring-boot-starter-parent pom.xml:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.4.0</version>
</parent>

它会负责管理好依赖。

6.2. Spring Boot 应用入口

每个基于Spring Boot的应用程序仅需要定义一个主入口,这通常是带有main方法的Java类,并带有@SpringBootApplication注释:

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

@SpringBootApplication注解会自动包含下面的注解:

  • @Configuration – 将该类标记为配置类
  • @EnableAutoConfiguration – 告诉Spring根据classpath上的依赖关系自动添加bean
  • @ComponentScan – 告诉Spring扫描该包下面的所有配置类和Bean

使用Spring Boot,我们可以使用Thymeleaf或JSP配置前端,而无需使用第3节中定义的ViewResolver。通过将spring-boot-starter-thymeleaf依赖项添加到我们的pom.xml中,即可启用Thymeleaf,并且不需要任何额外的配置。

Spring Boot的示例代码,可从GitHub上获取。

最后,如果您希望开始学习使用Spring Boot,请参考介绍此教程

7. 总结

在本示例中,我们使用Java配置,配置了一个简单而实用的Spring MVC项目。

本本Spring MVC的示例代码可从GitHub上获取。

项目启动后, 通过http://localhost:8080/spring-mvc-basics/sample 访问sample.jsp