使用Spring MVC提供Web内容

使用Spring MVC提供Web内容

使用Spring MVC提供Web内容

Serving Web Content with Spring MVC

你将通过此教程使用Spring创建一个”hello world”网站。

This guide walks you through the process of creating a “hello world” web site with Spring.


What you’ll build

你将构建一个拥有静态主页的应用,并且接收如下HTTP GET请求:

You’ll build an application that has a static home page, and also will accept HTTP GET requests at:



and respond with a web page displaying HTML. The body of the HTML contains a greeting:

"Hello, World!"


You can customize the greeting with an optional name parameter in the query string:



The name parameter value overrides the default value of “World” and is reflected in the response:

"Hello, User!"


What you’ll need


How to complete this guide


Like most Spring Getting Started guides, you can start from scratch and complete each step, or you can bypass basic setup steps that are already familiar to you. Either way, you end up with working code.


To start from scratch, move on to Build with Gradle.


To skip the basics, do the following:

  • 下载并解压此教程的源码仓库,或者使用Git进行clone:git clone https://github.com/spring-guides/gs-serving-web-content.git
  • 进入gs-serving-web-content/initial目录
  • 跳至创建一个web控制器.
  • Download and unzip the source repository for this guide, or clone it using Git: git clone https://github.com/spring-guides/gs-serving-web-content.git
  • cd into gs-serving-web-content/initial
  • Jump ahead to Create a web controller.


When you’re finished, you can check your results against the code in gs-serving-web-content/complete.


Create a web controller


In Spring’s approach to building web sites, HTTP requests are handled by a controller. You can easily identify these requests by the @Controller annotation. In the following example, the GreetingController handles GET requests for /greeting by returning the name of a View, in this case, “greeting”. A View is responsible for rendering the HTML content:


package hello;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

public class GreetingController {

