WebApplicationContext in Spring MVC

WebApplicationContext in Spring MVC

`WebApplicationContext` is an extension of the standard `ApplicationContext` in Spring. It is specifically designed to provide the application context for a web application. It is used for configuring and managing beans in a web application, including controllers, services, and other components.

Key Features

  • Configuration and Initialization: It provides configuration and initialization for web-specific components such as servlets, filters, and listeners.
  • Scope Management: Supports web-specific scopes such as `request`, `session`, and `application` scopes.
  • Integration with Web Frameworks: Integrates with other web frameworks and technologies, handling the lifecycle and configuration of web components.

WebApplicationContext in Spring MVC

How It Works

  • Typically initialized by the `DispatcherServlet` in a Spring MVC application.
  • It loads the configuration from XML files or Java-based configuration classes.
  • Manages beans and dependencies, making them available throughout the web application.

Java ExampleKey Features:

  • Configuration and Initialization: It provides configuration and initialization for web-specific components such as servlets, filters, and listeners.
  • Scope Management: Supports web-specific scopes such as `request`, `session`, and `application` scopes.
  • Integration with Web Frameworks: Integrates with other web frameworks and technologies, handling the lifecycle and configuration of web components.

How It Works:

  • Typically initialized by the `DispatcherServlet` in a Spring MVC application.
  • It loads the configuration from XML files or Java-based configuration classes.
  • Manages beans and dependencies, making them available throughout the web application.

Java Example

Project Structure
1. Project Structure
```
src
 └── main
     └── java
         └── com
             └── example
                 └── config
                     └── WebAppConfig.java
                 └── controller
                     └── HomeController.java
     └── resources
         └── application.properties
     └── webapp
         └── WEB-INF
             └── views
                 └── home.jsp
     └── web.xml
```

Maven Dependencies (pom.xml)
2. Maven Dependencies (pom.xml)
```xml
<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.3.10</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
        <scope>provided</scope>
    </dependency>
</dependencies>
```

Web Application Context Configuration (WebAppConfig.java)
3. Web Application Context Configuration (WebAppConfig.java)

Using Java-based configuration:
```java
package com.example.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
@EnableWebMvc
public class WebAppConfig implements WebMvcConfigurer {

    @Bean
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        return resolver;
    }
}
```
Using XML-based configuration (alternative):
```xml
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

Controller (HomeController.java)
4. Controller (HomeController.java)
```java
package com.example.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HomeController {

    @GetMapping("/")
    public String home(Model model) {
        model.addAttribute("message", "Hello, Spring MVC!");
        return "home";
    }
}
```

View (home.jsp)
5. View (home.jsp)
```jsp
<!DOCTYPE html>
<html>
<head>
    <title>Home</title>
</head>
<body>
    <h1>${message}</h1>
</body>
</html>
```

web.xml Configuration
6. web.xml Configuration
```xml
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" 
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
         http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" 
         version="4.0">
    
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/dispatcher-config.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>
```

Explanation of the Example:

1. WebAppConfig.java:

   This class configures the `WebApplicationContext` using Java-based configuration. It sets up the `InternalResourceViewResolver` to resolve view names to JSP files located in `/WEB-INF/views/`.

2. HomeController.java:

   A controller that handles HTTP GET requests to the root URL (`/`). It adds a message to the model and returns the view name `home`.

3. home.jsp:

   A JSP file that renders the model data with the message set by the controller.

4. web.xml:

   Configures the `DispatcherServlet` to use the Spring configuration file `/WEB-INF/spring/dispatcher-config.xml` and maps it to intercept all requests (`/`).

Homepage

Readmore