1. Overview
In this tutorial, we want to have a look at how to return HTML from a Spring MVC controller.
Let’s take a look at what needs to be done.
2. Maven Dependency
First, we have to add the spring-boot-starter-web Maven dependency for our MVC controller:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<versionId>3.1.5</versionId>
</dependency>
3. Controller
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.
Next, we configure our @GetMapping annotation to produce MediaType.TEXT_HTML_VALUE output.
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.
Without this last annotation, we’d receive a 404 error since a String return value by default refers to a view name.
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.
4. Conclusion
In this article, we looked at how to return HTML from a Spring MVC controller.
As always, code samples are available over on GitHub.