# HelloSpringMVC Is a trivial “Hello, World” web site with SpringMVC. This application is an outcome of [this](https://spring.io/guides/gs/serving-web-content/) guide, which walks you through the process of creating a “Hello, World” web site with Spring. It serves 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 `World` and is reflected in the response by the content changing to “Hello, User!” # Spring Initializr In VsCode press `cmd+shif+p` and type `Spring Initilizr`. Choose next dependencies: - SpringWeb - Thymeleaf - Spring Boot DevTools # MVC ## 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`](http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/stereotype/Controller.html) annotation. In the following example, `GreetingController` handles GET requests for `/greeting` by returning the name of a [`View`](http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/View.html) (in this case, `greeting`). A `View` is responsible for rendering the HTML content. The following listing (from `src/main/java/djmil/hellomvc/GreetingController.java`) shows the controller: ```java package djmil.hellomvc; 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) { // NOTE: Here we can request some data from our RESTful backend as well model.addAttribute("name", name); return "greeting"; // <<-- template } } ``` 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`](http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestParam.html) 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`](http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/ui/Model.html) object, ultimately making it accessible to the view template. ## Model, View and a Template The implementation of the `greeting()` method body relies on a view technology (in this case, [Thymeleaf](http://www.thymeleaf.org/doc/tutorials/2.1/thymeleafspring.html)) to perform server-side rendering of the HTML. > [!note] Make sure you have Thymeleaf on your classpath. Artifact co-ordinates: `org.springframework.boot:spring-boot-starter-thymeleaf` 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 `src/main/resources/templates/greeting.html` shows the template: ```html Getting Started: Serving Web Content

``` ## 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`](http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestParam.html) 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" for serving web-content. Which means it is served up as the root resource (that is, at `http://localhost:8080/`). For this, you need to create the following file `src/main/resources/static/index.html`: ```html Getting Started: Serving Web Content

Get your greeting here

``` When you restart the application, you will see the HTML at http://localhost:8080/. ## 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](http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#using-boot-devtools): - Enables [hot swapping](https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#using.running-your-application.hot-swapping). - Switches template engines to disable caching. - Enables LiveReload to automatically refresh the browser. - Other reasonable defaults based on development instead of production. ## Interactivity Let's add minimal interactivity to the page by introducing an input field and a button. On the button press, a simple JavaScript will reload the page (by calling [[README#Web Controller]] 's `Get` endpoint) providing a value from the input filed as an URL parameter. Update `greeting.htm` with next lines: ```html ...

``` # Testing the Web Layer Let's test our simple app with JUnit. We will concentrate on using Spring Test and Spring Boot features to test the interactions between Spring and your code. ## Sanity check The first thing you can do is write a simple sanity check test that will fail if the application context cannot start. From `src/test/java/djmil/hellomvc/SmokeTest.java` ```java package djmil.hellomvc; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import static org.assertj.core.api.Assertions.assertThat; @SpringBootTest public class SmokeTest { @Autowired private GreetingController controller; @Test void contextLoads() throws Exception { assertThat(controller).isNotNull(); } } ``` The `@SpringBootTest` annotation tells Spring Boot to look for a main configuration class (one with `@SpringBootApplication`, for instance) and use that to start a Spring application context. You can run this test in your IDE or on the command line (by running `./mvnw test` or `./gradlew test`), and it should pass. Spring interprets the `@Autowired` annotation, and the controller is injected before the test methods are run. We use [AssertJ](http://joel-costigliola.github.io/assertj/) (which provides `assertThat()` and other methods) to express the test assertions. > A nice feature of the Spring Test support is that the application context is cached between tests. That way, if you have multiple methods in a test case or multiple test cases with the same configuration, they incur the cost of starting the application only once. You can control the cache by using the @DirtiesContext annotation. ## Test HTTP requests It is nice to have a sanity check, but you should also write some tests that assert the behavior of your application. To do that, you could start the application and listen for a connection (as it would do in production) and then send an HTTP request and assert the response. The following listing (from `src/test/java/djmil/hellomvc/HttpRequestTest.java`) shows how to do so: ```java package djmil.hellomvc; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.beans.factory.annotation.Value; import static org.assertj.core.api.Assertions.assertThat; @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) public class HttpRequestTest { @Value(value="${local.server.port}") private int port; @Autowired private TestRestTemplate restTemplate; @Test public void greetingShouldReturnDefaultMessage() throws Exception { assertThat(this.restTemplate.getForObject("http://localhost:" + port + "/greeting", String.class)).contains("Hello, World"); } } ``` Note the use of `webEnvironment=RANDOM_PORT` to start the server with a random port (useful to avoid conflicts in test environments) and the injection of the port with `@LocalServerPort`. Also, note that Spring Boot has automatically provided a `TestRestTemplate` for you. All you have to do is add `@Autowired` to it.