100% found this document useful (1 vote)
5K views

Stream Training Notes Java

The document provides information on several Java 8 features and concepts: - Default methods and static methods in interfaces allow adding new functionality while maintaining backward compatibility. Lambda expressions support functional programming by allowing code to be passed as arguments. - Exception handling involves checked and unchecked exceptions, try/catch/finally blocks, and custom exceptions. - The Collections framework includes interfaces like Collection, Set, List, and Map. Common implementations are ArrayList, LinkedList, HashSet, TreeSet, and HashMap. Collections allow storing and iterating over objects.

Uploaded by

Niket
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
5K views

Stream Training Notes Java

The document provides information on several Java 8 features and concepts: - Default methods and static methods in interfaces allow adding new functionality while maintaining backward compatibility. Lambda expressions support functional programming by allowing code to be passed as arguments. - Exception handling involves checked and unchecked exceptions, try/catch/finally blocks, and custom exceptions. - The Collections framework includes interfaces like Collection, Set, List, and Map. Common implementations are ArrayList, LinkedList, HashSet, TreeSet, and HashMap. Collections allow storing and iterating over objects.

Uploaded by

Niket
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 37

Stream training notes

Module: Java 8 Features – Interfaces and Lambda

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

Static methods in Interfaces:


 Same as default methods except static methods can’t be overridden in subclass.
 Have a body in the interface itself.

Anonymous inner classes (NOT A FEATURE OF JAVA 8)


 We can declare and instantiate a class at the same time.
 Don’t have a name.
 We use anonymous classes if they are to be used only once.
 Eg:

Public interface Greeting{

Public void print();

Class Welcome{

Greeting greetingObject= new Greeting(){

//method definitions

//instance variable declarations

Public void print(){

System.out.println(“This is a method in anonymous class”);

}; }
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”);};

Check slide 20 for all possible scenarios of syntax.

Module: Exception Handling

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

Catch multiple exceptions in a single block


 The Exception classes should be at same level (eg: we cannot have ClassNotFoundException
and Exception as Exception is superclass)
 Catch(ClassNotFoundException | IOException e){}

Finally block
 Finally block is executed when we exit try block. It is used to release resources(eg close
connections).

Try with resources block

 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

Size Variable Fixed

Element type Objects Primitives or Objects

Performance Slower Faster

Memory utilization Better as size can be Bad


adjusted
Ease of coding Easy Difficult

Collections Framework Hierarchy

Collection Interface:
 No direct implementation is provided. Has sub interfaces Set, List and Queue.
Set Interface:

 Cannot have duplicates.


 Has 4 subclasses: SortedSet, TreeSet, HashSet, LinkedHashSet.

 HashSet Class- allows null. Doesn’t maintain insertion order.


 LinkedHashSet Class- allows null. Maintains insertion order.
 TreeSet Class- Doesn’t allow null. Entries are sorted.
 SortedSet Interface- Elements are ordered. Doesn’t allow null.

List Interface:

 Can have duplicate values.


 Maintains insertion order.
 Has 3 implementations: ArrayList, LinkedList, Vector.

 ArrayList class- Resizable- array implementation, not thread safe.


 LinkedList class- Doubly linked list implementation
 Vector class- Resizable- array implementation, Thread safe.
NOTE: ArrayList is slower than LinkedList as it uses array implementation. ArrayList is better for storing and
accessing data while LinkedList is better for manipulations.

Generics
 Define datatype to be stored in a collection.
 Eg: HashSet<String> set=new HashSet<>();

Iterating through elements in a collection-

 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.

 HashMap class- allows null, doesn’t guarantee insertion order.


 LinkedHashMap class – allows null, guarantees insertion order.
 Hashtable class- Doesn’t allow null, thread safe.
 TreeMap class- key cannot be null,Entries are sorted as per key.

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

JDBC has 2 packages: java.sql, javax.sql

Types of statements:
Statement- executes static SQL statements (like select statement without parameters)

PreparedStatement- SQL statement is precompiled. It takes in different parameters for different


times of execution.

Callable Statement – Used to execute SQL stored procedures.

JDBC Driver- used to connect to database.