    public String greeting(@RequestParam(name="name", required=false, defaultValue="World") String name, Model model) {
        model.addAttribute("name", name);
        return "greeting";



This controller is concise and simple, but there’s plenty going on. Let’s break it down step by step.

@GetMapping注解确保/greeting的HTTP GET请求映射到greeting()方法上。

The @GetMapping annotation ensures that HTTP GET requests to /greeting are mapped to the greeting() method.


@RequestParam binds the value of the query String parameter name into the name parameter of the greeting() method. This query String parameter is not required; if it is absent in the request, the defaultValue of “World” is used. The value of the name parameter is added to a Model object, ultimately making it accessible to the view template.


The implementation of the method body relies on a view technology, in this case Thymeleaf, to perform server-side rendering of the HTML. Thymeleaf parses the greeting.html template below and evaluates the th:text expression to render the value of the ${name} parameter that was set in the controller.


<html xmlns:th="http://www.thymeleaf.org">
    <title>Getting Started: Serving Web Content</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <p th:text="'Hello, ' + ${name} + '!'" />


Developing web apps

开发网页应用的一个常见场景是,编码实现,重启应用,刷新浏览器查看变化。整个过程消耗了大量时间。为了加速这种场景,Spring Boot中带了一个开箱即用的模块spring-boot-devtools

A common feature of developing web apps is coding a change, restarting your app, and refreshing the browser to view the change. This entire process can eat up a lot of time. To speed up the cycle of things, Spring Boot comes with a handy module known as spring-boot-devtools.

  • 启用热部署
  • 是模板引擎关闭缓存
  • 启用LiveReload自动刷新浏览器
  • 其他基于开发替换生产的默认功能
  • Enable hot swapping
  • Switches template engines to disable caching
  • Enables LiveReload to refresh browser automatically
  • Other reasonable defaults based on development instead of production


Make the application executable

虽然可以将服务打包作为传统的WAR包,并部署在一个外部应用服务上,但下面展示的更简单的方法是创建一个独立的应用。你可以将所有东西打包为一个独立的可执行的JAR包,由Java main()方法驱动。这样一来,就代替了使用外部实例进行部署,转而使用Spring支持的内嵌Tomcat servlet容器作为HTTP运行时。

Although it is possible to package this service as a traditional WAR file for deployment to an external application server, the simpler approach demonstrated below creates a standalone application. You package everything in a single, executable JAR file, driven by a good old Java main() method. Along the way, you use Spring’s support for embedding the Tomcat servlet container as the HTTP runtime, instead of deploying to an external instance.


package hello;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

public class Application {

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



@SpringBootApplication is a convenience annotation that adds all of the following:

  • @Configuration标记此类作为应用上下文的bean定义来源。
  • @EnableAutoConfiguration告诉Spring Boot基于classpath设置、其他bean或者各种属性设置来开始添加bean。
  • 通常你会在Spring MVC应用中添加@EnableWebMvc,如果在classpath中发现spring-webmvc,则Spring Boot会自动添加。此注解会标记应用为web应用,并激活一些关键行为例如设置一个DispatcherServlet
  • @ComponentScan告诉Spring在hello包中寻找其他组件、配置、服务等,也允许找到controllers。
  • @Configuration tags the class as a source of bean definitions for the application context.
  • @EnableAutoConfiguration tells Spring Boot to start adding beans based on classpath settings, other beans, and various property settings.
  • Normally you would add @EnableWebMvc for a Spring MVC app, but Spring Boot adds it automatically when it sees spring-webmvc on the classpath. This flags the application as a web application and activates key behaviors such as setting up a DispatcherServlet.
  • @ComponentScan tells Spring to look for other components, configurations, and services in the hello package, allowing it to find the controllers.

main()方法中使用了Spring Boot的SpringApplication.run()方法来加载一个应用。你注意到了没有任何XML吗?同样也没有web.xml文件。此web应用是100%纯Java并且你不要处理任何基础架构方面的配置。

The main() method uses Spring Boot’s SpringApplication.run() method to launch an application. Did you notice that there wasn’t a single line of XML? No web.xml file either. This web application is 100% pure Java and you didn’t have to deal with configuring any plumbing or infrastructure.


Build an executable JAR


You can run the application from the command line with Gradle or Maven. Or you can build a single executable JAR file that contains all the necessary dependencies, classes, and resources, and run that. This makes it easy to ship, version, and deploy the service as an application throughout the development lifecycle, across different environments, and so forth.

如果使用Gradle,可以使用./gradlew bootRun来运行应用。或者可以使用./gradlew build构建JAR文件。然后可以运行此JAR文件:

If you are using Gradle, you can run the application using ./gradlew bootRun. Or you can build the JAR file using ./gradlew build. Then you can run the JAR file:

java -jar build/libs/gs-serving-web-content-0.1.0.jar

如果使用Maven,可以使用./mvnw spring-boot:run来运行应用。或者可以使用./mvnw clean package构建JAR文件。然后可以运行此JAR文件:

If you are using Maven, you can run the application using ./mvnw spring-boot:run. Or you can build the JAR file with ./mvnw clean package. Then you can run the JAR file:

java -jar target/gs-serving-web-content-0.1.0.jar


The procedure above will create a runnable JAR. You can also opt to build a classic WAR file instead.


Logging output is displayed. The service should be up and running within a few seconds.


Test the App


Now that the web site is up, visit http://localhost:8080/greeting, where you see:

"Hello, World!"

在请求字符串参数中提供一个name,如http://localhost:8080/greeting?name=User。注意消息由”Hello, World!”变为了”Hello User!”:

Provide a name query string parameter with http://localhost:8080/greeting?name=User. Notice how the message changes from “Hello, World!” to “Hello User!”:

"Hello, User!"


This change demonstrates that the @RequestParam arrangement in GreetingController is working as expected. The name parameter has been given a default value of “World”, but can always be explicitly overridden through the query string.


Add a Home Page

例如HTML或JavaScript或CSS等静态资源,可以直接放入源码的合适位置,就可以在Spring Boot应用中起效。默认Spring Boot在classpath的”/static” (或者”/public”)目录放置静态资源。index.html比较特殊,因为如果有这个文件的话,是被当作“欢迎页”,意味着是作为根资源,例如,在本例中的http://localhost:8080/,所以先创建此文件:

Static resources, like HTML or JavaScript or CSS, can easily be served from your Spring Boot application just be dropping them into the right place in the source code. By default Spring Boot serves static content from resources in the classpath at “/static” (or “/public”). The index.html resource is special because it is used as a “welcome page” if it exists, which means it will be served up as the root resource, i.e. at http://localhost:8080/ in our example. So create this file:


    <title>Getting Started: Serving Web Content</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <p>Get your greeting <a href="/greeting">here</a></p>


and when you restart the app you will see the HTML at http://localhost:8080/.




Congratulations! You have just developed a web page using Spring.