Advance Java - Unit3
Advance Java - Unit3
UNIT 3
By Shivani Deopa
Java Beans
Introduction
• "A JavaBean is a reusable software component that can be manipulated
visually in a builder tool.“
• They are classes that encapsulate many objects into a single object (the
bean).
• Following are the unique characteristics that distinguish a JavaBean from
other Java classes −
• It provides a default, no-argument constructor.
• It should be serializable and that which can implement
the Serializable interface.
• It may have a number of properties which can be read or written.
• It may have a number of "getter" and "setter" methods for the properties.
Why use Java Bean
• Presence of a no argument constructor;
• Support for persistence;
• Properties manipulated by getter and setter methods;
• Support for introspection;(Introspection is the automatic process of
analysing a bean's design patterns to reveal the bean's properties,
events, and methods. This process controls the publishing and
discovery of bean operations and properties.)
• Events as the mechanism of communication between beans;
• Support for customization via property editors.
Advantages
• Bean obtains all the benefits of Java's "write-once, run-anywhere" paradigm.
• The properties, events, and methods of a Bean that are exposed to an application
builder tool can be controlled.
• A Bean may be designed to operate correctly in different locales, which makes it
useful in global markets.
• Auxiliary software can be provided to help a person configure a Bean. This software is
only needed when the design-time parameters for that component are being set. It
does not need to be included in the run-time environment.
• The configuration settings of a Bean can be saved in persistent storage and restored
at a later time.
• A Bean may register to receive events from other objects and can generate events that
are sent to other objects.
Disadvantage
• A class with a nullary constructor is subject to being instantiated in an
invalid state. If such a class is instantiated manually by a developer (rather
than automatically by some kind of framework), the developer might not
realize that the class has been improperly instantiated.
• The compiler can’t detect such a problem, and even if it’s documented,
there’s no guarantee that the developer will see the documentation.
• Having to create a getter for every property and a setter for many, most, or
all of them creates an immense amount of boilerplate code.(boilerplate
code are sections of code that have to be included in many places with
little or no alteration.
• When using languages that are considered verbose, the programmer must
write a lot of code to accomplish only minor functionality. Such code is
called boilerplate.)
JavaBean Property
• A JavaBean property is a named S.No. Method & Description
attribute that can be accessed by
getPropertyName()
the user of the object. The For example, if property name
attribute can be of any Java data is firstName, your method name would
type, including the classes that 1
be getFirstName() to read that property.
you define. This method is called accessor.
• A JavaBean property may
be read, write, read only, setPropertyName()
or write only. JavaBean For example, if property name
properties are accessed through 2 is firstName, your method name would
two methods in the JavaBean's be setFirstName() to write that property.
implementation class − This method is called mutator.
Examples
class TestBean implements java.io.Serializable {
private String name;
public void setName(String name) { this.name = name; }
public String getName() { return name; }
}
public class Test {
public static void main(String args[])
{
TestBean s = new TestBean();
s.setName(“Demo");
System.out.println(s.getName());
} }
JSON:
Overview
• JavaScript Object Notation is an open-standard file format or data
interchange format that uses human-readable text to transmit data
objects consisting of attribute–value pairs and array data types (or
any other serializable value). It is a very common data format, with a
diverse range of applications, such as serving as replacement
for XML in AJAX systems.
• JSON is a language-independent data format. It was derived
from JavaScript, but many modern programming languages include
code to generate and parse JSON-format data. JSON filenames use
the extension .json.
• Why use JSON
1. Since JSON format is text only it is very easy to use for data transfer,
and can be used as a data format by any programming language
2. JSON.parse() parse a JSON string, constructing the JavaScript value
or object described by the string. So if we receive data from a
server, in JSON format, we can use it like any other JavaScript
3. The basic use of JSOn is transfer data between a server and web
application
4. Majorly JSON is used with modern programming language Web
services and API’s uses JSON format to provide public data
JSON Data Type
• JSON's basic data types are:
1. Number: a signed decimal number that may contain a fractional
part and may use exponential E notation, but cannot include non-
numbers such as NaN. The format makes no distinction between
integer and floating-point. JavaScript uses a double-precision
floating-point format for all its numeric values, but other languages
implementing JSON may encode numbers differently.
2. String: a sequence of zero or more Unicode characters. Strings are
delimited with double-quotation marks and support a
backslash escaping syntax.
3. Boolean: either of the values true or false
4. Array: an ordered list of zero or more values, each of which may be
of any type. Arrays use square bracket notation with comma-
separated elements.
5. Object: an unordered collection of name–value pairs where the
names (also called keys) are strings. Objects are intended to
represent associative arrays, where each key is unique within an
object. Objects are delimited with curly brackets and use commas
to separate each pair, while within each pair the colon ':' character
separates the key or name from its value.
6. null: an empty value, using the word null
JSON Syntax
{
"book": [
{
"id": "01",
"language": "Java",
"edition": "third",
"author": "Herbert Schildt"
},
{
"id": "07",
"language": "C++",
"edition": "second",
"author": "E.Balagurusamy"
}
]
}
Schema
• JSON Schema is a content specification language used for validating the structure
of a JSON data.It helps you specify the objects and what values are valid inside
the object’s properties. JSON schema is useful in offering clear, human-readable,
and machine-readable documentation.
• Structure of a JSON Schema: Since JSON format contains an object, array, and
name-value pair elements. Name-value pairs are used for providing schema
processing elements as well as validating the JSON content. Schema processing
elements include(not limited to).
1. $schema” To specify the version of JSON schema.
2. title and description: To provide information about the schema.
3. required: It’s an array of elements that indicates which elements should be
present.
4. additionalProperties: To indicate whether existence of specified elements are
allowed or not.
{ "lastName": {
"$id": "type": "string",
"https://example.com/person.schema.js "description": "The person's last
on", name."
"$schema": "http://json- },
schema.org/draft-07/schema#",
"title": "Voters information", "age": {
"type": "object", "description": "Age in years which
must be equal to or
"properties": { greater than eighteen in
"firstName": { order to vote.",
"type": "string", "type": "integer",
"description": "The person's first "minimum": 18
name." }
}, }
}
• The above JSON schema contains the following:
1. $id keyword
2. $schema keyword
3. title annotation keyword
4. properties validation keyword
5. Three keys: firstName, lastName and age each with their own
description keyword.
6. type instance data model (see above)
7. minimum validation keyword on the age key.
JSON vs XML
JSON XML
JSON object has a type XML data is typeless
JSON types: string, number, array, Boolean
All XML data should be string
Data is readily accessible as JSON objects
XML data needs to be parsed.
JSON is supported by most browsers. Cross-browser XML parsing can be tricky
JSON has no display capabilities. XML offers the capability to display data
because it is a markup language.
JSON supports only text and number data XML support various data types such as number,
type. text, images, charts, graphs, etc. It also provides
options for transferring the structure or format
of the data with actual data.
JSON XML
Retrieving value is easy Retrieving value is difficult
Supported by many Ajax toolkit Not fully supported by Ajax toolkit
A fully automated way of Developers have to write JavaScript code to
deserializing/serializing JavaScript. serialize/de-serialize from XML
Native support for object. The object has to be express by conventions -
mostly missed use of attributes and elements.
It supports only UTF-8 encoding. It supports various encoding.
It doesn't support comments. It supports comments.
JSON files are easy to read as compared to XML documents are relatively more difficult to
XML. read and interpret.
It does not provide any support for It supports namespaces.
namespaces.
It is less secured. It is more secure than JSON.
Example
{ "phoneNumbers": [
"firstName": "John", {
"lastName": "Smith", "type": "home",
"isAlive": true, "number": "212 555-1234"
"age": 27, }, {
"address": { "type": "office",
"streetAddress": "21 2nd Street", "number": "646 555-4567"
"city": "New York", },{
"state": "NY", "type": "mobile",
"postalCode": "10021-3100" "number": "123 456-7890"
}, }
],
"children": [], "spouse": null
}
Struts 2
Basic MVC Architecture
• Model View Controller or MVC as it is popularly called, is a software
design pattern for developing web applications. A Model View
Controller pattern is made up of the following three parts −
The View
• It means presentation of data in a particular format, triggered by a
controller's decision to present the data. They are script-based templating
systems like JSP, ASP, PHP and very easy to integrate with AJAX technology.
The Controller
• The controller is responsible for responding to the user input and perform
interactions on the data model objects. The controller receives the input, it
validates the input and then performs the business operation that modifies
the state of the data model.
Struts 2
• Struts framework helps for developing the web based applications.
• Struts java framework is one of the most popular framework for web based applications.
• Java Servlet, JavaBeans, ResourceBundles and XML etc are the Jakarta commons
packages used for accomplishing this purpose.
• This is an open-source implementation of MVC pattern for the development of web-
based application.
The features of this type of framework are:
• More robust or reliable architecture
• Helps for development of application of any size
• Easy to design
• Scalable
• Reliable web application with java.
Struts 2 Framework Features
• A framework is a group of services that provide developers with common
set of functionality to be reused amongst multiple applications
• Struts is a java-based framework which separate the application logic that
interacts with the database from an HTML page that form the response
• Struts is not a technology, it’s a framework that can be used along with
other java-based technologies
• Struts make ease of enterprise application development with flexible and
extensible application architecture and custom tags
• Struts 2 is a web application framework based on the OpenSymphony
WebWork framework that implements MVC design pattern
Configurable MVC components
• In struts 2 framework, we provide all the components (view components
and action) information in struts.xml file.
• If we need to change any information, we can simply change it in the xml
file.
POJO based actions
• In struts 2, action class is POJO (Plain Old Java Object) i.e. a simple java
class.
• Here, you are not forced to implement any interface or inherit any class.
AJAX support
• Struts 2 provides support to ajax technology. It is used to make
asynchronous request i.e. it doesn't block the user.
• It sends only required field data to the server side not all. So it makes the
performance fast.
Integration Support
• We can simply integrate the struts 2 application with hibernate, spring,
tiles etc. frameworks.
Various Result Types
• We can use JSP, freemarker, velocity etc. technologies as the result in struts
2.
Various Tag support
• Struts 2 provides various types of tags such as UI tags, Data tags, control
tags etc to ease the development of struts 2 application.
Theme and Template support
• Struts 2 provides three types of theme support: xhtml, simple and
css_xhtml.
• The xhtml is default theme of struts 2. Themes and templates can be used
for common look and feel.
Components of Struts 2 framework
Actions
1. Model is implemented in struts using actions.
2. Actions include the business logic and interacts with persistence storage ,retrieve
and manipulate data.
Interceptors
1. Interceptor is an object, that is invoked (executed) the pre-processing request
and post-processing request.
2. Interceptors are used to perform the validations, exceptions handling and display
the result in between the execute() method.
3. In struts 2, Interceptors execution is same as the servlet filter execution type.
4. Using Interceptors, One can run the application using validations, and can remove
the validations on that application and one cannot deploy the application in the
server. If it directly run on the server.
Value Stack / OGNL
• ValueStack is a type of stack, it contains some objects or requests.
ValueStack is used for hiding some data internally and execute in execute()
method.
1. OGNL (Object Graph Navigation Language) is one type of Expression
Language.
2. OGNL is used to simplify the ActionContext contains data. These OGNL
expressions are used to display the ValueStack object values in browser.
3. Push the values in ValueStack object, then the values is mapped to JSP
pages through property tag.
Result types
1. Results are UI that represents the user requirement from the application
onto the client browser
Life Cycle of Struts 2
1. When a request comes web container maps the request in the web.xml and
calls the controller (FilterDispatcher).
2. FilterDispatcher calls the ActionMapper to find an Action to be invoked.
3. FilterDispatcher calls the ActionProxy.
4. ActionProxy reads the information of action and interceptor stack from
configuration file using configuration manager (struts.xml) and invoke the
ActionInvocation.
5. ActionInvocation calls the all interceptors one by one and then invoke the
action to generate the result.
6. Action is executed ActionInvocation again calls the all interceptors in reverse
order.
7. Control is returned to the FilterDispatcher.
8. Result is sent to the client.
Disadvantage of Struts 2
• Bigger Learning Curve − To use MVC with Struts, you have to be
comfortable with the standard JSP, Servlet APIs and a large &
elaborate framework.
• Poor Documentation − Compared to the standard servlet and JSP
APIs, Struts has fewer online resources, and many first-time users find
the online Apache documentation confusing and poorly organized.
• Less Transparent − With Struts applications, there is a lot more going
on behind the scenes than with normal Java-based Web applications
which makes it difficult to understand the framework.
Struts 2 MVC Design Pattern
1. Action - model
2. Result - view
3. FilterDispatcher - controller
The role each module plays
• Controller's job is to map incoming HTTP requests to actions. Those mapping are defined
by using XML-based configuration(struts.xml) or Java annotations.
• Model in Struts 2 is actions. Each action is defined and implemented by following the
framework defined contract(e.g. consist an execute() method). Model component
consists the data storage and business logic. Each action is an encapsulation of requests
and is placed ValueStack.
• View is the presentation component of MVC pattern. In spire of common JSP files, other
techniques such as tilts, velocity, freemaker, etc. can be combined to provide a flexible
presentation layer.
• Interactions among each MVC module
Request Life Cycle
• Initially User sends a request to the server for requesting for some resource
(for example- pages).
• By looking at the request The Filter Dispatcher determines the appropriate
Action.
• Validation, file upload etc functionalities are applied by Configured
interceptor. For example- Selected action is performed based on the
request operation
• Again configured interceptors are applied to do any post-processing if
required
• Finally the result is prepared by the view and returns the result to the user
Actions
• In struts 2, action class is POJO (Plain Old Java Object).
• POJO means you are not forced to implement any interface or extend any class.
• Generally, execute method should be specified that represents the business logic.
The simple action class may look like:
Welcome.java
package javastruts;
public class Welcome {
public String execute(){
return "success";
}
}
Action Interface
• A convenient approach is to implement
the com.opensymphony.xwork2.Action interface that defines 5 constants and one
execute method.
5 Constants of Action Interface
• Action interface provides 5 constants that can be returned form the action class.
They are:
a) SUCCESS indicates that action execution is successful and a success result
should be shown to the user.
b) ERROR indicates that action execution is failed and a error result should be
shown to the user.
c) LOGIN indicates that user is not logged-in and a login result should be shown to
the user.
d) INPUT indicates that validation is failed and a input result should be shown to
the user again.
e) NONE indicates that action execution is successful but no result should be
shown to the user.
• Let's see what values are assigned to these constants:
1. public static final String SUCCESS = "success";
2. public static final String ERROR = "error";
3. public static final String LOGIN = "login";
4. public static final String INPUT = "input";
5. public static final String NONE = "none";
Method of Action Interface
• Action interface contains only one method execute that should be
implemented overridden by the action class even if you are not
forced.
public String execute();
Role of Action
• Perform as a model
1. Action performs as a model by encapsulating the actual work to be done for a
given request based on input parameters.
2. Encapsulation is done using the execute() method. The code inside this method
should only hold the business logic to serve a Request
• Serves as a data Carrier
1. Action serves as data Carrier from Request to the View. Action being the Model
component of the framework carries the data around.
2. The data it requires is held locally which makes it easy to access using
JavaBeans properties during the actual execution of the business logic
3. The execute() method simply references the data using JavaBean properties
• Helps Determine Result
Interceptors
• Interceptors are conceptually the same as servlet filters or the JDKs Proxy
class. Interceptors allow for crosscutting functionality to be implemented
separately from the action as well as the framework. You can achieve the
following using interceptors −
• Providing preprocessing logic before the action is called.
• Providing postprocessing logic after the action is called.
• Catching exceptions so that alternate processing can be performed.
• Many of the features provided in the Struts2 framework are implemented
using interceptors;
• Examples include exception handling, file uploading, lifecycle callbacks, etc.
In fact, as Struts2 emphasizes much of its functionality on interceptors, it is
not likely to have 7 or 8 interceptors assigned per action.
• Struts 2 framework provides a good list of out-of-the-box interceptors
that come preconfigured and ready to use.
• Few of the important interceptors are listed below −
checkbox: Assists in managing check boxes by adding a parameter value of false for check
2
boxes that are not checked.
conversionError: Places error information from converting strings to parameter types into the
3
action's field errors.
4 createSession: Automatically creates an HTTP session if one does not already exist.