Types :

Connecting to database:
Establish connection
Statement interface:

Has 2 methods:

Prepared Statement interface:

Note: ? are called placeholders.

All DML statements use executeUpdate() method.

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

 It is used to read input bytes from a file


 Eg:
Try (FileInputStream file= new FileInputStream(file_path) ){
Int ch;
While( (ch=file.next) != -1 ){
System.out.println( (char) ch );
}
}

Output Stream

 Implements Flushable, Closeable and AutoCloseable interfaces.


 Has methods like write(), write( byte[] buffer), write ( byte[] buffer, int offset, int length).

FileOutputStream

 Used to write bytes to a file. It creates a file if it doesn’t exist. Overwrites content if it already
exists.

 Eg:

Try ( FileOutputStream fout= new FileOutputStream(file_path, true) ){

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

 It has read() methods same as InputStream.

FileReader

 Reads character data from input stream to a file.


 Eg:
Try (FileReader fr= new FileReader(file_name) ){
Int ch;
While( (ch=file.next) != -1 ){
System.out.println( (char) ch );
}
}

Writer Stream

 Implements Appendable, Flushable, Closeable interface.


 Has methods like write() like OutputStream.

FileWriter

Eg:

Try ( FileWriter Fw= new FileWriter(file_name, true); ){

Fw.fout(System.lineSeparator() );

Fw.fout(“This is written to file”);

}
Note: System.lineSeparator() is used to shift cursor to next line.

Chaining Streams

Java File ->BufferedOutputStream->FileOutputStream->Text

Text-> FileInputStream-> BufferedInputStream


Serialization
 It is the process of converting object into a stream of bytes and storing it in IO or database or
send it across a network.
 Deserialization is the process of converting an object from its serialized state to original
state.
 ObjectInputStream and ObjectOutputStream supports reading and writing of objects as
stream of bytes. The object to be serialized must implement Serializable interface.
Note: Serializable is a marker interface.

 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

Note: .dat is a generic data file.

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:

 Extending Thread class and overriding run()


Eg: public class MyThread extends Thread{
Public void run(){
}
}

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

 We can assign MAX_PRIORITY(10) or MIN_PRIORITY(1) priority to a thread using


ThreadObj.setPriority(int value). NORM_PRIORITY is 5.

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.

Inter Thread communication


 It is used for communicating between synchronized threads.
 It is implemented by using methods of Object class-
o Wait() – it causes the thread to release the lock and go into the blocked state till
another thread calls notify() or notifyAll() or for a specified time.
o Notify()- wakes up a single thread that is waiting on this object’s monitor.
o notifyAll()- wakes up all threads that are waiting on this thread’s monitor.

Module: Reuse OOP PD

Principles of Object Oriented Design


 Cohesion- How closely methods are related in a class. High cohesion increases reusability of
class.
 Coupling- How closely each program relies on other modules. Coupling should be as low as
possible. It helps to achieve maintainability.

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.

Single Responsibility Principle:

 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:

 Entities should be open for extension but closed for modification.


 Key is to use abstraction in designing classes.
 Advantages: Existing code is not affected, Extension points are well defined

Liskov Substitution Principle:

 Subtypes must be substitutable for types(parents).


 Key is to have well designed inheritance hierarchies.
 Advantages: Client need not know the implementation, it can work with interface. Promotes
Design By Contract approach. Ensures consistent behavior between base and derived class.

Dependency Inversion Principle:

 Abstraction shouldn’t depend on details. Details must depend on abstractions.


 Key is to define appropriate interfaces or abstract classes and provide implementation in
derived classes. User refers to interface not implementation class for functionality.
 Advantages: Loosely coupled, flexible.

Interface Segregation 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.

Module: XML and XSLT


XSLT can take data from XML file and display it in a browser. We have to link the .xsl file to .xml file
using <?xml-stylesheet type=”text/xsl” href=”path/file.xsl”?>. In XSL, we can use <xsl:for-each
select=”employees/employee”>

<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>

Id was attribute so we use @.

Module: Servlets and JSP

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.

JSP Java Server Page


It consists of Java coded embedded in HTML content.
Scripting elements are
JSP Scriptlet(to write Java code) <% … %>
JSP Declaration (to declare variables or methods like Java) <%! ..%>
JSP Expression <%=…%> (don’t write semicolon)
JSP Comment <%! …%>
JSP directive <%@ .. %>

Most common directives are page, taglib, include.

Custom tags:
Create a .tld file which the tags and their attributes.
Create a class file which implements TagSupport or SimpleTagSupport

Finally use it in jsp page.


<%@ taglib uri=”path of .tld file” prefix=”sample_prefix”%>
<sample_prefix:helloTag color=”blue” > text </sample_prefix>

Module: Spring Introduction

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.

Spring Framework Components:


Spring Core- consists of essential functionality. A primary component is BeanFactory, which applies
Inversion of Control concept.
Spring Context-It is a configuration file that provides contextual information to the Spring
framework.
Spring AOP- Integrates Aspect Oriented Programming with Spring. Provides transaction management
services for any object managed by Spring. We can incorporate declarative transaction
management.
SpringDAO- Provides meaningful exception hierarchy for to handle exceptions and error messages.
Simplifies error handling and reduces amount of code to be written.
Spring ORM- Provides Object Relational Mapping using Hibernate.
Spring Web Module- Provides context for web based applications.
Spring MVC Framework- MVC implementation for building web applications.

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)

