Spring MVC & Spring Boot MVC
Spring MVC & Spring Boot MVC
Spring MVC & Spring Boot MVC
Agenda
• Creating controllers
• Rendering frontend
Service
Renders calls
HTML (using model)
Model
View
template
Spring MVC dependencies
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
Spring MVC configuration
@RequestMapping(value = "/home")
public String home() {
return "index.jsp";
}
}
Creating controllers
Mapping annotations
@Controller
public class AppController {
@GetMapping(value = "/home")
public String home(@RequestParam String page) {
…
return "index.jsp";
}
}
e.g. localhost:8080/home?page=3
Handling path parameters
@Controller
public class AppController {
@GetMapping(value = "/home/{page}")
public String home(@PathParam String page) {
…
return "index.jsp";
}
}
e.g. localhost:8080/home/3
Handling headers
@Controller
public class AppController {
@GetMapping(value = "/home/{page}")
public String home(@PathParam String page,
@RequestHeader(“Accept-Encoding") String encoding ) {
…
return "index.jsp";
}
}
Handling cookies
@Controller
public class AppController {
@GetMapping(value = "/home/{page}")
public String home(@PathParam String page,
@CookieValue("language") String lang) {
…
return "index.jsp";
}
}
Handling HTTP body
@Controller
public class AppController {
@GetMapping(value = "/home/{page}")
public String home(@PathParam String page,
@RequestBody Entity entity) {
…
return "index.jsp";
}
}
Handling exceptions
– SimpleMappingExceptionResolver
– DefaultHandlerExceptionResolver
– ResponseStatusExceptionResolver
– ExceptionHandlerExceptionResolver
Handling exceptions
@Bean
public ThymeleafViewResolver viewResolver() {
final ThymeleafViewResolver resolver =
new ThymeleafViewResolver();
…
return resolver;
}
}
Configuring a view resolver
@Bean
public ThymeleafViewResolver viewResolver() {
ThymeleafViewResolver viewResolver =
new ThymeleafViewResolver();
SpringResourceTemplateResolver templateResolver =
new SpringResourceTemplateResolver();
templateResolver.setPrefix("classpath:/views");
templateResolver.setSuffix(".html");
SpringTemplateEngine templateEngine =
new SpringTemplateEngine();
templateEngine.setTemplateResolver(
templateResolver);
viewResolver.setTemplateEngine(templateEngine);
return viewResolver;
}
Template engines
– Thymeleaf
– Velocity
– Freemarker
– Mustache
Passing the model
• For example:
@Bean
public HttpMessageConverters customConverters() {
HttpMessageConverter<?> first = ...
HttpMessageConverter<?> second = ...
return new HttpMessageConverters(first, second);
}
}
Default converters for JSON and XML and provided by Spring Boot
Static content
– /static
– /public
– /resources
– /META-INF/resources)
– Thymeleaf
– FreeMaker
– Groovy
– Mustache
Error handling