Stream Training Notes Java
Stream Training Notes Java
Default methods:
Present in an interface.
Have a body.
Allows to add new functionality while providing backward compatibility as default methods
don’t have to be overridden.
NOTE: In case of ambiguity when implementing 2 interfaces with same names of default
methods, we need to resolve it by overriding one of them,
Eg: public void log(){ Interface1.super.log() } //Interface1’s method is called
OR
Override it by defining separate function in the class
Class Welcome{
//method definitions
}; }
NOTE: the ‘Greeting’ interface could be used in a user class with SOP welcome user, in customer class, etc with
class specific SOPs.
NOTE: Compiler creates a class Welcome$1 but we can’t use it in our code.
CONS :
Bulky code.
Anonymous class can’t access variables not marked as final in its enclosing scope.
Declaring variable in anonymous class shadows other declarations with same name.
Difficult to optimize.
Static members must be final.
Functional Interface
Interface having only one abstract method (can have any number of static or default
methods).
If the interface overrides superclass’s abstract methods, it doesn’t count in its abstract
method count. Eg: Comparator interface has 2 abstract methods equals and compare. But
equals is overridden from Object class, so Comparator is a functional interface.
NOTE: If an interface has no methods it is called tag interface.
Lambda Expression
Support functional programming paradigm.( Different functions (or codes) applied to same
data. We can also say that function is passed as an argument).
Syntax:
(parameters) -> {statements;};
o If there is only 1 parameter, no () required.
o Either data type of all parameters must be present or none.
o If there is only 1 statement {} not needed.
Pros: Less code compared to anonymous inner class.
Eg: Greeting greeting=(name)->{System.out.println(“Hi”);};
Exception Hierarchy
Checked Exception have to be handled either by try-catch block or use throws keyword.
They are anticipated exceptions.
It is not compulsory to handle unchecked exception. They occur due to logical errors.
Try block
Valid forms: try-catch , try-finally, try-catch-finally
Finally block
Finally block is executed when we exit try block. It is used to release resources(eg close
connections).
Any object that implements AutoCloseable or Closeable interface can be used in try with
resources block.
Eg: Scanner, Connection
try (Scanner sc=new Scanner(System.in);
Connection c= new Connection() ){}
Only try with resources is valid
Throw keyword
Used to throw an object of Throwable or any class which extends Throwable
Throws clause
Used to indicate that the particular method can throw exceptions and they must be handled
in the calling method.
Errors
Errors are something that cannot be fixed. They can’t be anticipated or handled.
Eg: StackOverFlowError
Custom Exception:
We create a class for our custom exception which extends Exception
An object of this class can be thrown using throws keyword
Module: Collections
Collections vs Arrays
Parameter Collections Arrays
Collection Interface:
No direct implementation is provided. Has sub interfaces Set, List and Queue.
Set Interface:
List Interface:
Generics
Define datatype to be stored in a collection.
Eg: HashSet<String> set=new HashSet<>();
Normal for loop- Can be used only with List as we need index to iterate.
Advanced for loop – Can be used with List and Set
Iterator interface -Can be used with List and Set
o Eg:
ArrayList<String> names= new ArrayList<>();
Iterator<String> itr=names.getIterator();
While(itr.hasNext() ){
String name=itr.next();
System.out.println(name);
}
NOTE: for Set, method is names.iterator();
forEach() method-Can be used with Set and List.
o Eg:
ArrayList<String> names= new ArrayList<>();
names.forEach( (x)-> System.out.println(x) );
NOTE: forEach() method was introduced in JAVA 8.
Map Interface
It has key value pairs. Key cannot have duplicates. Key and value both must be objects.
It uses get(Object key) and put(key,value) methods.
Its implementations are SortedMap(interface), TreeMap (implements SortedMap),
HashMap, LinkedHashMap,Hashtable.
Comparable Interface
Used for sorting.
Sorting done on single field.
Custom class must implement Comparable interface and override compareTo() method.
To use this, we simply call the sort method on the object of the class which implements
Comparable.
Eg: Collections.sort(employees);
Comparator Interface
Provides multiple choices for comparing.
Custom class must implement Comparator interface and override compare() method.
To use this, we create separate classes for comparisons on various fields (eg
CompareOnEmployeeId, ComparatorOnEmployeeName,etc) and these classes implement
Comparator and each has definition of compare(). While sorting we call sort() and pass 2
parameters- first, the object of the class and second the class whose comparator we want to
use.
Eg: Collections.sort(employees, new EmployeeComparatorOnEmployeeId);
Module: JDBC
Types of statements:
Statement- executes static SQL statements (like select statement without parameters)
Connecting to database:
Establish connection
Statement interface:
Has 2 methods:
JDBC Transactions
By default, a transaction is in auto commit mode.
Commit and rollback
Layered Architecture:
Module: IO API
Java supports 2 types of streams- byte and character. Byte stream for binary data and
character stream for character data.
InputStream and OutputStream are associated with byte streams.
Reader and Writer are associated with character streams.
InputStream
Implements Closeable and AutoCloseable interfaces.
Has methods like read(), read(byte[] buffer), read(byte[] buffer, int offset, int length).
Returns -1 when end of file is reached.
FileInputStream
Output Stream
FileOutputStream
Used to write bytes to a file. It creates a file if it doesn’t exist. Overwrites content if it already
exists.
Eg:
String msg=”hi”;
Fout.write(msg.getBytes());
Fout.flush();
}
Note: FileOutputStream constructor’s second argument is for append mode. Fout.flush() is used to empty the
buffer and ensure all contents are written to file when buffer hasn’t filled completely.
Character Stream
It stores values using UNICODE convention.
It supports internationalization ( can store data in different languages using local scripts
using unicodes).
Reader
FileReader
Writer Stream
FileWriter
Eg:
Fw.fout(System.lineSeparator() );
}
Note: System.lineSeparator() is used to shift cursor to next line.
Chaining Streams
Fields marked as transient are not serialized, static fields can’t be serialized.
Note: It doesn’t make sense to serialize static fields as it is associated with class not instance.
Serialization process
Object -> Serialized by ObjectOutputStream-> Written as bytes using FileOutputStream -> Stored in
memory
Deserialization process
Bytes in memory -> Take bytes using FileInputStream -> Deserialize using ObjectInputStream -> Java
Object
Module: Multithreading
Threads
Threads are lightweight processes.
They share same memory, variables and allocate objects in the same heap.
Multiple threads can run concurrently and each thread has its own stack, local variables, etc.
Note: In a normal Java program, the JVM creates a main thread and runs main() within it.
Creating threads:
Class Main{
Public static void main(String args[]){
MyThread t1=new MyThread();
T1.start();
}
}
Implementing Runnable Interface and implementing run()
Eg:
public class MyThread implements Runnable{
Public void run(){
}
}
Class Main{
Public static void main(String args[]){
Thread t1= new Thread(new MyThread() );
T1.start();
}
}
Start() method of Thread class starts a new thread(with new call stack), thread moves from new to
runnable state and when thread gets chance to execute its run() method will execute.
NOTE: if we directly call run() method instead of start, a new thread will not be created.
Thread Lifecycle:
When a thread is created using new operator, it is in New state.
Once start() is called, it is in Runnable state.
When scheduler picks a thread from runnable pool to execute, it goes in Running state. If
another thread is selected by scheduler before the previous thread completes execution, it
goes into Runnable state again.
A running thread enters Blocked state when –
o Thread.sleep() is called
o Thread calls wait().
o Thread tries to lock an object held by another thread.
o Thread calls an operation which is blocked by IO.
A blocked thread enters Runnable state when –
o It has slept for specified amount of time.
o Another thread calls notify() or notifyAll().
o Object lock is released.
o IO is completed.
A running thread enters Dead state when-
o It completes its execution.
o An exception is thrown but not caught.
Thread priorities
Thread methods
Thread.sleep(long milliseconds) - thread goes into blocked state for that duration.
Public final void join() – it puts current thread on wait till the thread on which it is called is dead.
Public final synchronized void join(long milliseconds) – It is used to wait for the thread on which it is
called to be dead or wait for that time.
Synchronization
Multithreading can lead to inconsistency and to ensure thread safety, we can make use of
synchronization.
It is achieved using locks. We can declare one or more methods to be synchronized.
When a thread tries to execute the method, it must first obtain the lock. If the lock is held by
some other thread, current thread goes into waiting state. Once it gets the lock, it can
execute the method. At a time, only one method will have lock and we can update shared
data safely.
To use synchronization:
o Use synchronized keyword
Public synchronized void add(){
//update shared data
}
o Using synchronized block:
Public void add(){
Int a, b;
Synchronized(this){
//update shared data
}
}
Threads will have to acquire lock to enter the synchronized block.
o Using exclusive lock object
Class Demo{
Object ob=new Object();
Public void add(){
Synchronized(ob){
//update shared data
}
}
The object ob acts as the lock.
Low coupling is achieved using interfaces. Interfaces is used to provide a standard and provides a
level of abstraction that makes programs easy to understand.
There should not be more than one reason for a class to change. Identify different
responsibilities and assign them to different classes.
Advantages: Distinct responsibilities, high cohesion, reduced dependency, improved
reusability
Open/Closed principle:
Many client specific interfaces are better than one general purpose interface.
Avoid fat interfaces, split them.
Advantages: Clients are split through separate interfaces. Low coupling.
Law of Demeter:
It limits the objects you send messages to within a method. In a method, messages should
only be sent to ‘this’ object, parameter of method, attribute of this, object created within
the method.
Advantages: More maintainable as it doesn’t depend on other objects
Design pattern
Reusable solution to commonly occurring problems.
Provides best practices.
Adhere to principle of high cohesion and low coupling.
Singleton Pattern- restricts creation of instances of class to 1.
Factory Pattern- used to hide the name of the actual class whose object is created.
Adapter Pattern- solves problem of 2 objects with incompatible interfaces that need to work
together. Allows client object to be decoupled from adapter object.
Decorator Pattern- allows to add new behavior to an object. Achieved by creating a new
decorator class that wraps the original class’s object.
<tr>
<td><xsl:value-of select="@id"/></td>
<td><xsl:value-of select="first_name"/></td>
<td><xsl:value-of select="last_name"/></td>
<td><xsl:value-of select="salary"/></td>
<td><xsl:value-of select="designation"/></td>
</tr>
Servlet
It is a server side Java module for processing web-based client requests.
It runs in a servlet container under the Application Server(here, Tomcat).
Belongs to only 1 application and can concurrently be accessed by multiple requests.
NOTE: At the server side, there is an application server. It consists of a web container and in it there is a servlet
container. A servlet container can have many servlets within it.
Servlet Lifecycle
Lifecycle is controlled by the Servlet container in which the servlet has been deployed in.
When a request is mapped to a servlet, it performs the following steps:
If an instance of the servlet is not already present, the web container loads the Servlet class.
Creates an instance of the Servlet class. Calls init() method for initialisation.
Calls service() method by passing request, response objects.
If container needs to remove servlet, it calls destroy().
The doGet() and doPost() methods are called by service() as per the type of http method invoked.
Servlet is basically Java which has HTML embedded in it. Basically, it is a .java file.
Basic Servlet:
doGet(), doPost() methods are already available. To write we first need to set Content Type as html
using response object. Next, we need PrintWriter reference and need to get Writer from response
object.
To create a session, we can use request.getSession() and add attributes.
To create Cookie, we need to create a new cookie object and add it to response object.
For applying a filter, we need to provide filter mapping in web.xml file.
To direct to another servlet we use RequestDispatcher by
response.getRequestDispatcher(jsp_page_name) and then call forward method on the reference.
Servlet Context is an interface which communicates with Servlet container. There is only one
ServletContext.
Servlet Config is contains configuration information of a servlet. It can be used to get ServletContext.
Custom tags:
Create a .tld file which the tags and their attributes.
Create a class file which implements TagSupport or SimpleTagSupport
Spring framework
Provides layered architecture.
Uses Inversion of Control concept- Object is not created in the application, it is created externally by
Spring framework.
Dependencies are described in a separate xml file and is not mixed with business logic.
Provides support to other frameworks.
Dependencies should be injected using Constructors or Setters. Piecing together all beans is called
wiring. Wiring can be done in a XML file (Spring bean configuration file).
Using constructor:
Consider there is a Employee class with 2 constructors, Employee(int id) and Employee(String name)
For 1, Employee(int id) is executed. For 2 and 3, Employee(String name) is executed. When type is
not given, by default it goes to String. For 4, both are called.
If the parameter is an object of a class, we use ref instead of value and provide bean name. Eg: If
there is Employee constructor with Address parameter and Address itself is a class,
Here as well, if the setter is for a reference type, use ‘ref’ instead of value.
@Autowired
We can use this annotation to directly assign a bean of the same type in the context.
Eg:
Public class Employee{
@Autowired
Private Addresss address;
}
Context.xml
<bean id=”address” class=”Address”>
<property name=”pin” value=”400014”/>
</bean>
NOTE: if no beans of that type are present, it throws an error. If the injection is not mandatory, we can set
@Autowired(required=false).
@Component
Indicates that the annotated class is a component. We can have @Component(“name”) to specify
name of the component. If nothing is given, it is decapitalized class name.
We need <context:component-scan base-package=”com.accenture.lkm” /> in spring bean
configuration file.
@Qualifier
In case of Autowired, if there are 2 beans of the same type, it will throw an error. To select a specific
bean, we can use @Qualifier(“beanName”) to specify the bean which we want to use.
It is used to consider the corresponding class as a source of bean definition. We use @Bean to
identify a POJO as bean.
Eg:
@Configuration
Public class MyConfig{
@Bean
Public TestBean testBean(){
Return new TestBean();
}
}
Is equivalent to writing
<bean id=”testBean” class=”TestBean”/>
@Lazy
Specifies if the beans have to be initiated lazily. It can be used on the class directly or on methods
annotated with @Bean.
@Controller
Indicates that the class serves as a controller.
It interprets user input and converts it into model object that can be used by view.
It is a stereotype annotation, dispatcher servlet can automically scan for this class. (we need to write
<context:component-scan > for this)
We can also include or exclude packages using <context: include-filter type=”annotation”
expression=”org.aspectj.lang.annotation.Aspect”/>.
@RequestMapping
Used to map URLs to a class or method (usually URLs are of the form “/urlname.htm”. This is a logical
URL, ie it doesn’t have any associated view or JSP page.
Methods with this annotation can have following arguments: HttpServletRequest,
HttpServletResponse, ModelMap, ModelAttribute,BindingResult, Errors.
Methods can have return types ModelAndView, ModelMap,String,ModelAttribute.
DispatcherServlet- Acts as a front controller. Receives HTTP request and forwards it to controller.
Controller- Maps the url to a function and returns ModelAndView.
CommandClass- Class of the object that is used to represent user data. Also called Form Backing Bean.
View Resolver-Customizable view resolution class Application context configuration file.
JSP- Acts as a view (it is not a part of Spring)
NOTE: in web.xml, we have to map Dispatcher servlet to url pattern. Then create an .xml file , name it as
dispatcher-servlet and put bean namespace in it and create beans there.
We can create a bean for InternalResourceViewResolver if we want to keep .jsp files elsewhere and
avoid giving suffix in setViewName().
Form tag
@ModelAttribute
in .jsp page
<td>
<form:select path=”country”>
<form:options item=”${countryList}” itemValue=”Id” itemLabel=”Name”/>
</form:select>
@ModelMap
ModelAndView class uses a ModelMap class that generates a key for every object added to it.
Eg:
Public void loadHome(ModelMap map){
ModelAndView mv= new ModelAndView ();
User user= new User();
Map.addObject(user);
mv.setViewName(“home”);
}
@SessionAttribute
Indicates the session attributes that a class uses. Applies to the model attributes that the annotated
handler class operates on. Attributes are only stored for a conversational session. After session
completes, attributes are removed.
For permanent use, use session.setAttribute().
@ExceptionResolver
Deals with exceptions that occur during controller execution
Used with @ResponseStatus to set a HTTP status code when method is invoked.
And then create a messages.properties file which would map error codes to messages.
In .jsp, we can use <form:errors cssClass=”NameValidator” path=”*”></form:errors> to display all the
errors.
It gives rise to higher coupling, difficulty in maintenance, error prone code. The solution is Aspect
Oriented Programming.
AOP tasks:
Reduces duplicated, tangled, scattered code and dependency between concerns. Modularizes
common code dealing with each concern that is applicable across multiple modules.
Phases of AOP:
Aspectual Decomposition – Identifying core and cross cutting concerns.
Implementation of concerns – Implementing core and cross cutting concerns separately.
Aspectual Recomposition – Weaving individual concerns into core application code based on weaving
rules.
Using Spring AOP, we can create aspects (separate classs) for a cross cutting concern such as logging.
To weave it with business service class, we use @Before and @After annotations.
AOP Terminology
Aspect- It is a well modularised cross cutting concern.
Aspects can have
usage constraint specifications,
extend other aspect, class or interface,
have abstract fields or methods i.e. it can be abstract,
Have java methods, fields.
Join Point
A well defined location or point in the execution of a program.
A point where one or more aspects could be applied.
Join Points can be
method or constructor calls
method or constructor execution
exception handler execution
class/object initialisation: static and dynamic
In Spring AOP, Join Point is always method execution.
Pointcut
It is the selection/collection of Join Points to specify where an advice is to be executed.
Collects context at those Join Points.
Advice
It is the actual code to be executed when the pointcut is triggered. Can be marked before,after or
around the join points in the point cut.
Types:
Before, After returning -executed after join point is completed without throwing exceptions, After
throwing -executed after join point exits by throwing exception , After (finally) – executed after Join
Point exits inspite of exceptions thrown, around – can perform functionality before and/or after the
join point, decides whether to invoke join point.
Weaving
It is linking aspects to other aspects. Weaving can be done at runtime, compile time or load time.
Spring AOP performs weaving at runtime.
Aspects in Spring can be implemented in 2 declarative ways: using regular classes with either
annotated AspectJ or with XML schema based approach. AOP configuration can be done is spring bean
configuration file itself.
@Around(value = "dummy()" )
public Object around(ProceedingJoinPoint pjp) throws Throwable {
Object value=null;
System.out.println("Before execution");
System.out.println(pjp.getSignature());
value=pjp.proceed();
System.out.println("After execution");
System.out.println(pjp.getSignature());
return value;
}
@AfterReturning(value="dummy()", returning="res")
public void afterReturning(JoinPoint jp, Object res)
{
//res is used to store result in log
System.out.println("After returning ans is "+(Integer)res);
Module: Hibernate
Hibernate is an open source object relational mapping (ORM) tool. It provides database query and
retrieval services. It reduces build time on the data layer.
It uses database and configuration file to provide persistence services and runtime reflection to
determine persistent properties of a class.
Hibernate Configuration-
Hibernate acts as a bridge between Object oriented Java application and relational database. Database
details are configured in a hibernate.cfg.xml file. Details on the application’s persistence objects are
provided in the XML file or through annotations.
Configuration Properties-
Include <property> in hibernate.cfg.xml-> programmatic configuration ->pass a java.util.Properties
instance to Configuration.setProperties() -> place config file in classpath
Sample hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<property name="hbm2ddl.auto">update</property>
<property
name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property
name="hibernate.connection.url">jdbc:mysql://localhost:3306/sampledb</property>
<property name="hibernate.connection.username">root</property>
<property
name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">true</property>
<mapping resource="employee.hbm.xml" />
</session-factory>
</hibernate-configuration>
Programmatic configuration
Functions of org.hibernate.cfg.Configuration object are –
Represents complete set of Java types mapping to SQL database
Specifies location of mapping documents and hibernate-specific properties.
Builds an immutable org.hibernate.SessionFactory
<hibernate-mapping>
<class name="com.accenture.lkm.Employee" table="EMPLOYEE">
<id name="id" type="int">
<column name="ID" />
<generator class="assigned" />
</id>
<property name="firstName" type="java.lang.String">
<column name="FIRSTNAME" />
</property>
<property name="lastName" type="java.lang.String">
<column name="LASTNAME" />
</property>
</class>
</hibernate-mapping>
Using annotations:
t.commit();
session.close();
System.out.println("Successfully saved");
Module: JPA
Java Persistence API aalows the programmer to develop persistence layer for their applications.
JPA is developed to ease development of persistence layer and also has standardized Java ORM
technologies.
JPA provides annotation and XML based configuration support. Application developed with JPA is
portable. It works with JEE and JSE applications.
Features of JPA
Standardised OR mapping.
Facilitates POJO based persistence.
Application server is optional(hence, lightweight).
Support for unidirectional and bidirectional relationships.
Entity
It is a lightweight persistence domain object.
Must implement serializable interface.
It represents database table.
It uses annotations to map java fields to database.
Lifecycle-
New/Transient – No persistent identity and not yet associated with persistence context
Managed/Persistent- Associated with persistence context and persistent identity
Detached- Has persistent identity but not associated with persistence context.
Removed- has persistent identity and associated with persistence context but scheduled for removal
from database.
Managing Entities
Entities are managed by EntityManagerFactory and EntityManager.
EntityManagerFactory is a singleton object and represents details of data source. 1 factory for 1 data
source.
EntityManager is instantiated for each connection/transaction. It can perform functions like persist(),
delete(), find().
An EntityManager is associated with a persistence context which defines the scope under which entity
instances are created, persisted and removed. There will be only 1 instance of entity class in a
persistence context.
PersistenceUnit
It contains list of all classes persisted by entity manager. Represented by persistence.xml.
transaction=em.getTransaction();
transaction.begin();
Museum musobj=new Museum();
musobj.setMuseumId("1");
musobj.setMuseumName("Museum Name 1");
musobj.setMuseumType("Historical");
musobj.setBuildingId("B002");
em.persist(musobj);//isme object persist state mein jayega.
transaction.commit();// commit hua hai
System.out.println("Ho gaya finally");
}catch(Exception e) {
System.out.println(e.getMessage());
transaction.rollback();
}finally {
em.close();//detached state mein jayega.
}
}
Possible Mappings are OneToOne, OneToMany, ManyToOne, ManyToMany. JPA mappings are not
bidirectional.
Types of cascade-
CascadeType.PERSIST- when we persist an entity, all entities in this field are also persisited.
CascadeType.REMOVE – when we delete an entity, all entities held in this field are also deleted.
CascadeType.REFRESH- when we refresh an entity, all entities in this field are also refreshed.
CascadeType.MERGE – When we merge an entity, all entities in this field are merged too
CascadeType.ALL- combination of persist,remove,refresh,merge.
JPQL
Java Persistence Query Language defines queries that are independent of the type of database used.
They are written with respect to entities and attributes NOT tablenames and columnnames.
We use Query interface to represent queries in JPA. EntityManager takes care of executing queries
using
createQuery() – for JPQL queries
namedQuery() – to use a named query
nativeQuery() – to use SQL or native language query
Spring framework can be integrated with Hibernate and JPA in terms of resource management, DAO
implementation support and transaction strategies.
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="persistenceUnitName"
value="JPASpringIntegration"></property>
</bean>
<!-- Data source definitions -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"
value="com.mysql.jdbc.Driver"></property>
<property name="url"
value="jdbc:mysql://localhost:3306/sampledb"></property>
<property name="username" value="root"></property>
<property name="password" value=""></property>
</bean>
In JDBC, we have 2 modes for managing transactions, auto-commit and manual-commit mode. Auto-
commit is the default transaction mode. To change we must do connection.setAutoCommit(false).
Transaction Choice
Global transactions-
Managed by application server using Java Transaction API.
Provide ability to work with different transactional resources.
Local transactions-
Are resource specific.
Application server is not involved.
@Transactional
Spring provides support for declarative transactions to POJOs through AOP framework using auto
proxies. Declarative transaction management can be applied to any class or method.
It as following properties-
Propagation level
Isolation level
Read only hints – false by default(all transactions are read/write)
Transaction timeout period
Propogation level defines boundaries of transaction wrt to the client and the method being called.
PROPAGATION_MANDATORY- method must run within a transaction. If existing transaction is in
progress, an exception is thrown.
PROPAGATION_NESTED – method should run in a nested transaction if existing transaction is in
progress. Nested transaction can be comitted and rolled back individually.
PROPAGATION_REQUIRED –
PROPAGATION_NEVER – method should never run in a transactional context. If an existing transaction
is in progress, it throws an exception.
PROPAGATION_NOT_SUPPORTED - method should never run in a transactional context. If an existing
transaction is in progress, it suspends for the duration of the method.
Advantages of AJAX-
Whole page reload is not needed. Only changing content is reloaded.
Reduced traffic between client and server.
Asynchronous request can be sent to server.
No plug-in needed.
Fast.
Flow of AJAX
Event triggers XMLHttpRequest to be created and callback function registered.
Request is sent to server asynchronously.
User continues to proceed.
Response is received and callback function is executed to process response and manipulate HTML
content.
Request.open(“POST”,”home.jsp”,true);
Request.send(“fname=Aish&Lname=Arya”);
Properties of XMLHttpRequest
readyState – contains the state of request (has values 0-4)
onreadystatechange – contains the name of the event handler to be executed when state is ready.
responseText- contains response as a string
responseXML - contains response as XML
status – HTTP code returned by a request (eg: 404,200)
statusText – HTTP response status text (eg: File not found, OK)
methods of XMLHttpRequest
open() – opens a request to the server.
Send()- sends the HTTP request to server
getRequestHeader() – sets the name and value of HTTP header
getResponseHeader() – returns value of HTTP header
getAllResponseHeaders() – returns all HTTP headers
abort() – aborts the HTTP request
Representation
Array – [value1,value2,..,value n]
Object – { “name”:”Aishwarya”, “age”:22}
Value could be string, object, array, true, false, null, number.
Module: Maven