Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
49 views

Java Adv

Uploaded by

amanmirzapur07
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views

Java Adv

Uploaded by

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

COLLECTION

:NEED :

int arr[]= new int[5]; //static

Int arr[] ={78,78,9,9};//dynamic

An array is an index collection of fixed number of homogeneous data element.

The main advantage of array is we can represent multiple value with a single variable

Optimize code,reusability.

Limitation of Array

Arrays are fixed in size i.e once we create an array with some size there is no chances of inc or

Declairing the size we need to know about size before creating an array.

➔ We can store only homogenous data


➔ Not implemented on some std data structure. We can’t use ready made methods.
➔ We need to write long logic code explicitly.
➔ To overcome the limitation we should go for collection.//complexity

Collection

➔ Collection are growable in nature i.e based on our requirement we can dec and inc the size
➔ It can hold heterogeneous data.
➔ Implements some std ds.(ready made method support.)

Difffernce b/w

Arrays collection
Only homogeneous hetrogenous
Size fixed growable
Not implemented on some std DS implemented on some std DS
w.r.t m/m not recomended w.r.t m/m recomended
Primitive data type & obj Only obj
What is collection

If we want to represent a group of individual object as a single entity then we should go for collection.

What is collection framework

It defines several classes and interfaces which can be used by a group of individual object as a single entity.

Collection(I)

IN genral it is considered as a root interface of of collection framework. There is no concreate class

Which is inheriting it directly.

Collections collections is an utility class present java.util package to define sevral utility methods

Like searching ,sorting.

collection(i)1.2v

Map

List(i)1.2 set(i)1.2 Queue(c) 1.4

List(I):

0 1 2 3 4 5 6
List is a child interface of collection.

If we want to represent a group a group of individual object as single entity where

Duplicate allowed and insertion order preserved. We can differenciate them on the bases of index.
list(1.2v )

arraylist(1.2v) growable array vector(1.0)DS:resizable and


def cap=10 linked list(1.2v) doble growable
(c*3/2)+1 linked list RANDOM acess(i)->marker i
null* syncyonized
these are interconnected with add
RANDOM ACCESS(I)->marker i
retrival opration best choice best->ins & del in middle duplicate allow,null*,inser pre
->worst choice insertion and del in b/w worst->retrival best for retrival
not syncyonized def cap=10-> inc =2*cc

stack(1.0)v
child of
vector(LIFO)

ArrayList

• growable array(DS)
• def cap=10
• (c*3/2)+1
• null*
• implementing RANDOM ACCESS(I)->marker
• present in java.util.
• retrival opration best choice
• ->worst choice insertion and del in b/w
• not syncyonized
ArrayList a1 = new ArrayList();

import java.util.*;
class Arraydemo{
public static void main(String[] args) {
ArrayList al = new ArrayList<>();
al.add(13);
al.add(67);
al.add("gras");
al.add(null);
System.out.println(al);//[13, 67, gras, null]

}
}

Note: we can use collection to hold and transfer objects from one place to another

To provide support to this requirement every collection implements

Serializable and clonable interface.

import java.io.Serializable;
import java.util.*;
class Arraydemo{
public static void main(String[] args) {
ArrayList al = new ArrayList<>();
LinkedList l1 = new LinkedList<>();
System.out.println(al instanceof Serializable);
System.out.println(l1 instanceof Serializable);
System.out.println(al instanceof RandomAccess);//array list
System.out.println(l1 instanceof RandomAccess);

}
}

ArrayList Vector
Not synchronized synchronized
Performance high Performance low
1.2v() 1.0v(legacy classes)

ArrayList a1 = new ArrayList();


Public static List synchronizedList(l1);

List l1=Collections. synchronizedList(a1);


data
10
LinkedList : aa
➔ The underlying DS is double linked list.
➔ Insertion order is preserved s
➔ Duplicate allowed
➔ Heterogeneous allowed
➔ Null possible.
➔ Implements clonable and serizable
➔ Not impl reamdom access.
➔ Best choice insertion del in b/w
➔ Worst choice for retrival operation.