In Spring beans configuration file,


1. <bean id=”empid” class=”com.accenture.lkm.Employee”>
<constructor-args value=”123” type=”int”/>
</bean>

2. <bean id=”empname” class=”com.accenture.lkm.Employee”>


<constructor-args value=”123” type=”String”/>
</bean>

3. <bean id=”empname” class=”com.accenture.lkm.Employee”>


<constructor-args value=”123”/>
</bean>

4. <bean id=”empname” class=”com.accenture.lkm.Employee”>


<constructor-args value=”123” type=”String”/>
<constructor-args value=”123” type=”int”/>
</bean>

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,

<bean id=”addr” class=”com.accenture.lkm.Address”><constructor-args value=”Street”/>


<constructor-args value=”400014”/></bean>
<bean id=”empname” class=”com.accenture.lkm.Employee”>
<constructor-args ref=”addr”/>
</bean>

Using setter methods

For Employee with 2 instance variables name and id,

<bean id=”empname” class=”com.accenture.lkm.Employee”>


<property name=”name” value=”abc”/>
<property name=”id” value=”132”/>
</bean>

Here as well, if the setter is for a reference type, use ‘ref’ instead of value.

To get a bean in the main(),

ApplicationContext context=new ClassPathXmlApplicationContext(“context.xml”);

Module: Spring Core Annotations

@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>

<bean id=”employee” class=”Employee” >


// no need to set property, as address is autowired, it gets the bean which has the same TYPE.
(AUTOWIRED.byType).

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.

@Configuration and @Bean

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”/>

We can use @Import(ClassName.class) to import beans in some other configuration class.


If we have multiple beans of the same type in our configuration, we use @Primary to set which is to
be chosen is @Autowired is written.

NOTE:For @Primary to work, component-scan must be written.

@Lazy

Specifies if the beans have to be initiated lazily. It can be used on the class directly or on methods
annotated with @Bean.

Module: Spring MVC

@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.

Spring MVC Components

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().

Module: Spring Form

Form tag

To use form tag we have to use taglib


<%@ taglib prefix=”form” uri=https://springframework.org/tags/form%>
It renders an HTML form tag and exposes a binding path to inner tags for binding.
It puts command object on PageContext so that command object can be accessed by inner tags.
The <input type=”text” name=”firstName”> is replaced by <form:input path=”firstName”>.

@ModelAttribute

It can be used for 2 cases-


