How to do it...

When creating a Spring MVC application using Spring Boot 2.0, the first thing to consider is the Spring Boot starter parent POM configuration. This inherits all the Spring Boot Maven dependencies supported by the chosen Spring Boot version. In this book, version 2.0.0M2 is the updated milestone for Spring Boot 2.0 at the moment:

  1. Open the newly created pom.xml of ch09 and add the following starter parent configuration:
<project xmlns="http://maven.apache.org/POM/4.0.0"  
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0  
      http://maven.apache.org/xsd/maven-4.0.0.xsd"> 
     <modelVersion>4.0.0</modelVersion> 
  <groupId>org.packt.cookbook</groupId> 
  <artifactId>ch09</artifactId> 
  <version>0.0.1-SNAPSHOT</version> 
  <packaging>war</packaging> 
     <parent> 
      <groupId>org.springframework.boot</groupId> 
      <artifactId>spring-boot-starter-parent</artifactId> 
      <version>2.0.0.M2</version> 
      <relativePath/> 
     </parent> 
// refer to sources 
</project> 
  1. For this parent starter configuration to work, be sure to use the preceding Maven 3.x to compile and run the pom.xml.
  2. The Spring Boot starter parent requires setting the appropriate Java version for the Spring Boot since the default compiler level is always Java 1.6. Since we are into Spring Boot 2.0 that supports Spring 5, it is necessary to set the JVM version to at least 1.8 in the <properties> configuration of pom.xml. Also included in the settings are projects UTF encodings, runnable JAR's startClass, and Maven details:
<project xmlns="http://maven.apache.org/POM/4.0.0"  
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0  
      http://maven.apache.org/xsd/maven-4.0.0.xsd"> 
     <modelVersion>4.0.0</modelVersion> 
  <groupId>org.packt.cookbook</groupId> 
  <artifactId>ch09</artifactId> 
  <version>0.0.1-SNAPSHOT</version> 
  <packaging>war</packaging> 
  <parent> 
      <groupId>org.springframework.boot</groupId> 
      <artifactId>spring-boot-starter-parent</artifactId> 
      <version>2.0.0.M2</version> 
      <relativePath/> 
  </parent> 
     <properties> 
            <project.build.sourceEncoding>UTF-8 
</project.build.sourceEncoding> 
         <project.reporting.outputEncoding>UTF-8 
</project.reporting.outputEncoding> 
            <java.version>1.8</java.version> 
         <startClass>org.packt.spring.boot.HRBootApplication 
</startClass> 
     </properties> 
// refer to sources 
</project> 
  1. After configuring all the details about the starter parent, now add the Spring Boot starters that are needed to comprise the default configuration of the Spring Boot application. These starter POMs are one of the listed inherited dependencies of the starter parent. Their version numbers are not specified, since it is the job of the Spring Boot starter parent to figure out what versions are appropriate for the setup. Since the ultimate goal is to build a Spring MVC application, include the required starters in the <dependencies>, which is to be later configured by the application configuration file:
<dependencies> 
      <dependency> 
        <groupId>org.springframework.boot</groupId> 
        <artifactId>spring-boot-starter-web</artifactId> 
   </dependency> 
// refer to sources 
</dependencies> 
  1. Although Spring Boot 2.0 supports at least Tomcat 8.0 by default, the following starter for Tomcat embedded server can be included for some servlet container details, but be sure to set the scope to provided since we will be deploying this application to our Tomcat 9 in WAR format:
<dependency> 
    <groupId>org.springframework.boot</groupId> 
    <artifactId>spring-boot-starter-tomcat</artifactId> 
    <scope>provided</scope> 
</dependency> 
  1. The next starters are needed to configure the JSTL, FreeMarker, and Thymeleaf views:
<dependency> 
      <groupId>javax.servlet</groupId> 
      <artifactId>jstl</artifactId>  
   </dependency> 
   <dependency> 
      <groupId>taglibs</groupId> 
      <artifactId>standard</artifactId> 
      <version>1.1.2</version> 
</dependency> 
<dependency> 
    <groupId>org.springframework.boot</groupId> 
    <artifactId>spring-boot-starter-freemarker</artifactId> 
</dependency> 
<dependency> 
   <groupId>org.springframework.boot</groupId> 
   <artifactId>spring-boot-starter-thymeleaf</artifactId> 
</dependency> 
If there are dependencies that are not part of the starters, the version numbers of these artifacts must be specified.
  1. To load all the necessary Spring Boot 2.0.0.M2 starters, add the following Maven repositories:
<repositories> 
        <repository> 
            <id>spring-snapshots</id> 
            <url>http://repo.spring.io/snapshot</url> 
            <snapshots><enabled>false</enabled></snapshots> 
        </repository> 
        <repository> 
            <id>spring-milestones</id> 
            <url>http://repo.spring.io/milestone</url> 
            <snapshots>   
                <enabled>true</enabled>   
            </snapshots>   
        </repository> 
    </repositories> 
    <pluginRepositories> 
        <pluginRepository> 
            <id>spring-snapshots</id> 
            <url>http://repo.spring.io/snapshot</url> 
            <snapshots>   
                <enabled>false</enabled>   
            </snapshots>   
        </pluginRepository> 
        <pluginRepository> 
            <id>spring-milestones</id> 
            <url>http://repo.spring.io/milestone</url> 
            <snapshots>   
                <enabled>true</enabled>   
            </snapshots>   
        </pluginRepository> 
</pluginRepositories>
  1. To close this POM configuration, add the following Maven deployment details. The <finalName> determines the name of the deployed JAR or WAR file:
<build> 
   <plugins>   
         <plugin>   
             <groupId>org.springframework.boot</groupId>   
             <artifactId>spring-boot-maven-plugin</artifactId>   
         </plugin>   
   </plugins>   
   <finalName>ch09</finalName> 
</build> 
If this project is ought to be deployed as a WAR application, omit the spring-boot-maven-plugin. Otherwise, the Maven plugin stays if the project will be deployed as a standalone JAR application with its embedded Tomcat server. Some of the Maven plugins are already part of the starters such as maven-jar-plugin and maven-surefire-plugin .
  1. Save the pom.xml. Update the ch08 Maven project given the new POM configuration.
  2. Any Spring Boot application must have an execution point where all starter beans will be loaded into the container, project components will be recognized by Spring Boot default component scan, and auto-configuration will be enabled.
  3. This is the application's entry point that helps bootstrap the application either as standalone or servlet-based application:
@SpringBootApplication 
public class HRBootApplication  
extends SpringBootServletInitializer  { 
    
   @Override 
    protected SpringApplicationBuilder  
      configure(SpringApplicationBuilder application) { 
        return application.sources(HRBootApplication.class); 
    } 
 
    public static void main(String[] args) throws Exception { 
        SpringApplication.run(HRBootApplication.class, args); 
    } 
}
This component must be located in the core package org.packt.spring.boot to recognize all project components through its auto-configured component-scan capability. Also, if this project is designed for standalone JAR application, register this class in the <startClass> of POM's <properties> to be recognized as JAR's main-class by the parent starter.
  1. To add more non-reactive web configurations to the Application, the @Configuration classes must be generated to contain all the @Bean mappings needed to complete the MVC platform. In the previous Spring Boot releases, configuration classes are required to be registered in the META-INF, but with this version, it is no longer required. Add the following WebMvcConfigurerAdapter class in the new package org.packt.spring.boot.config that enables MVC, and adds required view resolvers, massage bundles, and static resources:
@Configuration 
@EnableWebMvc 
public class SpringMvcConfig extends WebMvcConfigurerAdapter {  
    
   @Bean 
   public InternalResourceViewResolver getViewResolver() { 
      InternalResourceViewResolver resolver =  
      new InternalResourceViewResolver(); 
      resolver.setPrefix("/WEB-INF/"); 
      resolver.setSuffix(".html"); 
      resolver.setOrder(3); 
      return resolver; 
   } 
 
   @Override 
   public void configureDefaultServletHandling( 
       DefaultServletHandlerConfigurer configurer) { 
       configurer.enable(); 
   }     
        
   @Bean 
   public ResourceBundleViewResolver bundleViewResolver(){ 
      ResourceBundleViewResolver viewResolverB =  
      new ResourceBundleViewResolver(); 
      viewResolverB.setBasename("config.views"); 
      viewResolverB.setOrder(0); 
      return viewResolverB; 
   } 
        
      
   @Bean 
   public MessageSource messageSource() { 
      ReloadableResourceBundleMessageSource messageSource =  
         new ReloadableResourceBundleMessageSource(); 
      messageSource.setBasenames( 
      "classpath:config/messages_en_US",  
      "classpath:config/errors"); 
      messageSource.setUseCodeAsDefaultMessage(true); 
      messageSource.setDefaultEncoding("UTF-8"); 
      messageSource.setCacheSeconds(1); 
      return messageSource; 
   } 
    
   @Bean 
   public static PropertySourcesPlaceholderConfigurer  
       propertyConfig() { 
       return new PropertySourcesPlaceholderConfigurer(); 
   } 
 
    @Override 
    public void addResourceHandlers(ResourceHandlerRegistry  
    registry) { 
       registry 
       .addResourceHandler("/css/**") 
       .addResourceLocations("/js/") 
       .setCachePeriod(31556926); 
    } 
} 
The use of JSP as view is not really recommended because it will add more servlet-based configurations to the application, which will create so many issues on the auto-configuration processes of Spring Boot. Besides, Spring Boot supports many templating engines such as FreeMarker , Thymeleaf , Velocity, and Mustache that are directly supported by the application.
  1. To use FreeMarker and Thymeleaf templates, add the following starters:
