Saturday, December 28, 2024
Google search engine
HomeLanguagesJavaSpring MVC using Java based configuration

Spring MVC using Java based configuration

Prerequisites: MVC Design Pattern, Spring MVC with JSP View
Spring MVC framework enables separation of modules namely Model, View and Controller and seamlessly handles the application integration. This enables the developer to create complex applications also using plain java classes. The model object can be passed between view and controller using maps. In this article, we will see how to set up a Spring MVC application in the Eclipse IDE and understand how to make applications. 
The Spring MVC framework is comprised of the following components: 
 

  • Model: A model can be an object or collection of objects which basically contains the data of the application.
  • View: A view is used for displaying the information to the user in a specific format. Spring supports various technologies like freemarker, velocity and thymeleaf.
  • Controller: It contains the logical part of the application. @Controller annotation is used to mark that class as controller.
  • Front Controller: It remains responsible for managing the flow of the web application. DispatcherServlet acts as a front controller in spring MVC.

Requirements : 

  • Eclipse (EE version).
  • Tomcat Apache latest version.

Steps to set up the Spring MVC application in eclipse IDE:
 

  • Step 1: Go to File menu and click on New -> Maven Project. 
     

  • Step 2: Then in the search bar, type maven. Click on Maven Project and click Next
     

  • Step 3: The default settings should remain as it is. Click Next. 
     

  • Step 4: Select maven-archetype-webapp for web application and click Next
     

  • Step 5: Give some Group id as well as Artifact id
     

  • Step 6: Right click on the project and go to Properties
     

  • Step 7: Click on targeted runtimes. Select the installed apache tomcat in your system. Click on apply -> apply and close. 
     

  • Step 8: The java files should be in src/main/java folder to build spring MVC project. Go to src folder in the project. Right click on main and click on New -> Folder. 
     

  • Step 9: Write java as folder name. 
     

  • Step 10: Create a java class inside com.neveropen.springmvc under src/main/java folder. The directory structure should look as follows. 
     

  • Steps to implement a Spring web MVC application using java based configuration:
    • Step 1: Initially, we need to create a POM.XML file. This file contains the maven dependencies of the spring framework to use them in the project.
       

XML




<project
  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.neveropen</groupId>
  <artifactId>SpringMVCjava</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>SpringMVCjava Maven Webapp</name>
  <dependencies>
   
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
     
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.3.12.RELEASE</version>
    </dependency>
     
  </dependencies>
  <build>
    <finalName>SpringMVCjava</finalName>
  </build>
</project>


  • Step 2: The project contains a web.xml file which receives all the requests from the client. We will use WebInitializer.java in place of web.xml. getServletMappings() function receive all the requests corresponding to the ‘/ ’ URL mapping. The function getServletConfigClasses() configures the dispatcher servlet and transfers the handler to dispatcher servlet java file MVCconfig.class. MVCconfig.java file is used in place of dispatcher servlet for java based configuration. This class should extend AbstractAnnotationConfigDispatcherServletInitializer class to serve the purpose of web.xml file in java based configuration. This file is defined as:
     

Java




package com.neveropen.web;
 
import org.springframework.web
    .servlet.support
    .AbstractAnnotationConfigDispatcherServletInitializer;
 
public class WebInitializer
    extends AbstractAnnotationConfigDispatcherServletInitializer {
 
    @Override
    protected Class<?>[] getRootConfigClasses()
    {
        // TODO Auto-generated method stub
        return null;
    }
 
    @Override
    protected Class<?>[] getServletConfigClasses()
    {
        // TODO Auto-generated method stub
        return new Class[] { MVCconfig.class };
    }
 
    @Override
    protected String[] getServletMappings()
    {
        // TODO Auto-generated method stub
        return new String[] { "/" };
    }
}


  • Step 3: Now, we need to create a MVCconfig.java file. This file is used in place of dispatcher servlet file. Annotating a class with the @Configuration indicates that the class can be used by the Spring IoC container as a source of bean definitions. To enable autodetection of the annotated controllers, it is required to add component scanning to the configuration. It also gives the path of base package (i.e com.neveropen.web) wherein controller files need to be searched. This class should extend WebMvcConfigurerAdapter class to serve the purpose of dispatcher servlet.
     

Java

package com.neveropen.web;

import org.springframework.context
.annotation.ComponentScan;
import org.springframework.context
.annotation.Configuration;
import org.springframework.web.servlet
.config.annotation
.WebMvcConfigurerAdapter;

@Configuration
@ComponentScan({ “com.neveropen.web” })

public class MVCconfig
extends WebMvcConfigurerAdapter {
}

  • Step 4: Now, we need to define a controller. Controllers interpret user input and transform it into a model that is represented to the user by the view. The @RequestMapping annotation is used to map the URLs such as “/greet” onto an entire class or a particular handler method. We create an object of ModelAndView class. setViewName() indicates the view to be called and addObject() indicates the dynamic content to be added to that object.
     

Java




package com.neveropen.web;
import org.springframework
    .stereotype.Controller;
import org.springframework.web
    .bind.annotation.RequestMapping;
import org.springframework.web
    .servlet.ModelAndView;
 
@Controller
public class GreetController {
 
    @RequestMapping("/greet")
    public ModelAndView showview()
    {
 
        ModelAndView mv = new ModelAndView();
        mv.setViewName("result.jsp");
        mv.addObject("result",
                     "GeeksForGeeks Welcomes "
                         + "you to Spring!");
        return mv;
    }
}


  • Step 5: Now, we need to create an index page for the application. It is the page which is displayed when the given URL is hit. So, we create the index.jsp file as follows:
     

HTML




<html>
<body>
<h2>Hello World!</h2>
    <form action="greet">
        <input type="submit" value="Press to greet">
    </form>
</body>
</html>


  • Step 6: When the press to greet button from the above defined index.jsp is pressed, Result.jsp page opens up. So, we need to define the Result.jsp file: 
     

HTML




<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" isELIgnored="false"%>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="ISO-8859-1">
        <title>Insert title here</title>
    </head>
    <body>
     
        <h1>${result}</h1>
         
    </body>
</html>


  • When index.jsp is opened:
  • When the button is pressed:
RELATED ARTICLES

Most Popular

Recent Comments