Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to access member variables using ApplicationContext in Spring MVC

In this tutorial, we will learn what is ApplicationContext and the process to create web application with ApplicationContext using Spring MVC 3.2.

ApplicationContext is an interface implemented to create bean objects for all the defined beans into spring configuration file. This file should be assigned into the classpath of the project. This interface creates an application context object for a class that required to be created for once for a specific configuration file. This context object will help us to create bean object for the bean classes.

Create Bean Class object using ApplicationContext Interface:

To create a bean object for the spring bean container, an interface (ApplicationContext) is widely used that is defined in “org.springframework.context”. In this article, we will create a web application using Spring MVC and ApplicationContext interface will be used to bean object of bean class “Triangle” to access draw() method. This method returns a string that will be printed into the loaded JSP page. We are going to create this web application using Eclipse IDE.

Required Tools & Application:

To create this web application, we are required following tools and applications:

  • Eclipse IDE
  • Application or Web Server (Tomcat Apache 7 is used)
  • JDK Environment (Jdk 7 is used)

Create a web application using following steps:

  • Go to file->new->other that will open a wizard “Select a wizard” and write “Dynamic Web Project” and hit “Finish”.
  • This opens “Dynamic Web Project” wizard, place a project name, target run time environment.
  • Press next and next, choose “Generate web.xml deployment descriptor and hit “Finish”.

This creates a directory structure like this:

Directory Structure for Dynamic Web Project created

Figure 1: Directory Structure for Dynamic Web Project created

The above figure shows the directory structure for “Dynamic Web Project” created using “Eclipse” IDE.

We are required to add a set of spring jar files with this project. To add these jar files into this project, right click on project and choose “Build Path->Configure Build Path” click on “Libraries” tab and choose or create a user library or add jar files directly using “Add External JARs”.

Required Jar Files

Figure 2: Required Jar Files

These are the required list of jar files.

All the request comes to deployed web application will hit the deployment descriptor xml file web.xml.

Listing 1: web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>ApplicationContext</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>ApplicationContextApp</servlet-name>
    <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>ApplicationContextApp</servlet-name>
    <url-pattern>*.html</url-pattern>
  </servlet-mapping>
</web-app>

The above code loads web.xml file, a deployment descriptor file. All requests hit this file and are transferred to “DispatcherServlet” class of “org.springframework.web.servlet” package. It loads the default file “index.jsp” defined in <weblcome-file-list> and its sub-tag <weblcome-file>, once the application has been deployed.

Listing 2: index.jsp

<html>
<head>
<title>Application Context App | Index</title>
</head>
<body>
	<br>
	<div align='center'>
	<h2>
		WELCOME TO Application Context APP     
		<a href="triangle.html">Load Triangle</a>
	</h2>
	</div>
</body>
</html>

The above code creates an interface for application welcome file that has a hyper link to load the controller method using “triangle.html” file name.

Listing 3: springmvcapp-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:component-scan base-package="com.springmvcapp.controller" />
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

The springmvcapp-servlet.xml file defines a directory for controller and view portion of the application. The base-package name “com.springmvcapp.controller” is loaded with its sub-packages and java class files to be managed as controller and models. The directory name “WEB-INF/jsp” contains all the view for the application.

Listing 4: Shape.java

package com.springmvcapp.controller;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class Shape {

   @RequestMapping("/triangle")
   public ModelAndView triangle() {
	   String message = "<br><div align='center'><h1>Triangle.<h1><br>";
	   ApplicationContext context = new ClassPathXmlApplicationContext("springContext.xml");
	   Triangle obj = (Triangle) context.getBean("triangle");
	   message += obj.draw();
       return new ModelAndView("welcome", "message1", message);
   }
}

The above code defines a Shape java class file that defines a “Shape” controller using @Controller annotation class defined in org.springframework.web.bind.annotation package. This annotation defines that the defining class is being manipulated as a controller for the application. We can define a specific string to be mapped by the url. @RequestMapping annotation is used to define mapped string type that will be mapped to the requested url to reach the “Shape” controller. “triangle” string is defined as mapped string as follows:

@RequestMapping (“/triangle”)

This annotation is method specific and defined before the method definition.

This class defines a method triangle() that return data object to ModelAndView class type that loads the “welcome” jsp file with the message variable name “message1” using the string variable “message” defined in class.

In this method, An instance of ApplicationContext interface is created. A ClassPathXmlApplicationContext() constructor is assigned to this instance that initialized all the defined beans in “spring.xml” file.

A bean class is defined in this configuration file as :

Listing 5: spring.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <bean id = "triangle" class = "com.springmvcapp.controller.Triangle">
    	<property name="type" value = "Equiletral Type"/>
    </bean>
</beans>

The <bean> tag defines a bean for bean class “Triangle” defined in “com.springmvcapp.controller” package. The <property> tag is used to assign the “type” member variable of bean class “Triangle” using “name” and “value” attributes.

Listing 6: Triangle.java

package com.springmvcapp.controller;

public class Triangle {
	private String type;
	
	public Triangle(){
		
	}
	public Triangle(String type){
		this.type = type;
	}
	
	public Triangle(int height){
		this.height = height;
	}
	
	public Triangle(String type, int height){
		this.type = type;
		this.height = height;
	}
	  
	public String getType() {
		return type;
	}
      
     public void setType(String type) {
		this.type = type;
	}

	public String draw(){
		return getType() + " Triangle Drawn";
	}
}

The above code defines a bean class “Triangle”. It defines a draw() method that will be called by “Shape” controller, once an ApplicationContext instance has been created.

Listing 7: WEB-INF/jsp/welcome.jsp

<html>
<head>
    <title>Application Context Welcome File</title>
</head>
<body>
    ${message1}
</body>
</html>

The above code defines a jsp file that is loaded by the “helloworld” controller and displays the message that is passed by the controller method “helloworld” using “ModelAndView” class. A variable “message1” is passed by controller to welcome.jsp to display a message. To display the information passed from the controller, we use ${variable-name-passed-by-controller} syntax as follows:

${message1}

Where message1 is the variable passed by the controller.

Now to deploy the application on the server, right click on the application directory structure and choose “Run As->Run on Server” that opens “Run on Server” wizard and choose the server configured with the Eclipse IDE. Press next or finish button to deploy the web application on the server immediately. Once the application has been deployed on the server, a new browser tab will be opened with its startup page. The url http://localhost:8080/ApplicationContext_Spring_MVC/ will open the deployed application into the web browser.

Application running into the browser

Figure 3: Application running into the browser

The above figure shows the running application into the web browser that was deployed on the web server with the application name “spring_mvc”. It loads the default jsp page with the url: http://localhost:8080/ApplicationContext_Spring_MVC/

There is a request to “Shape” controller which is defined inside the page using the anchor tag with the url triangle.html loads method triangle() as follows:

triangle.html

Figure 4: triangle.html

The figure 4 shows the HelloWorld controller request hitting to helloworld method with the url: http://localhost:8082/spring_mvc/triangle.html

Conclusion:

In this article, we learn:

  • What is spring MVC?
  • How do we create web application using Spring MVC 3.2?


I am a software developer from India with hands on experience on java, html for over 5 years.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login