To inject data objects before a view loads i.e. to preload data. This ensures the page has data required
to display itself (eg: to display course list, we need to preload the list of courses).
To read data from the model and passing on to the parameters of the handler method.
Eg: in .java file
@ModelAttribute(“countryList”)
Public List<Country> getList(){
List<Country> countries = new ArrayList<Country>();
Country c=new Country();
c.setId(1);
c.setName(“India”);
countries.add(c);
c.setId(2);
c.setName(“China”);
countries.add(c);
return countries;

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.

Module: Spring Form Validation

Spring supports validation with Validator Interface.


It has 2 functions:
Boolean supports(Class<?> class)- It returns true or false depending on whether validator can perform
validation on this class.
Void validate(Object target, Errors errors)- performs actual validation. Errors should be reported by
adding it to errors object.

In order to validate a form,


Provide implementation of Validator interface.
Override validate().
Create object of this class in controller.
Call invokevalidator() from controller.

To view errors, first we need to create a bean as follows:


<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource"
>
<property name="basename" value="/WEB-INF/messages"></property>
</bean>

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.

Annotation Based Validations

We can use @Null, @Email, @Size(min=2,max=10), @Length(max=10),@Max, @Min, @NotBlank.


To use these, we need to insert bean in servlet.xml file:
Module: Spring AOP

Core concern- core business logic


Cross cutting concerns – concerns that cannot be clearly distinguished from other concerns in
OOP.Not core concern but still needed. Eg: Exception handling, logging,security, caching, transaction
management.

Problems in OOP are :


There is code scattering and code duplication.
Same concern used in many places.
Eg: for logging, logger statements are executed at the start and end of every method. It becomes boiler
plate code.

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.

Join Point context information can be accessed by using methods:


getThis() – returns currently executing object that has been intercepted.
getArgs() – returns parameters of the method at Join Point.
getSignature() – returns signature of the method at Join Point.
getTarget() – returns target object of the execution (advised object)

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.

Target Object / Advised Object


The object on which aspect or set of aspects can be applied. In Spring, this object will always be a
proxy object.

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.

To create an Aspect class, use @Aspect.


Eg:
@Aspect
@Component
public class MyAspect {

@Before(value= "execution (* *.add*(..))")


public void beforeAddition(JoinPoint jp) {
System.out.println("This happens before execution");
System.out.println("method "+jp.getSignature().getName());
}

@After(value= "execution (* *.addTwo(..))")


public void afterAddition(JoinPoint jp) {
System.out.println("After addition");
System.out.println("method "+ jp.getSignature());
}

@Pointcut(value = "execution (* *.sub*(..))")


public void dummy() {

@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.

Three main components of Hibernate architecture are:


Connection Management Service
Transaction Management Service
Object Relational Mapping

It uses database and configuration file to provide persistence services and runtime reflection to
determine persistent properties of a class.

Two approaches to hibernate architecture-


Lite – has to provide own JDBC connections and manage transactions. It provides only ORM.
Full cream – provides all 3

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>

Hibernate Data Source properties


Hibernate.connection.dataSource - datasource Java Naming and Directory Interface
Hibernate.jndi.url - URL for JNDI provider
Hibernate.jndi.class – class of the JNDI InitialContextFactory
Hibernate.connection.username – database username
Hibernate.connection.password – respective password

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

There are two approaches to specify mapping files:


Configuration cfg= new Configuration().addResource(“User.hbm.xml”);
Configuration cfg= new Configuration().addClass(com.accenture.lkm.User.class);

A persistent object is a POJO.


The POJO must implement the marker interface java.io.Serializable.
It should have an identifier property(primary key).
It should have a no argument constructor.
It should have getter and setter for all instance variables.

Hibernate Mapping Files(classname.hbm.xml)


Providing necessary information of class.
Generate database schema.
Create java source file.

<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:

Sample program using hibernate


public class StoreData {

public static void main(String[] args) {


// TODO Auto-generated method stub
Configuration cfg=new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory factory=cfg.buildSessionFactory();
Session session=factory.openSession();
Transaction t=session.beginTransaction();
Employee e1=new Employee();// transient
e1.setId(114);
e1.setFirstName("yash");
e1.setLastName("uhcdsjk");
session.persist(e1);//persist

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 is a specification, we need JPA implementation. Hibernate is an implementation of JPA.


Java Persistence consists of 3 areas, JPA, Query language, ORM metadata.

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.

Sample program using JPA


public class CreateMuseumJPA {

public static void main(String[] args) {


// TODO Auto-generated method stub
EntityManagerFactory
emf=Persistence.createEntityManagerFactory("JPA");
EntityManager em=emf.createEntityManager();
EntityTransaction transaction=null;
try {

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.

}
}

Module: JPA Mapping

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

The methods used to retrieve results can be-


Query.getResultList() – returns a List
Query.getSingleResult() – returns an object having a single row of result

For update queries, we create query using createQuery(),


Query query= em.createQuery(“ update course c set c.coursefee= ?1 where c.coursename=?2”);
Query.setParameter(1,100);
Query.setParameter(2,”English”);

Int result= query.executeUpdate();

Returns integer value

Sample for OneToMany mapping, NamedQuery


@Entity
@NamedQuery(name="findAllMuseumsWithName", query="select m from Museum m where
m.museumName like :mn")
//yeh namedQuery hai
// yeh JPA ka query hai. This query is written on object. RDBMS knowledge not
necessary.
public class Museum implements Serializable {
private static final long serialVersionUID=1L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int museumId;
private String museumName;
private String museumType;
private String buildingId;
@OneToMany(targetEntity=Event.class,cascade=CascadeType.ALL)
@JoinColumn(name="museumId")
private Set<Event> events;
//getters and setters
}

Module: Spring with JPA

Spring framework can be integrated with Hibernate and JPA in terms of resource management, DAO
implementation support and transaction strategies.

It can be done by 2 ways:


Coding DAO against plain Hibernate APIs.
Using Spring DAO’s templates.
In both cases, DAOs can be configured through dependency injection and participate in Spring’s
resource and transaction management.

Benefits of using Spring with JPA


Ease of testing
Common data access exceptions.
General resource management.
Integrated transaction management.

Spring JPA offers support to Java Persistence API.


It gives 3 ways of setting up JPA EnitityManagerFactory-
 LocalEntityManagerFactoryBean using persistence unit.
o LocalEntityManagerFactoryBean creates an EntityManagerFactory useful for
environments which only use JPA for data access. It needs only persistence unit name
to be specified.
o It is the simplest and most limited form of JPA deployment. There is no way to link an
existing data source or support global transactions.
 Obtaiining EntityManagerFactory from JNDI.
o Use this option when deploying to Java EE 5 server.
 LocalContainerEntityManagerFactoryBean using custom data sources (most powerful setup
option).
o We need to set property data source to our custom data source in context.xml.
<context:component-scan base-
package="com.accenture.lkm"></context:component-scan>
<bean id="entityManagerFactory"

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>

Module: Spring/JPA Transaction Management

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).

Spring Transaction Management


Provides flexible and powerful layer for transaction management.
Provides consistent programming model across different transaction APIs.
Hides differences between local and global transactions.
Choice of demarcation strategy and transaction manager are independent. For any transaction
manager, declarative and programmatic transaction work well.
If transaction manager is changed, only configuration files are updated.
Spring provides implementation of transaction managers for HibernateTransactionManager and
JPATransactionManager.

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.

Using Spring JPA transactions


It uses JPATransactionManager
<tx:annotation-driven/>
<bean id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="dataSource" ref="dataSource" ></property>
<property name="entityManagerFactory" ref="entityManagerFactory"></property>
</bean>

@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.

Trasaction semantics can be defined


Declaratively – by using <tx:attributes> in a configuration file
Programmatically – by creating an instance of DefaultTransactionDefinition that implements
TransactionDefinition and sets properties.
Module: AJAX

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.

Create instance of XMLHttpRequest.


Request= new XMLHttpRequest();

Create request by using the open(method,url,[async]) method


Request.open(“GET”,”home.jsp”,true);

Send request to server by using send()


Request.open(“GET”,”home.jsp”,true);
Request.send();

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

data interchange can be done using XML or JSON.


JSON (JavaScript Object Notation)
Lightweight format.
Uses JavaScript objects to transfer data.
Platform independent.
Build on 2 structures – collection of name/value pair, ordered list of values

Representation
Array – [value1,value2,..,value n]
Object – { “name”:”Aishwarya”, “age”:22}
Value could be string, object, array, true, false, null, number.

Module: Maven

You might also like