Spring MVC Tutorial – 春天MVC教程

最后修改: 2018年 1月 22日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

This is a simple Spring MVC tutorial showing how to set up a Spring MVC project, both with a Java-based configuration as well as with XML configuration.

这是一个简单的Spring MVC教程,展示了如何设置Spring MVC项目,包括基于Java的配置和XML的配置。

The Maven dependencies for a Spring MVC project are described in detail in the Spring MVC dependencies article.

Spring MVC项目的Maven依赖项在Spring MVC依赖项文章中有详细描述。

2. What Is Spring MVC?

2.什么是Spring MVC??

As the name suggests, it’s a module of the Spring framework dealing with the Model-View-Controller or MVC pattern. It combines all the advantages of the MVC pattern with the convenience of Spring.

顾名思义,它是Spring框架的一个模块,处理模型-视图-控制器或MVC模式。它结合了MVC模式的所有优点和Spring的便利。

Spring implements MVC with the front controller pattern using its DispatcherServlet.

Spring用前台控制器模式实现了MVC,使用其DispatcherServlet

In a nutshell, the DispatcherServlet acts as the main controller to route requests to their intended destination. Model is nothing but the data of our application, and the view is represented by any of the various template engines.

简而言之,DispatcherServlet充当主控制器,将请求路由到预定目的地。模型只不过是我们应用程序的数据,而视图则由各种模板引擎中的任何一个表示。

We’ll look at JSPs in our example in a bit.

我们稍后将在我们的例子中看一下JSP。

3. Spring MVC Using Java Configuration

3.使用Java配置的Spring MVC

To enable Spring MVC support through a Java configuration class, we just add the @EnableWebMvc annotation:

为了通过Java配置类启用Spring MVC支持,我们只需添加@EnableWebMvc注释

@EnableWebMvc
@Configuration
public class WebConfig {

    /// ...
}

This will set up the basic support we need for an MVC project, such as registering controllers and mappings, type converters, validation support, message converters and exception handling.

这将设置我们对MVC项目所需的基本支持,如注册控制器和映射、类型转换器、验证支持、消息转换器和异常处理。

If we want to customize this configuration, we need to implement the WebMvcConfigurer interface:

如果我们想定制这个配置,我们需要实现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;
   }
}

In this example, we’ve registered a ViewResolver bean that will return .jsp views from the /WEB-INF/view directory.

在这个例子中,我们注册了一个ViewResolver bean,它将从/WEB-INF/view目录中返回.jsp视图。

Very important here is that we can register view controllers that create a direct mapping between the URL and the view name using the ViewControllerRegistry. This way, there’s no need for any Controller between the two.

这里非常重要的是,我们可以使用ViewControllerRegistry注册视图控制器,在URL和视图名称之间创建一个直接的映射。这样一来,两者之间就不需要任何控制器了。

If we want to also define and scan controller classes, we can add the @ComponentScan annotation with the package that contains the controllers:

如果我们想同时定义和扫描控制器类,我们可以在包含控制器的包中添加@ComponentScan注解。

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

To bootstrap an application that loads this configuration, we also need an initializer class:

为了启动一个加载该配置的应用程序,我们还需要一个初始化类。

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("/");
    }
}

Note that for versions earlier than Spring 5, we have to use the WebMvcConfigurerAdapter class instead of the interface.

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

4. Spring MVC Using XML Configuration

4.Spring MVC使用XML配置

Instead of the Java configuration above, we can also use a purely XML config:

取代上面的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>

If we want to use a purely XML configuration, we’ll also need to add a web.xml file to bootstrap the application. For more detail on this approach, check out our previous article.

如果我们想使用纯粹的 XML 配置,我们还需要添加一个 web.xml 文件来引导应用程序。有关这种方法的更多细节,请查看我们之前的文章

5. Controller and Views

5.控制器和视图

Let’s have a look at an example of a basic controller:

让我们来看看一个基本控制器的例子。

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

}

And the corresponding JSP resource is the sample.jsp file:

而相应的JSP资源是sample.jsp文件。

<html>
   <head></head>

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

The JSP-based view files are located under the /WEB-INF folder of the project, so they’re only accessible to the Spring infrastructure and not by direct URL access.

基于JSP的视图文件位于项目的/WEB-INF文件夹下,所以它们只能被Spring基础设施访问,而不能被直接的URL访问。

6. Spring MVC With Boot

6.使用Boot的Spring MVC

Spring Boot is an addition to the Spring platform that makes it very easy to get started and create stand-alone, production-grade applications. Boot is not intended to replace Spring but to make working with it faster and easier.

Spring Boot是对Spring平台的补充,它使人们可以非常容易地开始并创建独立的、生产级的应用程序。Boot不是为了取代Spring,而是为了使其工作更快、更容易。

6.1. Spring Boot Starters

6.1.Spring Boot启动器</strong

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

新框架提供了方便的启动器依赖,即依赖描述符,可以为某一功能带来所有必要的技术。

These have the advantage that we no longer need to specify a version for each dependency but instead allow the starter to manage dependencies for us.

这些优点是我们不再需要为每个依赖关系指定一个版本,而是让启动器为我们管理依赖关系。

The quickest way to get started is by adding the spring-boot-starter-parent pom.xml:

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

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

This will take care of dependency management.

这将照顾到依赖性管理。

6.2. Spring Boot Entry Point

6.2.Spring Boot入口点

Each application built using Spring Boot needs merely to define the main entry point.

使用Spring Boot构建的每个应用程序只需要定义主入口点。

This is usually a Java class with the main method, annotated with @SpringBootApplication:

这通常是一个带有main方法的Java类,用@SpringBootApplication注释。

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

This annotation adds the following other annotations:

该注释增加了以下其他注释。

  • @Configuration marks the class as a source of bean definitions.
  • @EnableAutoConfiguration tells the framework to add beans based on the dependencies on the classpath automatically.
  • @ComponentScan scans for other configurations and beans in the same package as the Application class or below.

With Spring Boot, we can set up front end using Thymeleaf or JSP’s without using ViewResolver as defined in Section 3. By adding spring-boot-starter-thymeleaf dependency to our pom.xml, Thymeleaf gets enabled, and no extra configuration is necessary.

有了Spring Boot,我们可以使用Thymeleaf或JSP来设置前端,而无需使用第3节中定义的ViewResolver。通过在pom.xml中添加spring-boot-starter-thymeleaf依赖项,Thymeleaf就会被启用,而且不需要额外的配置。

The source code for the Boot app is, as always, available over on GitHub.

Boot应用程序的源代码一如既往地在GitHub上提供超过

Finally, if you’re looking to get started with Spring Boot, have a look at our reference intro here.

最后,如果您想开始使用Spring Boot,请看看我们的参考介绍

7. Conclusion

7.结论

In this article, we configured a simple and functional Spring MVC project, using Java configuration.

在这篇文章中,我们使用Java配置了一个简单而实用的Spring MVC项目。

The implementation of this Spring MVC tutorial can be found in the GitHub project.

这个Spring MVC教程的实现可以在 GitHub项目中找到。

When the project runs locally, the sample.jsp can be accessed at http://localhost:8080/spring-mvc-basics/sample.

当项目在本地运行时,sample.jsp可以在http://localhost:8080/spring-mvc-basics/sample访问。