|
||
---|---|---|
gradle/wrapper | ||
src | ||
.gitignore | ||
build.gradle | ||
gradlew | ||
gradlew.bat | ||
README.md | ||
settings.gradle |
HelloSpringMVC
Is a trivial “Hello, World” web site with SpringMVC.
This application is an outcome of this 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
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 (from src/main/java/djmil/hellomvc/GreetingController.java
) shows the controller:
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
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.
Model, View and a Template
The implementation of the greeting()
method body relies on a view technology (in this case, Thymeleaf) 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:
<!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>
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" 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
:
<!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/.
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:
- 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.
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:
...
<body>
<p th:text="'Hello, ' + ${name} + '!'" />
<input placeholder="Enter username.."/>
<button>Go!</button>
</body>
</html>
<script>
function getName() {
const name = document.querySelector('input').value;
console.log(name);
window.open('http://localhost:8080/greeting?name='+name)
}
const button = document.querySelector('button');
button.addEventListener("click", getName);
</script>
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
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 (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.
It is nice to have a sanity check, but you should also write some tests that assert the behavior of your application.
Testing depth
You can as SpringBoot to test your app at the different depth. Trading test coverage for speed.
HTTP requests: application
Here, we are starting our 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:
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.
Web app only
Another useful approach is to not start the server at all but to test only the layer below that, where Spring handles the incoming HTTP request and hands it off to your controller. That way, almost of the full stack is used, and your code will be called in exactly the same way as if it were processing a real HTTP request but without the cost of starting the server. To do that, use Spring’s MockMvc
and ask for that to be injected for you by using the @AutoConfigureMockMvc
annotation on the test case. The following listing (from src/test/java/djmil/hellomvc/WebApplicationTest.java
) shows how to do so:
package djmil.hellomvc;
import static org.hamcrest.Matchers.containsString;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;
@SpringBootTest
@AutoConfigureMockMvc
public class WebApplicationTest {
@Autowired
private MockMvc mockMvc;
@Test
public void shouldReturnDefaultMessage() throws Exception {
this.mockMvc.perform(get("/greeting"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().string(containsString("Hello, World")));
}
}
In this test, the full Spring application context is started but without the server.
Controller: web layer only
We can narrow the tests to only the web layer by using @WebMvcTest
, as the following listing (from src/test/java/djmil/hellomvc/WebLayerTest.java
) shows:
@WebMvcTest
public class WebLayerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void shouldReturnDefaultMessage() throws Exception {
this.mockMvc.perform(get("/greeting")).andDo(print()).andExpect(status().isOk())
.andExpect(content().string(containsString("Hello, World")));
}
}
The test assertion is the same as in the previous case. However, in this test, Spring Boot instantiates only the web layer rather than the whole context. In an application with multiple controllers, you can even ask for only one to be instantiated by using, for example, @WebMvcTest(HomeController.class)
.
Testing with mocks
So far, our GreetingController
is simple and has no dependencies. We could make it more realistic by introducing an extra component, say another service which will harbor some business logic, in our case - calculate length of a URL name
parameter.
src/main/java/djmil/hellomvc/GreetingService.java
package djmil.hellomvc;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
@Service
public class GreetingService {
public int nameLength(String name) {
return name.length();
}
}
In SpringBoot @Service
annotation is usually used to mark business logic classes. Doing so allows SpringBoot IoC to handle dependencies between different classes. Here, we have to update GreetingsControler
to use GrretingsSrvice
to handle /greeting
request:
@Controller
public class GreetingController {
private final GreetingService greetigService;
public GreetingController(GreetingService greetigService) {
this.greetigService = greetigService;
}
@GetMapping("/greeting")
public String greeting(@RequestParam(name="name", required=false, defaultValue="World") String name, Model model) {
model.addAttribute("name", name);
model.addAttribute("nameLength", greetigService.nameLength(name));
// NOTE: Here we can request some data from our RESTful backend as well
return "greeting"; // view tempalte
}
}
Spring IoC will insert instance of GreetingService
as a constructor parameter of GreetingController
, which we store as a private class member for later use.
Also, to make full use of newly created service, update src\main\resources\templates\greeting.html
:
<p th:text="'Hello, ' + ${name} + '!'" />
<p th:text="'Length of a given name is ' + ${nameLength} + ' characters.'" />
Run the tests, and notice that only GreetingControllerTest
has failed.
Mocking
To fix the test, we have to provide mock implementation of a GreetingService
class inside GreetingControllerTest
:
import static org.mockito.Mockito.when;
@WebMvcTest(GreetingController.class)
public class CreetingControllerTests {
@Autowired
private MockMvc mockMvc;
@MockBean
private GreetingService service;
@Test
public void greetingShouldReturnMessageFromService() throws Exception {
when(service.nameLength("World")).thenReturn(7);
this.mockMvc.perform(get("/greeting"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().string(containsString("Length of a given name is 7 characters.")));
}
}
Notice the @MockBean
annotation, which is essentially used to obtain an interface of a mocked class. Later, when
function used to define an actual mock.
Security
Let's say, that we want to have secret
endpoint, available only for for some users. SpringSecurity can be used to achieve this.
build.gradle
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-security'
testImplementation 'org.springframework.security:spring-security-test'
}
Security config
At the core of Spring Security architecture - lays concept of filters. Common practice is to use dedicated class as provider of desired security configuration.
src/main/java/djmil/hellomvc/SecurityConfig.java
package djmil.hellomvc;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
@Configuration
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(authz -> authz
.requestMatchers("/secret").authenticated()
.anyRequest().permitAll()
);
http
.formLogin(form -> form
.loginPage("/login")
.permitAll()
);
return http.build();
}
SecurityFilterChain
is used by FilterChainProxy to determine which Spring Security Filter
instances should be invoked for the current request. In this code snipped, we've defined:
- only
authenticated
users are allowed to access/secret
endpoint - all other request would be server without any restrictions
- login form is accessible at
/login
endpoint At this point, we shall make sure that this endpoint is known by our Controller
Login page
Basic idea is well defined in official documentation.
- First, a user makes an unauthenticated request to the resource (
/private
) for which it is not authorized. - Spring Security’s
AuthorizationFilter
indicates that the unauthenticated request is Denied by throwing anAccessDeniedException
. - Since the user is not authenticated,
ExceptionTranslationFilter
initiates Start Authentication and sends a redirect to the login page with the configuredAuthenticationEntryPoint
. In most cases, theAuthenticationEntryPoint
is an instance ofLoginUrlAuthenticationEntryPoint
. - The browser requests the login page to which it was redirected.
- Something within the application, must render the login page.
Login Form - src/main/resources/templates/login.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org">
<head>
<title>Please Log In</title>
</head>
<body>
<h1>Please Log In</h1>
<div th:if="${param.error}">
Invalid username and password.</div>
<div th:if="${param.logout}">
You have been logged out.</div>
<form th:action="@{/login}" method="post">
<div>
<input type="text" name="username" placeholder="Username"/>
</div>
<div>
<input type="password" name="password" placeholder="Password"/>
</div>
<input type="submit" value="Log in" />
</form>
</body>
</html>
LoginController
@Controller
class LoginController {
@GetMapping("/login")
String login() {
return "login";
}
}
User Authentication
Spring Security provides comprehensive support for Authentication. We are going to use In-Memory Authentication Mechanism
Add these Beans
to SecurityConfig.java
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public UserDetailsService testOnlyUsers(PasswordEncoder passwordEncoder) {
User.UserBuilder users = User.builder();
UserDetails sarah = users
.username("agent")
.password(passwordEncoder.encode("qaz123"))
//.roles("CARD-OWNER") // no roles for now
.build();
return new InMemoryUserDetailsManager(sarah);
}
Essentially, this means that our app would authorise only one hard-coded user. There are other ways to manage user login credentials.
Test
So far so good, in a best TDD fashion, let's write a test to check our secure endpoint security:
CreetingControllerTests.java
import org.springframework.security.test.context.support.WithMockUser;
...
@WebMvcTest(controllers = GreetingController.class)
public class CreetingControllerTests {
...
@Test
@WithMockUser(username = "user1", password = "pwd", roles = "USER")
public void secret() throws Exception {
when(service.nameLength("World")).thenReturn(7);
this.mockMvc.perform(get("/secret"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().string(containsString("Greetings user1!")));
}
}
@WithMockUser
injects mock user into Controller's test instance from WebMvcTest
.
[!note] Mock user from tests has nothing to do with In-Memory stored user credentials from README#User Authentication
Secure endpoint
Finally, everything is ready for creation of /secret
Secure Endpoint.
GreetingsController.java
import java.security.Principal;
...
@GetMapping("/secret")
public String secret(Principal principal, Model model) {
model.addAttribute("name", principal.getName());
model.addAttribute("secret", 42);
return "secret";
}
SpringSecurity will make sure to process all our previously defined security routines (alongside with applying some common protection techniques and utilities like Cookies) and only if the request was qualified - it will be served to the specified endpoint with all the security related info stored in convenient Principal
class.
Also, let's update our home page, so users would be aware of existence of our secret endpoint.
index.html
<body>
<p>Get your greeting <a href="/greeting">here</a></p>
<p>Get your secret <a href="/secret">here</a></p>
</body>
Upon attempt to visit /secret
endpoint, unauthenticated users would be redirected to /login
page, and if that was successful, they'd be redirected back to the /secret
. Spring framework is handling all that complexity for us.