36-Spring Web with Spring Boot Flashcards
Types of Spring MVC applications
- Web Servlet
2. Web Reactive
What is the starter for Spring MVC?
spring-boot-starter-web
What jar files that spring-boot-starter-web includes?
spring-web.jar spring-webmvc.jar spring-boot-starter.jar jackson*.jar tomcat-embed.jar
Does the web starter depend on the validation starter?
No
List out Spring MVC components created at startup time
- DispatcherServlet
- HandlerAdapter
- MessageConverter
- ContentTypeManager
- HandlerMapper
- ViewResolver, LocalResolver, ExceptionResolver
What is the processing lifecycle of a REST request?
client -> DispatcherServlet -> Controller -> MessageConverter -> DispatcherServlet -> client
What are message-converters in Spring MVC?
If found on the classpath, Spring will use:
- Jackson for JSON/XML *
- JAXB for XML*
- GSON for JSON*
- Byte[], String, BufferredImage
- Form-based data
- Protobuf*
- Feed data such as ATOM/RSS*
- JAXP Source
Note:
- Requires 3rd party libs on the classpath
- Protobuf is not setup automatically
When need to use @ResponseBody?
In the controller class with @Controller, the method needs to mark with @ResponseBody to convert the return object to JSON before sending it to the client. We don't need this in @RestController controller class
How can Spring lookup for @PathVariable, @RequestParam parameters without a name? e.g. @PathVariable long accountId
- To do this the compiled class needs extra metadata – the names of the method parameters by using flag
-parameters
- Spring will lookup using parameter names:
a. @PathVariable(“accountId”) long accountId -> @PathVariable long accountId
b. @RequestParam(“overdrawn”) boolean overdrawn -> @RequestParam boolean overdrawn
How to set a request parameter optional?
@RequestParam(required=false) Integer location
How to enable message converters?
- Auto-configure if it’s Spring Boot app
- If not, need to
@Configuration @EnableWebMvc class Config {}
How to customize message-converters?
- Override WebMvcConfigurer.configureMessageConverters, annotate with @Configuration
- Mark this class with @Configuration
How to replace embedded tomcat with jetty?
In pom.xml,
- exclude sprint-boot-starter-tomcat from spring-boot-starter-web
- add dependency spring-boo-starter-jetty
How to configure to run the app from both the command line and web container?
- Extends SpringBootServletInitializer
- Implement SpringBootServletInitializer.configure(SpringApplicationBuilder)
add: builder.sources(Application.class) - Add normal main class (to run from the command line)
What does mvn package produce?
- app-0.0.1.jar: fat & executable jar
2. app-0.0.1.jar.original: traditional jar