<dependency> 
       <groupId>org.springframework.boot</groupId> 
       <artifactId>spring-boot-starter-freemarker</artifactId> 
</dependency> 
<dependency> 
      <groupId>org.springframework.boot</groupId> 
      <artifactId>spring-boot-starter-thymeleaf</artifactId> 
</dependency>
  1. The next step is to set up the Thymeleaf and FreeMarker properties through the application configuration file. However, since we have injected into the application InternalResourceViewResolver and ResourceBundleViewResolver, conflicts arise when it comes to the ordering of view hierarchy. There will be no choice but to inject all the configuration @Bean for these templating engines using another non-reactive @Configuration class to be dropped inside the package org.packt.spring.boot.config:
@Configuration 
@EnableWebMvc 
public class SpringContextConfig  { 
    
   @Autowired 
   private ApplicationContext applicationContext; 
    
   @Bean(name = "viewResolverFTL") 
   public FreeMarkerViewResolver getViewResolverFtl() { 
       FreeMarkerViewResolver viewResolver =  
new FreeMarkerViewResolver(); 
       viewResolver.setPrefix(""); 
       viewResolver.setSuffix(".ftl"); 
       viewResolver.setOrder(1); 
       return viewResolver; 
   } 
  
   @Bean(name = "freemarkerConfig") 
   public FreeMarkerConfigurer getFreemarkerConfig() { 
      FreeMarkerConfigurer config = new FreeMarkerConfigurer(); 
      config.setTemplateLoaderPath("/WEB-INF/templates/"); 
      return config; 
   } 
       
   @Bean(name ="templateResolver")   
   public SpringResourceTemplateResolver getTemplateResolver() { 
      SpringResourceTemplateResolver templateResolver =  
new SpringResourceTemplateResolver(); 
      templateResolver.setApplicationContext( 
applicationContext); 
         templateResolver.setPrefix("/WEB-INF/templates/"); 
         templateResolver.setSuffix(".html"); 
         templateResolver.setTemplateMode("XHTML"); 
         return templateResolver; 
   } 
    
   @Bean(name ="templateEngine")      
   public SpringTemplateEngine getTemplateEngine() { 
         SpringTemplateEngine templateEngine =  
new SpringTemplateEngine(); 
         templateEngine.setTemplateResolver(getTemplateResolver()); 
         return templateEngine; 
   } 
    
   @Bean(name="viewResolverThymeLeaf") 
   public ThymeleafViewResolver getViewResolverThyme(){ 
         ThymeleafViewResolver viewResolver =  
new ThymeleafViewResolver();  
         viewResolver.setTemplateEngine(getTemplateEngine()); 
         viewResolver.setOrder(2); 
         return viewResolver; 
} 
} 
  1. One of the most important components of this application is the application configuration file that contains all the predefined properties of the supported dependencies needed by all the auto-configuration classes found in Spring Boot 2.0. This file is fetched and read during bootstrap of HRBootApplication to supply all the properties to the auto-configuration classes enabled by the starter dependencies. This file is popular as application.xml, application.properties, or application.yml, and is always located in the src/main/resources folder:
server.port=8443 
server.servlet.context-path=/ch09 
server.ssl.key-store=spring5server.keystore 
server.ssl.key-store-password=packt@@ 
server.ssl.keyStoreType=PKCS12 
server.ssl.keyAlias=spring5server 
 
spring.thymeleaf.cache=false 
#spring.thymeleaf.template-resolver-order=2 
#spring.thymeleaf.suffix=.html 
spring.freemarker.cache=false 
#spring.freemarker.suffix=.ftl 
Some of the core properties of org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration and org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration classes are commented because these will be bypassed by FreeMarker and Thymeleaf configuration done in the context definition previously. All server.* property values are to be supplied to org.springframework.boot.autoconfigure.web.ServerProperties, which handles the embedded server auto-configuration.
  1. Create the src/main/resources/config folder and drop here the views.properties, errors.properties, and messages_en_US.properties from ch08, here. Modify them to fit into this recipe.
  2. Create src/main/webapp/WEB-INF/templates and drop all test view pages in JSTL, FreeMarker, and Thymeleaf rendition formats here.
  3. There are two ways how to deploy Spring Boot applications: JAR or WAR. In this recipe, this project will be deployed as a WAR as indicated in POM:
<project xmlns="http://maven.apache.org/POM/4.0.0"  
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0  
      http://maven.apache.org/xsd/maven-4.0.0.xsd"> 
     <modelVersion>4.0.0</modelVersion> 
  <groupId>org.packt.cookbook</groupId> 
  <artifactId>ch09</artifactId> 
  <version>0.0.1-SNAPSHOT</version> 
     <packaging>war</packaging> 
   // refer to sources 
</project> 
  1. Run Maven command clean install -U. Deploy the WAR file manually in our installed Tomcat 9. The Spring Boot 2.0 project will have a directory structure like this:
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.19.243