Serving Web Content with Spring MVC

Serving Web Content with Spring MVC

This guide walks you through the process of creating a "Hello, World" web site with Spring.

What You Will Build

You will build an application that has a static home page and that will also accept HTTP GET requests at: http://localhost:8080/greeting.

It will respond with a web page that displays HTML. The body of the HTML will contain a greeting: "Hello, World"

You can customize the greeting with an optional name parameter in the query string. The URL might then be http://localhost:8080/greeting?name=User.

The name parameter value overrides the default value of Wordl and is reflected in the response by the content changing to "Hello, User".

How to complete this guide

List 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 Starting with Spring Initializer.

To skip the basic, do the following:

  • 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 finish, you can check your results against the code in gs-serving-web-content/complete

Starting with Spring Initializer

You can use this pre-initialized project and click Generate to download a ZIP file. This project is configured to fit the examples in this tutorial.

To manually initialize the project:

  1. Navigate to https://start.spring.io. This service pulls in all the dependencies you need for an application and does most of the setup for you.

  2. Choose either Gradle or Maven and the languate you want to use. This guide assumes that you chose Java.

  3. Click Dependencies and select Spring Web, Thymeleaf, and Spring Boot DevTools.

  4. Click Generate.

  5. Download the resulting ZIP file, which is an archive of a web application that is configured with your choices.

If your IDE has the Spring Initializer integration, you can complete this process from your IDE.
You can also fork the project from Github and open it in your IDE or other editor.

Create a Web Controller

In Spring's approach to building web sites, HTTP requests are handled by a controller. You can easily identify the controller by the @Controller annotation. In the following example, 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. The following listing shows the controller:

package com.example.servingwebcontent;
​
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
​
@Controller
public class GreetingController {
​
    @GetMapping("/greeting")
    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 is plenty going on. We break it down step by step.

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 and evaluates the th:text expression to render the value of the ${name} parameter that was set in the controller. The following listing shows the greeting.html template:

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head> 
    <title>Getting Started: Serving Web Content</title> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
    <p th:text="'Hello, ' + ${name} + '!'" />
</body>
</html>
Make sure you have Thymeleaf on your classpath (artifact co-ordinates: `org.springframework.boot:spring-boot-starter-thymeleaf`). It is already there is the "initial" and "complete" samples in Github

Spring Boot Devtools

A common feature of developing web applications is coding a change, restarting your application, and refreshing the browser to view the change.This entire process can eat up a lot of time. To speed up this refresh cycle, Spring Boot offers with a handy module known as spring-boot-devtools. Spring Boot Devtools:

  • Enables hot swapping

  • Switches template engines to disable caching.

  • Enables LiveReload to automatically refresh the browser.

  • Other reasonable defaults based on development instead of production.

Run the Application

The Spring Initializer creates an application class for you. In this case, you need not further modify the class provided by the Spring Initializer. The following listing shows the application class:

package com.example.servingwebcontent;
​
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
​
@SpringBootApplication
public class ServingWebContentApplication {
​
    public static void main(String[] args) {
        SpringApplication.run(ServingWebContentApplication.class, args);
    }
​
}

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

  • @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. For example, if spring-webmvc is on the classpath, this annotation flags the application as a web application and activates key behaviors, such as setting up a DispatcherServlet.

