AEJP UNIT V
AEJP UNIT V
AEJP UNIT V
Spring Framework
Spring is a powerful lightweight application development framework used for Java Enterprise
Edition (JEE). In a way, it is a framework of frameworks because it provides support to various
frameworks such as Struts, Hibernate, Tapestry, EJB, JSF, etc. The framework in a broader sense
can be defined as a structure using which you can solve many technical problems. You can say
that the Spring Framework is a comprehensive tool for supporting applications using Java
programming language.
Roderick B. Johnson, an Australian computer specialist officially released the Spring
Framework in 2004. Since its origin, the Spring Framework has released many versions. 4.3.8 is
the current Spring Framework version.
Features Of Spring Framework
Lightweight: Spring Framework is lightweight with respect to size and transparency.
Inversion Of Control (IoC): In Spring Framework, loose coupling is achieved using
Inversion of Control. The objects give their own dependencies instead of creating or
looking for dependent objects.
Aspect Oriented Programming (AOP): By separating application business logic from
system services, Spring Framework supports Aspect Oriented Programming and enables
cohesive development.
Container: Spring Framework creates and manages the life cycle and configuration of
application objects.
MVC Framework: Spring Framework is a MVC web application framework. This
framework is configurable via interfaces and accommodates multiple view technologies.
Transaction Management: For transaction management, Spring framework provides a
generic abstraction layer. It is not tied to J2EE environments and it can be used in
container-less environments.
JDBC Exception Handling: The JDBC abstraction layer of the Spring Framework
offers an exception hierarchy, which simplifies the error handling strategy.
Why do we use Spring in Java?
Works on POJOs (Plain Old Java Object) which makes your application lightweight.
Provides predefined templates for JDBC, Hibernate, JPA etc., thus reducing your effort
of writing too much code.
Because of dependency injection feature, your code becomes loosely coupled.
Using Spring Framework, the development of Java Enterprise
Edition (JEE) applications became faster.
It also provides strong abstraction to Java Enterprise Edition (JEE) specifications.
It provides declarative support for transactions, validation, caching and formatting.
But because of having all these advanced features, often people tend to ask questions like,
Is Spring easy to learn?
So let me answer this question in very simple terms. Yes, Java Spring is really easy to learn as
the entire Spring framework is designed to work with POJOs rather than depending on special
interfaces, abstract classes, etc.
So, let’s now dive into this Spring Tutorial, starting off from the very basic differences between
Java and Spring.
What is the difference between Java and Spring?
The below table represents the differences between Java and Spring:
Java Spring
Java is one of the prominent programming Spring is a Java-based open-source application
languages in the market. framework.
Java provides a full-highlighted Enterprise Spring Framework comes with various modules
Application Framework stack called Java EE for like Spring MVC, Spring Boot, Spring Security
which provides various ready to use features for
web application development
web application development.
Java EE is built upon a 3-D Architectural Spring is based on a layered architecture that
Framework which are Logical Tiers, Client consists of various modules that are built on top
Tiers and Presentation Tiers. of its core container.
Since its origin till date, Spring has spread its popularity across various domains. Spring
Framework now is the foundation for various other Spring Projects that have come up in the
offerings in the last two to three years. Check the below image to find out various projects
undertaken by Spring.
Spring Framework Architecture
As you can see in the diagram below, Spring Framework architecture is an arranged layered
architecture that consists of different modules. All the modules have their own functionalities
that are utilized to build an application. There are around 20 modules that are generalized into
Core Container, Data Access/ Integration, Web, AOP (Aspect Oriented Programming),
Instrumentation, and Test. Here, the developer is free to choose the required module. Its
modular architecture enables integration with other frameworks without much hassle.
Let’s now explore these modules in detail. I will start with the Core Container on which the rest
of the modules are constructed, then I’ll talk about Data Access followed by Web and AOP.
Finally, I will discuss some of the miscellaneous modules.
Let us start actual programming with Spring Framework. Before you start writing your first
example using Spring framework, you have to make sure that you have set up your Spring
environment properly as explained in Spring - Environment Setup Chapter. We also assume that
you have a bit of working knowledge on Eclipse IDE.
Now let us proceed to write a simple Spring Application, which will print "Hello World!" or any
other message based on the configuration done in Spring Beans Configuration file.
Step 1 - Create Java Project
The first step is to create a simple Java Project using Eclipse IDE. Follow the option File → New
→ Project and finally select Java Project wizard from the wizard list. Now name your project
as HelloSpring using the wizard window as follows −
Once your project is created successfully, you will have the following content in your Project
Explorer −
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
Usually developers name this file as Beans.xml, but you are independent to choose any name
you like. You have to make sure that this file is available in CLASSPATH and use the same
name in the main application while creating an application context as shown in MainApp.java
file.
The Beans.xml is used to assign unique IDs to different beans and to control the creation of
objects with different values without impacting any of the Spring source files. For example,
using the following file you can pass any value for "message" variable and you can print
different values of message without impacting HelloWorld.java and MainApp.java files. Let us
see how it works −
<?xml version = "1.0" encoding = "UTF-8"?>
</beans>
When Spring application gets loaded into the memory, Framework makes use of the above
configuration file to create all the beans defined and assigns them a unique ID as defined in
<bean> tag. You can use <property> tag to pass the values of different variables used at the
time of object creation.
Step 5 - Running the Program
Once you are done with creating the source and beans configuration files, you are ready for this
step, which is compiling and running your program. To do this, keep MainApp.Java file tab
active and use either Run option available in the Eclipse IDE or use Ctrl + F11 to compile and
run your MainApp application. If everything is fine with your application, this will print the
following message in Eclipse IDE's console −
Your Message : Hello World!
Congratulations, you have successfully created your first Spring Application. You can see the
flexibility of the above Spring application by changing the value of "message" property and
keeping both the source files unchanged.
Every Java-based application has a few objects that work together to present what the
end-user sees as a working application. When writing a complex Java application, application
classes should be as independent as possible of other Java classes to increase the possibility to
reuse these classes and to test them independently of other classes while unit testing.
Dependency Injection (or sometime called wiring) helps in gluing these classes together and at
the same time keeping them independent.
Consider you have an application which has a text editor component and you want to provide a
spell check. Your standard code would look something like this −
public class TextEditor {
private SpellChecker spellChecker;
public TextEditor() {
spellChecker = new SpellChecker();
}
}
What we've done here is, create a dependency between the TextEditor and the SpellChecker. In
an inversion of control scenario, we would instead do something like this −
public class TextEditor {
private SpellChecker spellChecker;
// Class
// Implementing Sim interface
public class Jio implements Sim{
@Override
public void calling() {
System.out.println("Jio Calling");
}
@Override
public void data() {
System.out.println("Jio Data");
}
}
So let’s now call these methods inside the main method. So by implementing the Run time
polymorphism concept we can do something like this
// Java Program to Illustrate Mobile Class
// Class
public class Mobile {
sim.calling();
sim.data();
}
}
But what happens if in the future another new Sim Vodafone came and we need to change again
to the child class name in the code, like this
Sim sim = new Vodafone();
So we have to do our configuration in the source code. So how to make it configurable? We
don’t want to touch the source code of this. The source code should be constant. And how can
we make it? Here Spring IoC comes into the picture. So in this example, we are going to use
ApplicationContext to implement an IoC container. First, we have to create an XML file and
name the file as “beans.xml“.
Example: beans.xml File
<?xml version="1.0" encoding="UTF-8"?>
<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
https://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>
Output Explanation: In the beans.xml file, we have created beans. So inside the id, we have to
pass the unique id and inside the class, we have to pass the Class name for which you want to
create the bean. Later on, inside the main method, we can tweek it out that will be described in
the upcoming program.
Bean Definition: In Spring, the objects that form the backbone of your application and that are
managed by the Spring IoC container are called beans. A bean is an object that is instantiated,
assembled, and otherwise managed by a Spring IoC container.
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
The Spring framework consists of seven modules which are shown in the above Figure. These
modules are Spring Core, Spring AOP, Spring Web MVC, Spring DAO, Spring ORM, Spring
context, and Spring Web flow. These modules provide different platforms to develop different
enterprise applications; for example, you can use Spring Web MVC module for developing
MVC-based applications.
Spring Framework Modules
Spring Core Module:
The Spring Core module, which is the core component of the Spring framework, provides
the IoC container There are two types of implementations of the Spring container,
namely, bean factory and application context. Bean factory is defined using the
org.springframework.beans.factory.BeanFactory interface and acts as a container for
beans. The Bean factory container allows you to decouple the configuration and
specification of dependencies from program logic. In the Spring framework, the Bean
factory acts as a central IoC container that is responsible for instantiating application
objects. It also configures and assembles the dependencies between these objects. There
are numerous implementations of the BeanFactory interface. The XmlBeanFactory class
is the most common implementation of the BeanFactory interface. This allows you to
express the object to compose your application and remove interdependencies between
application objects.
Spring AOP Module:
Similar to Object-Oriented Programming (OOP), which breaks down the applications
into hierarchy of objects, AOP breaks down the programs into aspects or concerns.
Spring AOP module allows you to implement concerns or aspects in a Spring application
in Spring AOP, the aspects are the regular Spring beans or regular classes annotated with
@Aspect annotation. These aspects help in transaction management and logging and
failure monitoring of an application. For example, transaction management is required in
bank operations such as transferring an amount from one account to another Spring AOP
module provides a transaction management abstraction layer that can be applied to
transaction APIs.
Spring ORM Module:
The Spring ORM module is used for accessing data from databases in an application. It
provides APIs for manipulating databases with JDO, Hibernate, and iBatis. Spring ORM
supports DAO, which provides a convenient way to build the following DAOs-based
ORM solutions:
o Simple declarative transaction management
o Transparent exception handling
o Thread-safe, lightweight template classes
o DAO support classes
o Resource management
Spring Web MVC Module:
The Web MVC module of Spring implements the MVC architecture for creating Web
applications. It separates the code of model and view components of a Web application.
In Spring MVC, when a request is generated from the browser, it first goes to the
DispatcherServlet class (Front Controller), which dispatches the request to a controller
(SimpleFormController class or AbstractWizardformController class) using a set of
handler mappings. The controller extracts and processes the information embedded in a
request and sends the result to the DispatcherServlet class in the form of the model
object. Finally, the DispatcherServlet class uses ViewResolver classes to send the results
to a view, which displays these results to the users.
Spring Web Flow Module:
The Spring Web Flow module is an extension of the Spring Web MVC module. Spring
Web MVC framework provides form controllers, such as class SimpleFormController
and AbstractWizardFormController class, to implement predefined workflow. The Spring
Web Flow helps in defining XML file or Java Class that manages the workflow between
different pages of a Web application. The Spring Web Flow is distributed separately and
can be downloaded through http://www.springframework.org website.
The following are the advantages of Spring Web Flow:
o The flow between different UIs of the application is clearly provided by defining
Web flow in XML file.
o Web flow definitions help you to virtually split an application in different
modules and reuse these modules in multiple situations.
Spring Web Flow lifecycle can be managed automatically
Spring Web DAO Module:
The DAO package in the Spring framework provides DAO support by using data access
technologies such as JDBC, Hibernate, or JDO. This module introduces a JDBC
abstraction layer by eliminating the need for providing tedious JDBC coding. It also
provides programmatic as well as declarative transaction management classes. Spring
DAO package supports heterogeneous Java Database Connectivity and O/R mapping,
which helps Spring work with several data access technologies. For easy and quick
access to database resources, the Spring framework provides abstract DAO base classes.
Multiple implementations are available for each data access technology supported by the
Spring framework. For example, in JDBC, the JdbcDaoSupport class and its methods are
used to access the DataSource instance and a preconfigured JdbcTemplate instance. You
need to simply extend the JdbcDaoSupport class and provide a mapping to the actual
DataSource instance in an application context configuration to access a DAO-based
application.
Spring Application Context Module:
The Spring Application context module is based on the Core module. Application context
org.springframework.context.ApplicationContext is an interface of BeanFactory. This
module derives its feature from the org.springframework.beans package and also supports
functionalities such as internationalization (I18N), validation, event propagation, and
resource loading. The Application context implements MessageSource interface and
provides the messaging functionality to an application.
Spring - Bean Definition
The objects that form the backbone of your application and that are managed by the
Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and
otherwise managed by a Spring IoC container. These beans are created with the configuration
metadata that you supply to the container. For example, in the form of XML <bean/> definitions
which you have already seen in the previous chapters.
Bean definition contains the information called configuration metadata, which is needed for the
container to know the following −
How to create a bean
Bean's lifecycle details
Bean's dependencies
All the above configuration metadata translates into a set of the following properties that make
up each bean definition.
Sr.No. Properties & Description
class
1
This attribute is mandatory and specifies the bean class to be used to create the bean.
name
2 This attribute specifies the bean identifier uniquely. In XMLbased configuration metadata,
you use the id and/or name attributes to specify the bean identifier(s).
scope
3 This attribute specifies the scope of the objects created from a particular bean definition
and it will be discussed in bean scopes chapter.
constructor-arg
4
This is used to inject the dependencies and will be discussed in subsequent chapters.
properties
5
This is used to inject the dependencies and will be discussed in subsequent chapters.
autowiring mode
6
This is used to inject the dependencies and will be discussed in subsequent chapters.
lazy-initialization mode
7 A lazy-initialized bean tells the IoC container to create a bean instance when it is first
requested, rather than at the startup.
initialization method
8 A callback to be called just after all necessary properties on the bean have been set by the
container. It will be discussed in bean life cycle chapter.
destruction method
9 A callback to be used when the container containing the bean is destroyed. It will be
discussed in bean life cycle chapter.
Spring Configuration Metadata
Spring IoC container is totally decoupled from the format in which this configuration metadata is
actually written. Following are the three important methods to provide configuration metadata to
the Spring Container −
XML based configuration file.
Annotation-based configuration
Java-based configuration
You already have seen how XML-based configuration metadata is provided to the container, but
let us see another sample of XML-based configuration file with different bean definitions
including lazy initialization, initialization method, and destruction method −
<?xml version = "1.0" encoding = "UTF-8"?>
</beans>
You can check Spring Hello World Example to understand how to define, configure and create
Spring Beans.
We will discuss about Annotation Based Configuration in a separate chapter. It is intentionally
discussed in a separate chapter as we want you to grasp a few other important Spring concepts,
before you start programming with Spring Dependency Injection with Annotations.
Naming Spring Beans
1. Overview
In this article, we'll look at how we can name our Spring beans. By controlling the naming of our
beans, we can tell Spring which beans we want to inject into a target bean.
2. Default Bean Naming Strategy
Let's start with the default bean naming strategy employed by Spring.
Spring gets the class name and converts the first letter to lowercase. Then, this value
becomes the name of the bean.
We'll use the AuditService interface for the upcoming examples:
public interface AuditService {
}
Now, let's see the default name generated for an AuditService implementation:
@Component
public class LegacyAuditService implements AuditService {
}
Here, we have the LegacyAuditService bean. Spring will register this bean under the name of
legacyAuditService.
3. Naming Beans using @Component
Now, let's look at how we can name our beans using the @Component annotation.
We can define the bean name using the value of @Component:
@Component("advanced")
public class AdvancedAuditService implements AuditService {
}
Here, Spring will register the AdvancedAuditService under the name of advanced.
4. Naming Beans using @Qualifier
Another way to name our Spring beans is by using the @Qualifier annotation.
Similar to @Component, we can use the value of @Qualifier to define a name. Moreover, we
can use both approaches at the same time:
@Component("advanced")
@Qualifier("qualifiedAdvanced")
public class AdvancedAuditService implements AuditService {
}
Here, Spring will register the AdvancedAuditService bean under two different names: advanced
and qualifiedAdvanced.
5. Using @Bean
There are also several approaches for naming the beans defined with the @Bean annotation.
5.1. Naming Beans with @Bean
Firstly, we can use the value of @Bean to name our beans:
public class SimpleAuditService implements AuditService{
}
Here is our SimpleAuditService class. Let's look at the bean configuration:
@Configuration
public class AuditConfiguration {
@Bean("simple")
public AuditService theSimpleOne() {
return new SimpleAuditService();
}
}
Here Spring will register SimpleAuditService under the name of simple.
5.2. Naming Beans with @Qualifier and @Bean
Secondly, we can use the @Qualifier annotation with @Bean methods to name our beans.
Moreover, we can also combine two approaches:
@Configuration
public class AuditConfiguration {
@Bean("simple")
@Qualifier("qualifiedSimple")
public AuditService theSimpleOne() {
return new SimpleAuditService();
}
}
As a result, Spring will register the SimpleAuditService bean under two names: simple and
qualifiedSimple.
5.3. Naming Beans with Method Name
Lastly, we can name our beans using the @Bean method name:
public class ObsoleteAuditService implements AuditService {
}
Here we have the ObsoleteAuditService class.
We'll look at the configuration next:
package com.javabyexamples.spring.core.beannaming;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AuditConfiguration {
@Bean
public AuditService obsolete(){
return new LegacyAuditService();
}
}
Since we aren't specifying a name in the @Bean annotation, Spring uses the method name,
obsolete, as the name of the bean.
Spring - Bean Scopes
When defining a <bean> you have the option of declaring a scope for that bean. For example, to
force Spring to produce a new bean instance each time one is needed, you should declare the
bean's scope attribute to be prototype. Similarly, if you want Spring to return the same bean
instance each time one is needed, you should declare the bean's scope attribute to be singleton.
The Spring Framework supports the following five scopes, three of which are available only if
you use a web-aware ApplicationContext.
Sr.No. Scope & Description
singleton
1
This scopes the bean definition to a single instance per Spring IoC container (default).
prototype
2
This scopes a single bean definition to have any number of object instances.
request
3 This scopes a bean definition to an HTTP request. Only valid in the context of a web-
aware Spring ApplicationContext.
session
4 This scopes a bean definition to an HTTP session. Only valid in the context of a web-
aware Spring ApplicationContext.
global-session
5 This scopes a bean definition to a global HTTP session. Only valid in the context of a
web-aware Spring ApplicationContext.
In this chapter, we will discuss about the first two scopes and the remaining three will be
discussed when we discuss about web-aware Spring ApplicationContext.
The singleton scope
If a scope is set to singleton, the Spring IoC container creates exactly one instance of the object
defined by that bean definition. This single instance is stored in a cache of such singleton beans,
and all subsequent requests and references for that named bean return the cached object.
The default scope is always singleton. However, when you need one and only one instance of a
bean, you can set the scope property to singleton in the bean configuration file, as shown in the
following code snippet −
<!-- A bean definition with singleton scope -->
<bean id = "..." class = "..." scope = "singleton">
<!-- collaborators and configuration for this bean go here -->
</bean>
Example
Let us have a working Eclipse IDE in place and take the following steps to create a Spring
application −
Steps Description
Create a project with a name SpringExample and create a package com.tutorialspoint under
1
the src folder in the created project.
Add required Spring libraries using Add External JARs option as explained in the Spring
2
Hello World Example chapter.
3 Create Java classes HelloWorld and MainApp under the com.tutorialspoint package.
4 Create Beans configuration file Beans.xml under the src folder.
The final step is to create the content of all the Java files and Bean Configuration file and
5
run the application as explained below.
Here is the content of HelloWorld.java file −
package com.tutorialspoint;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
</beans>
Once you are done creating the source and bean configuration files, let us run the application. If
everything is fine with your application, it will print the following message −
Your Message : I'm object A
Your Message : I'm object A
The prototype scope
If the scope is set to prototype, the Spring IoC container creates a new bean instance of the object
every time a request for that specific bean is made. As a rule, use the prototype scope for all
state-full beans and the singleton scope for stateless beans.
To define a prototype scope, you can set the scope property to prototype in the bean
configuration file, as shown in the following code snippet −
<!-- A bean definition with prototype scope -->
<bean id = "..." class = "..." scope = "prototype">
<!-- collaborators and configuration for this bean go here -->
</bean>
Example
Let us have working Eclipse IDE in place and follow the following steps to create a Spring
application −
Steps Description
Create a project with a name SpringExample and create a package com.tutorialspoint under
1
the src folder in the created project.
Add required Spring libraries using Add External JARs option as explained in the Spring
2
Hello World Example chapter.
3 Create Java classes HelloWorld and MainApp under the com.tutorialspoint package.
4 Create Beans configuration file Beans.xml under the src folder.
The final step is to create the content of all the Java files and Bean Configuration file and
5
run the application as explained below.
Here is the content of HelloWorld.java file
package com.tutorialspoint;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
HelloWorld objA = (HelloWorld) context.getBean("helloWorld");
</beans>
Once you are done creating the source and bean configuration files, let us run the application. If
everything is fine with your application, it will print the following message −
Your Message : I'm object A
Your Message : null
Spring Bean Reference ,<ref> Tag in Spring
In Spring if one Bean depends on another Bean class for some business logic, then this
type of dependency is called object dependency.In case of Object dependency in Spring, the
spring IOC container is responsible for creating that required object and injecting into the
dependent classes.
In Spring we need to use <ref> element to inform spring container about the object dependency.
In Spring, beans can "access" to each other by specify the bean references in the same or
different bean configuration file.In spring we can write multiple configuration xml file.Our
associated bean may be in same xml or in other xml file.
Syntax :
<ref bean="someBean"/>
Consider the xml file given below.
account-bean.xml
?
1<?xml version="1.0" encoding="UTF-8"?>
2<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3
xsi:schemaLocation="http://www.springframework.org/schema/beans
4
http://www.springframework.org/schema/beans/spring-beans.xsd">
5
6
<bean id="accountDetails" class="com.jwt.spring.AccountImpl"/>
7
8
</beans>
In the above xml file AccountImpl bean is configured.
Now in the below xml file we are referring ,”accountDetails” configured in the
account=bean.xml file, so we need to use ‘ref‘ tag with ‘bean‘ attribute i.e <ref
bean=”accountDetails”/>.
bank-bean.xml
?
1
2
<?xml version="1.0" encoding="UTF-8"?>
3
<beans xmlns="http://www.springframework.org/schema/beans"
4
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5
xsi:schemaLocation="http://www.springframework.org/schema/beans
6
http://www.springframework.org/schema/beans/spring-beans.xsd">
7
8
9
<bean id="bankservice" class="com.jwt.spring.BankService">
1
<property name="accdetails">
0
<ref bean="accountDetails"/>
1
</property>
1
</bean>
1
2
</beans>
1
3
public StudentsBean() {
}
public String getFirstName(){
return firstName;
}
public String getLastName(){
return lastName;
}
public int getAge(){
return age;
}
public void setFirstName(String firstName){
this.firstName = firstName;
}
public void setLastName(String lastName){
this.lastName = lastName;
}
public void setAge(Integer age){
this.age = age;
}
}
Accessing JavaBeans
The useBean action declares a JavaBean for use in a JSP. Once declared, the bean becomes a
scripting variable that can be accessed by both scripting elements and other custom tags used in
the JSP. The full syntax for the useBean tag is as follows −
<jsp:useBean id = "bean's name" scope = "bean's scope" typeSpec/>
Here values for the scope attribute can be a page, request, session or application based on your
requirement. The value of the id attribute may be any value as a long as it is a unique name
among other useBean declarations in the same JSP.
Following example shows how to use the useBean action −
<html>
<head>
<title>useBean Example</title>
</head>
<body>
<jsp:useBean id = "date" class = "java.util.Date" />
<p>The date/time is <%= date %>
</body>
</html>
You will receive the following result − −
The date/time is Thu Sep 30 11:18:11 GST 2010
Accessing JavaBeans Properties
Along with <jsp:useBean...> action, you can use the <jsp:getProperty/> action to access the
get methods and the <jsp:setProperty/> action to access the set methods. Here is the full syntax
−
<jsp:useBean id = "id" class = "bean's class" scope = "bean's scope">
<jsp:setProperty name = "bean's id" property = "property name"
value = "value"/>
<jsp:getProperty name = "bean's id" property = "property name"/>
...........
</jsp:useBean>
The name attribute references the id of a JavaBean previously introduced to the JSP by the
useBean action. The property attribute is the name of the get or the set methods that should be
invoked.
Following example shows how to access the data using the above syntax −
<html>
<head>
<title>get and set properties Example</title>
</head>
<body>
<jsp:useBean id = "students" class = "com.tutorialspoint.StudentsBean">
<jsp:setProperty name = "students" property = "firstName" value = "Zara"/>
<jsp:setProperty name = "students" property = "lastName" value = "Ali"/>
<jsp:setProperty name = "students" property = "age" value = "10"/>
</jsp:useBean>
<p>Student Age:
<jsp:getProperty name = "students" property = "age"/>
</p>
</body>
</html>
Let us make the StudentsBean.class available in CLASSPATH. Access the above JSP. the
following result will be displayed −
Student First Name: Zara
Student Age: 10
Resources
1 Introduction
Java's standard java.net.URL class and standard handlers for various URL prefixes unfortunately
are not quite adequate enough for all access to low-level resources. For example, there is no
standardized URL implementation that may be used to access a resource that needs to be
obtained from the classpath, or relative to a ServletContext. While it is possible to register new
handlers for specialized URL prefixes (similar to existing handlers for prefixes such as http:),
this is generally quite complicated, and the URL interface still lacks some desirable
functionality, such as a method to check for the existence of the resource being pointed to.
2 The Resource interface
Spring's Resource interface is meant to be a more capable interface for abstracting access to low-
level resources.
public interface Resource extends InputStreamSource {
boolean exists();
boolean isOpen();
String getFilename();
String getDescription();
}
public interface InputStreamSource {