BlogLovin

<a href="https://www.bloglovin.com/blog/18435741/?claim=cmyewjkgpb2">Follow my blog with Bloglovin</a>

Spring MVC and Java Based Configuration

Spring MVC and Java Based Configuration

In this Article, We will see How to configure Spring MVC application without using, web.xml and Spring config file. We will use Java based configuration.


For this example, we will use a simple Maven web Project.



Step 1. Create pom.xml for use required libraries.
  
<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/maven-v4_0_0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>com.example</groupId>
 <artifactId>SpringWebExample</artifactId>
 <packaging>war</packaging>
 <version>0.0.1-SNAPSHOT</version>
 <name>SpringWebExample Maven Webapp</name>
 <url>http://maven.apache.org</url>
 <properties>
      <java-version>1.7</java-version>
 </properties>
   <dependencies>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-webmvc</artifactId>
          <version>4.3.0.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>javax.servlet</groupId>
          <artifactId>javax.servlet-api</artifactId>
          <version>3.0.1</version>
          <scope>provided</scope>
      </dependency>
      <dependency>
          <groupId>javax.servlet</groupId>
          <artifactId>jstl</artifactId>
          <version>1.2</version>
      </dependency>
       <dependency>
         <groupId>junit</groupId>
         <artifactId>junit</artifactId>
         <version>3.8.1</version>
         <scope>test</scope>
          </dependency>
   </dependencies>
   <build>
      <finalName>HelloWorld</finalName>
      <pluginManagement>
          <plugins>
              <plugin>
                  <groupId>org.apache.maven.plugins</groupId>
                  <artifactId>maven-compiler-plugin</artifactId>
                  <version>2.3.2</version>
                  <configuration>
                      <source>${java-version}</source>
                      <target>${java-version}</target>
                  </configuration>
              </plugin>
              <plugin>
                  <groupId>org.apache.maven.plugins</groupId>
                  <artifactId>maven-war-plugin</artifactId>
                  <version>2.4</version>
                  <configuration>
                      <warSourceDirectory>src/main/webapp</warSourceDirectory>
                      <warName>SpringWebExample</warName>
                      <failOnMissingWebXml>false</failOnMissingWebXml>
                  </configuration>
              </plugin>
          </plugins>
      </pluginManagement>
   </build>
</project>



We use Spring 4.3.0 and Servlet 3.
Step 2: As we want to do java based configuration we will create a class called SpringConfig, where we will register all Spring related beans using Spring ‘s java based configuration style.


This class will replace the need to create a SpringApplicationContext.xml file, where we use two important tags

<context:component-scan/>
<mvc:annotation-driven/>      


Please note that this class has to extends import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter class.


Let see the class

SpringConfig.java

package com.example.anotatedconfiguration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;


@EnableWebMvc
@ComponentScan(basePackages = "com.example")
public class SpringConfig extends WebMvcConfigurerAdapter{
   
   @Bean
   public ViewResolver viewResolver() {@Configuration
      InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
      viewResolver.setViewClass(JstlView.class);
      viewResolver.setPrefix("/WEB-INF/pages/");
      viewResolver.setSuffix(".jsp");

      return viewResolver;
   }

   @Override
   public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
      configurer.enable();
   }

}



Please note that here we will use 3 different annotations  at top level, They will serve the purpose of Xml based tags used in earlier.


Xml Tag
Annotation
Description
<context:component-scan/>
@ComponentScan()
Scanned starts from base package and register all controller ,repository,service etc beans
<mvc:annotation-driven/>   
@EnableWebMvc
Enable Spring MVc specific annotation like @Controller
Spring config file
@Configuration
Treat as Configuration file for Spring MVC enable application.


also, We use @Bean tag to Register ViewResolver, we use InternalResourceViewResolver.



Step 3 :  Create another class which will replace our traditional web.xml. We use Servlet 3.0 version and extends org.springframework.web.WebApplicationInitializer class

WebServletConfiguration.java

package com.example.anotatedconfiguration;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

public class WebServletConfiguration implements WebApplicationInitializer{

   public void onStartup(ServletContext ctx) throws ServletException {
      AnnotationConfigWebApplicationContext webCtx = new AnnotationConfigWebApplicationContext();
      webCtx.register(SpringConfig.class);
      webCtx.setServletContext(ctx);

      ServletRegistration.Dynamic servlet = ctx.addServlet("dispatcher", new DispatcherServlet(webCtx));

      servlet.setLoadOnStartup(1);
      servlet.addMapping("/");
     
   }

}

Here we provide our SpringConfig class and add DispatcherServlet which acts as the FrontController of Spring MVC application.
SpringConfig class is the source of Spring beans,  previously which we do use contextConfiglocation.

Step 4: Now we will create a Controller class, Which will take a parameter from request URL and greet a message in the browser.

package com.example.anotatedconfiguration;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class GreetController {

@RequestMapping(path= "/greet/{name}",method=RequestMethod.GET)    
public String greet(@PathVariable String name, ModelMap model){
   
   String greet =" Hello !!!" + name + " How are You?";
   model.addAttribute("greet", greet);
   System.out.println(greet);
   return "greet";
}

}


Step 5:  Create a jsp page to show the message

<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<%@ page isELIgnored="false" %>
</head>
<h1>Welcome to Spring 4 and Servlet 3 Based Application</h1>
<body>
<div>

</div>
</body>
</html>


Please note that here I use <%@ page isELIgnored="false" %>, Because if JSTL version is old before 1.2 it can’t  evaluate  ${} EL. If your jstl version is 1.2 you can safely remove that tag.


Output :


Hello !!!shamik How are You?