Spring5 MVC HelloWorld JavaConfig Example

By | | Updated : 2018-12-01 | Viewed : 429 times

Spring5 MVC HelloWorld JavaConfig Example

In this current lesson, we will configure and execute Spring5 MVC HelloWorld example. Here we will use java based configuration.

    Requirements

  • Spring5 Web MVC

  • Java 1.8+

  • Eclipse 4.8.0

  • Servlet 4.0

  • apache-tomcat-9.0.12

Spring5 MVC HelloWorld JavaConfig Example

As we are using the Maven as build management tool, we will create a maven project in eclipse as given below.

Create Maven project for Spring5 MVC HelloWorld JavaConfig Example
<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>com.docsconsole.tutorials.springmvc</groupId>
  <artifactId>Spring5-MVC-HelloWorld-JavaConfig-Example</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <name>Spring5 MVC HelloWorld JavaConfig Example</name>
  <description>An Spring5 MVC HelloWorld Example with JavaConfig</description>
  
  <properties>
		<springframework.version>5.1.2.RELEASE</springframework.version>
		<maven.war.plugin.version>3.2.2</maven.war.plugin.version>
		<servlets.version>4.0.0</servlets.version>
		<jsp.version>2.3.1</jsp.version>
		<jstl.version>1.2.2</jstl.version>
		<tld.version>1.1.2</tld.version>
		<maven.compiler.source>9</maven.compiler.source>
		<maven.compiler.target>9</maven.compiler.target>
	</properties>

	<dependencies>

		<!-- Spring core dependencies -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${springframework.version}</version>
		</dependency>

		<!-- Spring MVC dependencies -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${springframework.version}</version>

		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${springframework.version}</version>
		</dependency>
		<!-- SERVELET Dependency -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>${servlets.version}</version>
			<scope>provided</scope>
		</dependency>

		<!-- JSP Dependency -->
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>javax.servlet.jsp-api</artifactId>
			<version>${jsp.version}</version>
			<scope>provided</scope>
		</dependency>

		<!-- JSTL Dependency -->
		<dependency>
			<groupId>javax.servlet.jsp.jstl</groupId>
			<artifactId>javax.servlet.jsp.jstl-api</artifactId>
			<version>${jstl.version}</version>
		</dependency>

		<dependency>
			<groupId>taglibs</groupId>
			<artifactId>standard</artifactId>
			<version>${tld.version}</version>
		</dependency>

	</dependencies>

	<build>
		<pluginManagement>
			<plugins>
				<plugin>
					<groupId>org.apache.maven.plugins</groupId>
					<artifactId>maven-war-plugin</artifactId>
					<version>${maven.war.plugin.version}</version>
					<configuration>
						<warSourceDirectory>src/main/webapp</warSourceDirectory>
						<warName>${project.artifactId}</warName>
						<failOnMissingWebXml>false</failOnMissingWebXml>
					</configuration>
				</plugin>
			</plugins>
		</pluginManagement>
	</build>
</project>

We used web.xml in previous example to register and initialize the dispatcher servlet. But here we are using here java configuration. Servlet 3.0 allows java configuration for Servlet config.

Creation of WebAppInitializer.java
Right click on src/main/java 
--> New 
--> Click on Class 
--> Enter value for Package as com.docsconsole.tutorials.springmvc5.config and Enter value for Name WebAppInitializer.

    We can use two type of classes to register and initialize the dispatcher servlet in Spring Web MVC.

  • 1.WebApplicationInitializer

  • 2.AbstractAnnotationConfigDispatcherServletInitializer

WebAppInitializer.java by using WebApplicationInitializer
package com.docsconsole.tutorials.springmvc5.config;


import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

@Configuration
public class WebAppInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {

        AnnotationConfigWebApplicationContext dispatcherServletContext = new AnnotationConfigWebApplicationContext();

        dispatcherServletContext.register(WebMvcConfig.class);

        DispatcherServlet dispatcherServlet = new DispatcherServlet(dispatcherServletContext);

        // Create a servlet dynamically.
        ServletRegistration.Dynamic dispatcher = servletContext.addServlet("DispatcherServlet", dispatcherServlet);

        dispatcher.setLoadOnStartup(1);

        // Add servlet mapping url. All url end with .html will be processed by this servlet.
        dispatcher.addMapping("/");
    }

}
WebAppInitializer.java by using AbstractAnnotationConfigDispatcherServletInitializer
package com.docsconsole.tutorials.springmvc5.config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class WebAppInitializer extends
        AbstractAnnotationConfigDispatcherServletInitializer {
 
   @Override
   protected Class<?>[] getRootConfigClasses() {
	   return new Class[] { WebMvcConfig.class };
   }
 
   @Override
   protected Class<?>[] getServletConfigClasses() {
      return null;
   }
 
   @Override
   protected String[] getServletMappings() {
      return new String[] { "/" };
   }
}

We will create java file WebMvcConfig.java. it is equal to the xml file spring-dispatcher-servlet.xml.

Creation of WebMvcConfig.java
Right click on src/main/java 
--> New 
--> Click on Class 
--> Enter value for Package as com.docsconsole.tutorials.springmvc5.config and Enter value for Name WebMvcConfig.
WebMvcConfig.java
package com.docsconsole.tutorials.springmvc5.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
 
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "com.docsconsole.tutorials.springmvc5"})
public class WebMvcConfig implements WebMvcConfigurer {
 
   @Bean
   public InternalResourceViewResolver resolver() {
      InternalResourceViewResolver resolver = new InternalResourceViewResolver();
      resolver.setViewClass(JstlView.class);
      resolver.setPrefix("/WEB-INF/views/");
      resolver.setSuffix(".jsp");
      return resolver;
   }
  
}

We configured InternalResourceViewResolver for resolving the view. As per configuration we should configured all the views in folder /WEB-INF/views/

Creation of home.jsp
Right click on folder views 
--> New 
--> Click on Other 
--> JSP File (under Web)
--> Click on Next 
--> Enter value for Filename as home.jsp and  and click finish
home.jsp
<%@ page contentType = "text/html; charset = UTF-8" %>
<html>
   <head>
      <title>Spring5-MVC-HelloWorld-XMLConfig-Example</title>
   </head>
   
   <body>
      <h2 style="color: #528396;padding: 20 0 0 40;">${msg}</h2>
   </body>
</html>

After completion of all the above steps the project structure will be as given below.

Spring5 MVC HelloWorld JavaConfig Example

After deploying the war, please execute the below given url http://localhost:8080/Spring5-MVC-HelloWorld-JavaConfig-Example/getHelloMessage, you will find below given output in the browser.

Spring5 MVC HelloWorld JavaConfig Example
Leave A Reply