  • @ComponnetScan: Tells Spring to look for other components, configurations, and services in the com/example package, letting it find the controllers.

The main() method uses Spring Boot's SpringApplication.run() method to launch an application. Did you notice that there was not a single linux of XML? There is no web.xml file, either. This web application is 100% pure Java and you did not 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. You can also build a single executable JAR file that contains all the necessary dependencies, classes, and resources and run that. Building an executable jar makes it easy to ship, version, and deploy the service as an application throughout the development lifecycle, across different environment, and so forth.

If you use Maven, you can run the application by using ./mvnw spring-boot:run. Alternatively, you can build the JAR file with `./mvnw clean package and then run the JAR file, as follows:

java -jar target/gs-serving-web-content-0.1.0.jar
The steps described here create a runnable JAR. You can also build a classic WAR file.

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

Test the Application

Now that the web site is running, visit http://localhost:8080/greeting, where you should see "Hello, World".

Provide a name query string parameter by visiting http://localhost:8080/greeting?name=User. Notice how the message changes from "Hello, World" to "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 it can be explicitly overridden through the query string.

Add a Home Page

Static resources, including HTML and JavaScript and CSS, can be served from your Spring Boot application by 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, if it exists, it is used as a welcome page.

As a result, you need to create the following file (which you can find intsrc/main/resources/static/index.html):

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

When you restart the application, you will see the HTML at http://localhost:8080/

Summary

Congratullation! You have just developed a web page by using Spring.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 这是一个关于在 Windows 上使用 Waitress 作为 Flask 应用程序服务器的 Stack Overflow 帖子。在此帖子中,用户询问如何在 Windows 上使用 Waitress,以便能够更好地处理并发请求并提高应用程序的性能。 回答中提到了一些步骤,包括安装 Waitress、将应用程序绑定到 Waitress 中,并使用 Waitress 运行应用程序。此外,还提到了一些可能出现的问题以及如何解决它们。 总的来说,这是一个非常有用的帖子,可以帮助 Flask 开发人员在 Windows 上使用 Waitress 以提高应用程序的性能和可靠性。 ### 回答2: 问题链接中是一个有关使用Flask和Waitress在Windows上提供Flask应用的问题。Flask是一个Python的微型web框架,用于快速实现web应用,而Waitress是一个纯Python的WSGI服务器,用于提供Python web应用。 在Windows上使用Waitress提供Flask应用的步骤如下: 首先,确保已经安装了Python并设置了环境变量。 然后,可以使用以下命令来安装Flask和Waitress依赖: ``` pip install flask waitress ``` 在Flask应用程序中,通过导入Flask类并创建一个应用程序实例来设置Flask应用,然后编写一个处理请求的路由函数。 最后,在应用程序的最后部分,添加以下代码来使用Waitress服务器提供应用: ``` from waitress import serve if __name__ == '__main__': # 这里的app是之前创建的Flask应用程序实例 serve(app, host='0.0.0.0', port=5000) ``` 这里的`host`参数设置为`'0.0.0.0'`表示可以通过任意IP地址访问应用,`port`参数设置为`5000`表示使用5000端口提供应用。 然后,只需在命令行中运行Python脚本即可开始提供Flask应用。访问`http://localhost:5000`即可查看应用。 总结起来,使用Waitress在Windows上提供Flask应用只需要安装依赖,设置Flask应用和添加使用Waitress的代码即可。希望对你有帮助! ### 回答3: 感谢你的问题。这个问题问的是如何在Windows上使用Waitress来提供Flask应用。 首先,确保已经在Windows系统上安装了Python。然后,通过运行以下命令安装Waitress: ``` pip install waitress ``` 接下来,创建一个简单的Flask应用程序,比如以下示例: ```python from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello, World!' if __name__ == '__main__': app.run() ``` 以上代码创建了一个名为app的Flask应用,其中包含一个指向根URL的路由。当运行该应用时,它将在本地主机的默认端口5000上运行。 接下来,使用以下代码将Flask应用与Waitress集成: ```python from waitress import serve from your_flask_app import app serve(app, host='0.0.0.0', port=8080) ``` 以上代码导入了serve函数和我们之前创建的Flask应用。将serve函数与app对象一起调用,可以在本地主机的8080端口上提供Flask应用。 最后,保存以上代码为一个Python脚本(例如`server.py`),在命令提示符中运行以下命令来启动Waitress服务器: ``` python server.py ``` 现在,你的Flask应用将使用Waitress在本地主机的8080端口上运行。你可以通过访问`http://localhost:8080/`来查看你的应用。 希望这个回答对你有帮助。如果你还有其他问题,请随时提问!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值