import java.util.*;
class Arraydemo{
public static void main(String[] args) {
LinkedList l1 = new LinkedList<>();
l1.add(123);
l1.add("sonali");
l1.add(56);
l1.addFirst("first");
l1.remove(2);
l1.add(2, "middle");
System.out.println(l1);

ArrayList LinkedList
Best choice retrieval Worst choice for retrieval
Wrost choice ins/del in b/w best choice ins/del in b/w
growable Doubly linked list
Random access implements Does not implement Random access

Vector

The underlying datastructure is resizable or growable array.

Duplicates are allowed

Insertion order preserved

Null insertion is possible

Implement random access,colnable,serializable

Synchronized.

Legacy class.(1.0)->re-engineered class

Def capacity =10 …………. C*2;

import java.util.*;
class Arraydemo{
public static void main(String[] args) {
Vector v1 =new Vector<>();
System.out.println(v1.capacity());
for(int i=1;i<=21;i++){
v1.add(i);

}
System.out.println(v1);
System.out.println(v1.capacity());
}
}
Stack :

Child class of vector.

LIFO

Stack s1 = new Stack();

import java.util.*;
class Arraydemo{
public static void main(String[] args) {
Stack s1 = new Stack<>();
s1.push("a");
s1.push("b");
s1.push("c");
s1.push("d");
s1.push(34);
System.out.println(s1.pop());
System.out.println(s1);
System.out.println(s1.search("c"));
System.out.println(s1.search("abc"));//-1
System.out.println(s1);
}
}

import java.util.*;
class Arraydemo{
public static void main(String[] args) {
Stack s1 = new Stack<>();
s1.push("a");
s1.push("b");
s1.push("c");
s1.push("d");
s1.push(34);
System.out.println(s1);//[a, b, c, d, 34]
System.out.println(s1.peek());//34
System.out.println(s1);//[a, b, c, d, 34]
}
}
Arrays->single variable->multiple value

NEED OF collections: growable,hetro,homor,datastrust

1. Arrays and Collection->primitive are not allowed im collection and obj in both

2.collection = if we want to rep a group of obj as a single entity---→

* collections = it is a utility class present java.util pack to define sevral utility method like sort ,searching

* collections framework= It defines sevral class and interface which can be used by these group…………

List-> child(I) of collection[duplicate allowed,insertion pres] -→serilizable and coloneable I impl

Set->child (i) of collection[dup no,inser not pres]

Queue-> child (i) of collection prior to processing

Difference= arraylist and vector

Difference b/w ArrayList and LinkList

How to get syncronized version in AL

List l1 = collections.SyncronizedList(al);
list(1.2v)

arraylist(1.2v) growable array


def cap=10 vector(1.0)DS:resizable and growable
(c*3/2)+1 linked list(1.2v) doble linked list RANDOM acess(i)->marker i
null* these are interconnected with add syncyonized
RANDOM ACCESS(I)->marker i best->ins & del in middle duplicate allow,null*,inser pre
retrival opration best choice worst->retrival best for retrival
->worst choice insertion and del in b/w def cap=10-> inc =2*cc
not syncyonized

stack(1.0)v
child of vector(LIFO)

Three cursors of java:

If we want to retrive obj one by one from collection …….


Enumeration Iterator ListIterator
• for any collection obj. • It is not universal
• enumeration(1.0) • both read & remove cursor(powerful)
• public bolean • 1.public boolean • Move in both dirtion
hasMoreElement() hasnext() • Add,remove,replacement
• public Object • 2.public Object next()
nextElement() • 3public void.remove() public Listiterator listiterator();
ListIterator i1 = lobj.listiterator();
public enumeration elements(); public Iterator iterator();
Enumeration e1= V1.element(); Iterator i1 = cobj.iterator();
----------------------------------- Limitation:
Limitation : only for legacy Only move in forward direction
classes,read operation only… Only read & remove ……no
not other operation. replacement operation

Enumeration

import java.util.*;
class enumer{
public static void main(String[] args) {
Vector v1 = new Vector<>();
for(int i=0;i<=10;i++){
v1.addElement(i);
}
System.out.println(v1);

Enumeration e1 = v1.elements();
while(e1.hasMoreElements()){
Integer i1 = (Integer)e1.nextElement();
System.out.println(i1);
}

Set Interface

If we want to represent a group of individual object as a single entity where duplicates

Are not allowed and insertion order is not preserved.


Set(i)1.2v

HashSet(1.2) SortedSet(1.2)

LinkedHashset(1.4) NavigableSet(1.6)

Treeset(1.2)

HashSet

• The underlying data structure is Hashtable.


• Dulplicates are not allowed if you will try insert you will get false.
• Insertion order is not preserved coz data will be inserted on the basis of hashcode.
• Null possible
• Hash set is the best choice for search operation.
• Filling ratio 0.75
HashSet h1 = new HashSet();

import java.util.*;
class enumer{
public static void main(String[] args) {
HashSet h1 = new HashSet<>();
h1.add("neha");
h1.add("sonali");
h1.add(6);
h1.add("neha");
h1.add(89);
h1.add(null);

System.out.println( h1.add("neha"));
System.out.println(h1);//[sonali, null, neha, 6, 89]

}
}
LinkedHashSet

The underlying datastructure is HashTable + Linked List (that is hybrid data structure).
Insertion order preserved.
Introduced 1.4v
(rest same hashset)

import java.util.*;
class set1{
public static void main(String arg[]){

LinkedHashSet lh = new LinkedHashSet<>();


lh.add("neha");

lh.add("smriti");
lh.add("anamika");
System.out.println(lh.add("neha"));
System.out.println(lh);

}
}

Sorted Set(i)

It is the child interface of set.


If we want to represent a group of individual object represent as a single entity where duplicates are not
allowed and objects will be inserted in according to sorting order.

TreeSet
• The underlying data structure for tree set is Balanced tree.
• Duplicates object are not allowed.
• Insertion order is not preserved but elements are inserted according to some sorting tech.
• If you try to insert heterogeneous element you will get class cast exception.
• Null insertion is not possible .//null pointer exception.

Comparable(i)

Default natural sorting

Present in java.lang package.

It contains method public int compareTo(Object ob);

Ex-: obj.compareTo(obj1) [10,0,15,20,20,]

10
Returns –ve if obj1 has to come before obj2

Returns +v if obj1 has to come after obj2

Returns 0 if obj1 and obj2 are same. 0 15

20

Comparator(i)

Present in java.util package


It has two methods equals() and compare()
Public int compare(obj 1 ,obj2)

import java.util.*;
class set1{
public static void main(String arg[]){

TreeSet t1 = new TreeSet<>(new customized());


t1.add(152);
t1.add(67);
t1.add(889);
t1.add(123);
System.out.println(t1);
}
}

class customized implements Comparator{

public int compare (Object ob1,Object ob2){


Integer i1 = (Integer)ob1;
Integer i2 = (Integer)ob2;

if(i1>i2){
return -1;
}
else if (i1<i2) {
return +1;
}
else{
return 0;
}

String comparison sorting

import java.util.*;
class set1{
public static void main(String arg[]){

TreeSet t1 = new TreeSet<>(new customized());


t1.add("yash");
t1.add("anamika");
t1.add("neha");
t1.add("divya");
System.out.println(t1);
}
}

class customized implements Comparator{

public int compare (Object ob1,Object ob2){


String i1 = (String)ob1;
String i2 = (String)ob2;
int q1 = i1.length();
int q2 = i2.length();

if(q1>q2){
return -1;
}
else if (q1<q2) {
return +1;
}
else{
int a = i1.compareTo(i2);
return a;
}

}
Comaparable and comparator mei difference

Map

HashMap IdentityHashMap WeakHashMap SortedHashMap

LinkedHashMap NavigableMap

TreeMap

Map
• Map is not child interface of collection.
• If we want to represent a group of object as a key value pair then
We should go for Map.
Both keys and value are object…duplicates key not allowed…value can be duplicate
Key and value pair is known as entry
Hence it is known as collection of entry object.

Obj.put(“key”,”value”);

Collection Views of map

1. Set keyset();
2. Collection values();
3. Set entrySet();

Entry (i)
It is a pair of key and value which is known as entry s0,map is a
Collection of entry object there is no use of map without entry.

Interface Map{
Interface Entry{

Object getkey()
Object getValue()
Object setvalue(obj)}}

HashMAP (1.2)
• The underlying DS is Hashtable.
• Insertion order is not preserved bcz of hashcode
• Dup key not allow.,value can be duplicate
• Null is allowed as key but only once(value any time)
• HashMap h1 = new HashMap();
• Best choice for searching operation

import java.util.*;
class A{
public static void main(String[] args) {
HashMap m1 = new HashMap<>();
m1.put("sonali", 700);
m1.put("prerna", 800);
m1.put("neha", 567);
m1.put("anushaka", 600);
System.out.println( m1.put("sonali", 7800));//returing 700
System.out.println(m1);
//{sonali=700, anushaka=600, shivi=7800, neha=567, prerna=800}
Set s1 =m1.keySet();
System.out.println(s1);

//fetching value only


Collection c1 = m1.values();
System.out.println(c1);
//use of entry set
Set s2 = m1.entrySet();
System.out.println(s2);

Iterator i1 = s2.iterator();
while (i1.hasNext()) {
Map.Entry ME = (Map.Entry)i1.next();
System.out.println(ME.getKey()+" "+ME.getValue());

}
}
}

LinkedHashMap (1.4)
It is child class of HashMap including method of HashMap.
Data Structure underlying LinkedList and HashTable(Hybrid)
Insertion order is preservrd.
import java.util.*;
class map{
public static void main(String[] args) {
LinkedHashMap l1 = new LinkedHashMap<>();
l1.put(12, "neetu");
l1.put(13, "kriti");
l1.put(14, "deepika");
System.out.println(l1);
}
}

IdentityHashMap
It is same as hashMap including methods of constructor except following
difference.
1. ==(ref) 2. equals(content)
In the case of normal hashMap jvm will use .equals method for
comparison but in case of identityHashMap comparison on the basis of
==
import java.util.*;
class A{
public static void main(String[] args) {
IdentityHashMap h1 = new IdentityHashMap<>();
Integer i1 =new Integer(8);
Integer i2 =new Integer(8);

h1.put(i1, "sonali");
h1.put(i2, "smiriti");

System.out.println(h1); //{8=sonali, 8=smiriti} //comapring on th basis ref(==)

WeakHashMap
It is exactly same as Hashmap except
In the case of HashMap even though object does ‘t have any ref .it is not
eligible for garbage collection.HashMap dominates the GC
But in case of
In the case of WeakHashMap even though object have any ref .it is
eligible for garbage collection.Gc dominates the WeakHashMap
SortedMap
It is the child interface Map if we want to represent a group of key-value
According to some sorting order then we should go for SortedMap
Sorting will be on the bases of key.
Sorted MAP defines following metods{102,112,123,144,567}
firstKey(),lastKey(),
headMap(123) ----(102,112),
tailMap(123)=---(123,144,567),
submap(112,567)->(112,123,144)

TreeMap
The Underlying data structure is red black tree.(insertion order on some
sorting)
WHETER we are depending on DNS or CS there is no restriction of value
But the key should homogeneous.
(after 1.7 v null inserton is not possible in single time)
import java.util.*;
class A{
public static void main(String[] args) {
TreeMap t1 = new TreeMap<>();
t1.put(56, "sana");
t1.put(6, "sonali");
t1.put(26, "anamika");
t1.put(13, "sandhya");

System.out.println(t1);
}
}

MYSQL : Basically it use to accessing and manipulating the


database.(Oracle)
MySQL is a relational database management system
MySQL is open-source
MySQL is free
MySQL is ideal for both small and large applications
MySQL is very fast, reliable, scalable, and easy to use
MySQL is cross-platform
MySQL is compliant with the ANSI SQL standard
MySQL was first released in 1995
MySQL is developed, distributed, and supported by Oracle Corporation
MySQL is named after co-founder Monty Widenius's daughter

MYSQL DATABASE

Basic Commands ->insert,delete,where………………….


Key-> unique key, primary ke………………………………….
Join->inner joiner,outer join …………………………………..
MySQL
Commands

DDL DML TCL DQL

DDL : Data definition language (Create ,Drop,Alter,Truncate)

DML : Data Manipulation Language (insert,update,delete)

TCL :Transcation Control Language (commit,rollbacak)

DQL: Data query language (select)

Basic Commands

1. show databases;
2. use grastech;
3. create table eskill (id integer ,name varchar(50),psw varchar(50),city varchar(50));
4. select * from eskill;
5. select name from eskil;
6. select city from eskill where psw="45@p";
7. select * from eskill;
8. alter table eskill add column mobile_no integer;
9. update eskill set mobile_no=897966789;
10. select * from eskill order by name;
11. select * from eskill where name like '_i%';
12. select * from eskill where city in('delhi','meerut');
13. insert into eskill
values(4,"neetu","425@p","goa"),(5,"neha","78@p","meerut"),(6,"nancy","89@p","gurugram");
14. select * from eskill where id between 1 and 3;
15. select distinct * from eskill;
16. select max(id) from eskill;
17. truncate table eskill;//deletes data
18. drop table eskill;//deletes table

Dtabase Constraints : are used to limit the type of data that can store in table.

1. not null constraint


2. unique key constraint
3. primary key constraint
4. composite key constraint
5. check constraint
6. foreign key constraint
7. default constraint

not null : The not null constraint enforces a column to not to accept null values.

Is always contains value.

Unique : The unique constraint uniquely identifies each record in database table.

We have many unique key constraint as per table .

Primary key : The primary key constraint uniquely identifies each record in db

It should not have null values and single table a single primary key.

Check : The check constraint limit the value range that can be placed in a column.

Default : The default constraint is used to insert a default value into a column if no

Value will be specified.

Foreign key : The foreign key is used to link one or more than one table together

Means a foreign key in one table refers to the primary key field in another table.

Composite key : combination of two column.


Foreign Key

Composite key :
MYSQL
JOINS

inner join self join outer join cross join

Left outer Right outer


join join

Inner Join : The inner join keyword selects the records that have matching values in both

Table.

T1 T2

Left Join : The left join keyword return all records from the left table and matching records from right table.

Right Join : The Right join keyword return all records from the right table and matching records from left table.
Self join : A single table will join itself…..
JDBC :JAVA DATABASE CONNECTIVITY
1.Java standard edition(j2ee/jse) JDBC[standalone]
2.Java Enterprise edition(j2ee/jee)sevlet/jsp)[web
application]
3.Java micro edition(j2me/jme)[mobile application]

Menu
JDBC Store(Database)
(student.html)

Kitchen

(servlet):processing

Table(result.html)
JDBC : JDBC is a technology which can be used to
communicate with database from java application.

JAVA Application JDBC DATABASE

JDBC is a part of jse.


JDBC is specification defined by java vendor and
implementation by database vendor(Driver s/w).
Most of the jdbc driver are developed in java. We can
work on any platform independently.
We can easily do crud (create
,read,update,delete)operation.
Diff b/w JDBC and ODBC
ODBC JDBC
Open database Java database connectivity
connectivity
1992 by microsoft 1997 by sun microsystem
C,c++,java Only java
Windows only Any platform
Driver in native lang Driver dev in java
Platform dependent Mostly independent.

JDBC API:
1. JDBC API provides several classes and interfaces.
2. Programmer can use these classes and interface
to communicate with database.
3. Driver s/w vendor can use these JDBC API while
Developing the driver s/w.
JDBC API CONTAIN 2 package
Java.sql.package Javax.sql.package
It contains basic class and It contains more
interface for database advanced class and
connectivity. interface for database
connectivity.
INTERFACES:===== INTERFACE:
Driver,Connection, Datasource,Rowset.
Statement,PreparedStatement
CallableStament,Result Set
Classes:== DriverManger,Date

Types of Driver

While communicating with database ,we have to


convert java calls into database specific calls and
Database specific calls to java calls for this Driver
s/w required.

Type-1 Driver
Also known as JDBC-ODBC bridge driver.
1. This driver provided by sun microsystem as part of jdk(after 1.8 not supported)
2. Internally it will take support of ODBC driver to communicate with database
3. Type-1 Driver converts JDBC calls into ODBC calls ODBC driver converts the ODBC calls into Database specific
calls.
4. Slowest driver and for windows(not portable) only (thick)

DB

Type -2 Driver (Native API Partly java Driver)

1. It is same as type -1 driver only ODBC driver replace with Database Specific native lib.(written non java c,c++)
2. We have to install vendor provided native lib on client machine.
3. Type-2 Driver converts JDBC calls into native api partially calls native api partially calls are directly
understandable by db.
4. Portable.(driver platform dependent)

Property TYPE-1 TYPE-2 TYPE-3 TYPE-4


conversion JDBC-ODBC JDBC-NATIVE LIB JDBC-MIDLEWARE JDBC-DB
Implementation ONLY JAVA NATIVE LANG ONLY JAVA ONLY JAVA
Architecture 2-TIER 2-TIER 3-TIER 2-TIER
PLATEFORM IDEPEN N0 NO YES YES
DB INDEPENDENT YES NO YES NO
THIN OR THICK THICK THICK THICK THIN
KNOWN AS BRIDGE-DRIVER NATIVE-DRIVER MIDDLEWARE- PURE-THIN DRIVER
DRIVER
Steps to Prepare JDBC APPLICATION

✓ Load and Register Driver forName()->Class.forName(“driver name”);


✓ Establish connection b/w java application and DB
✓ ----Connection c1=DriverManger.getConnection();
✓ Create either statement or prepared Statement or callable statement.
✓ Public statement createstatement();=Statement st= c1.createstatement()

✓ Write and execute sql queries.

✓ 1.execute ,2.executeupdate , 3.executeQuery


✓ Close connection.

Difference between execute(),executeQuery(),executeUpdate().

1. executeQuery : If we know the type of the query at the beginning and it is always select
query then we should go for executeQuery() method.
Eg: ResultSet rs=st.executequery(“select * from student”);//DQL

2. executeUpdate : If we know the type of the query at the beginning and it always non-select
query then we should go for executeUpdate() method.
Eg: int rowcount=st.executeUpdate(“insert into student values(1,”gras”);//DML
3. execute() : If we don’t know the type of query at the beginning and it is available dynamically

at runtime (may be from properties file or from command prompt ) then we should go for

execute() method.

Boolean b = st.execute(“//dynamic input”) ;

If(b==true)//select query{

ResultSet rs = st.getResultSet();
while (rs.next()) {
System.out.println(rs.getInt(1)+"\t"+rs.getString(2));
}
else{
}
int rowcount= st.getUpdateCount();
System.out.println("The no of row affected"+rowcount);
}
PreparedStatement : It is a Precompiled Query. Because at the beginning associated with query.

Pst.executeQuery()//just execution …..compilation already done.

Difference b/w Statement and PreparedStatement.

Statement PreparedStatement
If 100 times execute then 100 times compile. 100 time execute but compile only once.
Req + compile + execution + Result Req + execution + Result
At the time of creating statement we don’t provide At the time of creating statement we provide query.
query.
Inserting large data is difficult. Inserting large data is easy.

Callable Statement : To call the stored procedure in database we use callable statement.
Statement(I)

PreparedSatement (I)

CallableStatement(I)

Meta Data Introduction :

1. Database MetaData
2. ResultSet MetaData
3. Parameter MetaData

Metadata about database is nothing but database product name database version.
Metadata about resultSet means no of columns each column name and column type.
Metadata is defined as the information that describes and explains data. It provides context with details
such as the source, type, owner, and relationships to other data sets. So, it can help you understand the
relevance of a particular data set and guide you on how to use it. In a nutshell: Metadata is a cornerstone of
a modern enterprise data stack.

DataBaseMetaData(I) :
It is an interface present in java.sql package driver s/w vendor is responsible to provide the implementation.

We can get DatabaseMeta object by using get MetaData() method of connection.

Public DatabaseMetaData getMetaData();

Eg: DatabaseMetaData dbmd = con.getMetaData();

We can call following methods.


• getDatabaseProductName()
• getDatabaseProductVersion()
• getMaxColumsinTable()
• getDriverName()
• getURL()

ResultSetMetaData(I) :
Java.sql package contains extra info about ResultSet.

ResultSetMetaData rsmd = rs.getMetaData();

rsmd.getColumnCount();

rsmd.getColumnName(int i);

rsmd.getColumnType(int i);

rsmd.getTableName(int i);

ParameterMetaData(I):
When you want to get extra info about Positional Parameter.

ParameterMetaData pst = con.PrepareStatement(“insert into emp values(?,?,?,?));

ParameterData psmd = pst.getParameterMetaData();

Psmd.getParameterCount();

Psmd.getParameterType();
Servlet
Servlet is a web technology which is used to develop web-Application.

Web is basically a system of internet server that supports specially formatted documents.
REQUEST

Client
SERVER

RESPONSE

HTTP : is a protocol that clients and server use on the web to communicate.[Stateless]
HTTP Request : Is a packet of information that send by the client to server.
HTTP Response : Is a packet of information that send by the server to client.

Difference b/w HTTP get & HTTP post


HTTP GET HTTP POST
Data is sent in header Data is sent in body.
Limited data can send Large amount of data can be send
Not secure It is secure

It creates Web Application provides interfaces and classes .Must be implemented to create servlet.
It can responds to any incoming request .Deployed to create web pages.
It is Robust and Scalable.
.

Loading and Instant ion

START Init()

Initialized

Service()

Handling Request

destroy()

END
STOP

General Technical Term

• Web Server : Is a application used to receives the request from web browser and process with help of

Web container.

. Web Container: Is use manage the life cycle of servlet.

➔ Web Client : is used to send the request to the server.


➔ HTTP:
➔ TCP/IP : top of all the protocol and used for data transmission.
➔ DNS : is a registry binded with IP address.

Life Cycle Of Servlet

1. Servlet class is loaded


The class loader is responsible to load the servlet class. The servlet class is loaded when the first req for the
The servlet is received by web container.

2. Servlet Instance is created:


The web container creates the instance of a servlet class loaded .The instance will be created only once in a life
cycle.
3. Init():
Web container invokes the init() only once and creates the instance use to initialize the servlet.
4. Service():
The service method is the main method perform actual task. The web container calls the service method()
To handle the req from the client and perform operation and send it back to client.
5. Destroy():
At last completing the task destroy method will be called.

Servlet Config :

• For servlet web container creates one config obj.


• Servlet obj will be created at the time of sevlet obj creation and destroy at the time servlet destruction.
• Web container hand over the config object to the intit parameter.

ServletConfig config = getServletConfig();

Request Dispatcher in Servlet (I)

The RequestDispatcher interface provides the facility of dispatching the request to another resource[jsp/html/servlet].

And also used to include the content from another context.

1. Public void forward(ServletRequest req,ServletResponse res);


2. Public void include(ServletRequest req,ServletResponse res); Forward
Servlet-2
Forward
Servlet-1
Request

Client

Response

RESPONSE
Include()
INCLUDE() : SERVLET- SERVLET-
1 2

CLIENT

RESPONSE RESPONSE

SpringBoot
1.Introduction to SpringBoot :
What is spring Boot

Makes it easy to create


spring-powered production
grade app.

Take an opionionated view


of the spring platform
SPRING
BOOT

used to create stand alone


java application

Features of SpringBoot
1.Spring CLI : SpringBoot CLI allows you to groovy for writing springBoot
Application and avoids boilerplate code.
3. Spring Initializer :
This is basically a web application, which can create an internal project structure.

4. Spring Actuator :

The feature provides help while running springBoot Application

5. Starter dependency : with the help of this feature springboot aggregates common dependencies together

eventually improves productivity.

6. Auto-Configuration :

The auto-configuration feature of springboot helps in loading the default configuration according

to the project you are working.

7. Logging and Security

this feature
of springBoot ,ensures that all the application made using
spring boot are secure.

Why we need springBoot


• Stability
• Connectivity
• Flexibility
• Open source
Spring SpringBoot
Takes time to running springapp Shortest way to run spring
Application
Manage life cycle of java Need not to worry about
configuring a datasource.
Dependency injection framework Pre-configured set of framework
Model View Controller

It is a java framework which is used to build web application


It follows the Model-View –Controller design pattern.

Not just that it is also implements all the basic features of a


Core spring framework link dependency injection.

Model View and Controller

It is a java framework which is used to build web application,


It follows model-view-controller design pattern.
(include+ dependency injection).
Web-
browser

model model

Front-
controller

Model : A model contains the data of the application .


A data can be single object or a collection obj.

Controller : A controller contains the business logic.

View: A view represent info in form in particular


format(HTML,jsp).
Frontcontroller : DispatcherServlet class works as front
controller.it is responsible to mangae the flow of MVC

Request Dispatcher servlet controller

Model & view

View(html/jsp)
Response

You might also like