1. Overview
1.概述
In this tutorial, we want to have a look at how to return HTML from a Spring MVC controller.
在本教程中,我们要看一下如何从Spring MVC控制器中返回HTML。
Let’s take a look at what needs to be done.
让我们来看看需要做什么。
2. Maven Dependency
2.Maven的依赖性
First, we have to add the spring-boot-starter-web Maven dependency for our MVC controller:
首先,我们必须为我们的MVC控制器添加spring-boot-starter-web Maven依赖项。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<versionId>1.3.7.RELEASE</versionId>
</dependency>
3. Controller
3.控制器
Next, let’s create our controller:
接下来,让我们创建我们的控制器。
@Controller
public class HtmlController {
@GetMapping(value = "/welcome", produces = MediaType.TEXT_HTML_VALUE)
@ResponseBody
public String welcomeAsHTML() {
return "<html>\n" + "<header><title>Welcome</title></header>\n" +
"<body>\n" + "Hello world\n" + "</body>\n" + "</html>";
}
}
We use the @Controller annotation to tell the DispatcherServlet that this class handles HTTP Requests.
我们使用@Controller注解来告诉DispatcherServlet这个类处理HTTP请求。
Next, we configure our @GetMapping annotation to produce MediaType.TEXT_HTML_VALUE output.
接下来,我们配置我们的@GetMapping注解以产生MediaType.TEXT_HTML_VALUE输出。
And finally, the @ResponseBody annotation tells the controller that the object returned should be automatically serialized to the configured media type, that is, TEXT_HTML_VALUE, or text/html.
最后,@ResponseBody注解告诉控制器,返回的对象应该被自动序列化为配置的媒体类型,即TEXT_HTML_VALUE,或text/html。
Without this last annotation, we’d receive a 404 error since a String return value by default refers to a view name.
如果没有这最后一个注解,我们会收到404错误,因为String返回值默认是指一个视图名称。
With that controller in place, we can test it out:
有了这个控制器,我们就可以测试它了。
curl -v localhost:8081/welcome
The output will look similar to:
输出结果将看起来类似于。
> ... request ...
>
< HTTP/1.1 200
< Content-Type: text/html;charset=UTF-8
< ... other response headers ...
<
<html>
<header><title>Welcome</title></header>
<body>
Hello world
</body>
</html>
As expected, we see that the Content-Type of the response is text/html. Furthermore, we see that the response also has the correct HTML content.
正如预期,我们看到响应的Content-Type是text/html。此外,我们还看到,响应也有正确的HTML内容。
4. Conclusion
4.总结
In this article, we looked at how to return HTML from a Spring MVC controller.
在这篇文章中,我们研究了如何从Spring MVC控制器中返回HTML。
As always, code samples are available over on GitHub.
像往常一样,代码样本可在GitHub上获得。