0% found this document useful (0 votes)
3 views

Advanced Java

The document provides an overview of Servlets, including their lifecycle, the role of the Servlet Container, and the differences between various types of Servlets. It also discusses JDBC, including its API, drivers, and transaction management, as well as connection pooling and the advantages of using JSP over Servlets. Key concepts such as cookies, session tracking, and the use of Prepared Statements in JDBC are also outlined.

Uploaded by

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

Advanced Java

The document provides an overview of Servlets, including their lifecycle, the role of the Servlet Container, and the differences between various types of Servlets. It also discusses JDBC, including its API, drivers, and transaction management, as well as connection pooling and the advantages of using JSP over Servlets. Key concepts such as cookies, session tracking, and the use of Prepared Statements in JDBC are also outlined.

Uploaded by

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

Servlet :

- Servlet is a JEE module server side web technology that allows us to


develop “Single Instance Multiple Thread based” server side web
components.
- It allows us to develop dynamic web components having ability to
generate dynamic web pages.

What is work of Servlet Container ?


- It loads servlet class, creates the object , manages the object, call the
life cycle method and destroys the object.

What are servlet packages ?


1. jakarta.servlet
2. jakarta.servlet.http
3. jakarta.servlet.annotation
4. jakarta.servlet.descriptor

web.xml
- also called as deployment descriptor file/configuration file.
- It contains instructions to container and server about various web
component of the web app
- Servlet configuration : passing info about servlet class to tServlet
class. <servlet> and sub tags
- Servlet Mapping : linking incoming request url of browser with servlet
comp.

<servlet-name> : logical name


<servlet-class> : fully qualified name
<url-pattern> : url content that is mappe with servlet class,

What is diff bw Servelt(I) vs GenericServlet(AC) vs HttpServlet(Ac) ?


Servlet :
- It is interface.It contains life.

What is Servlet Lifecycle ?


- It means keeping track of various activities of servlet from birth to
death i.e obj creation to obj destruction . Servlet container manages
the lifecycle.
- 3 lifecycle events will be raised
1. Instantiation Event
a. ServletContianer creates Servlet class obj.
b. init(ServletConfig) method is called.
c. One time executing block so we generally place
initialization logics like creating JDBC con obj.
2. Request Processing event
a. service(ServletRequest req, ServletResponse res ) is
invoked
b. keeps class obj fo request processing
c. repeatedly executing block i.e. for every req SC calls this
method.

3. Destruction Event
a. SC is about to destroy class obj. Also one time executing
block.
b. destroy() is invoked. we place uninitialization logics like
closing streams, closing jdbc.
c. when the webapp is reloaded, undeployed or when the
server is stopped or restarted or crashes.

who creates servlet class object ?


- Servlet Container by using 0-param constructor.

who destroys servlet class object ?


- Servlet Container destroys using its own GC.
Why does SC uses its own GC instead of JDK’S GC ?
- Because JDK’S GC algorithm ie.e mark and sweep algorithm that
means first marks the objects that are not having references then
destroy the object.
- But SC has to destroy all the objects though they are having
references.

What is the Lazy loading (or) when servlet object is created in server?
- On First request made by the web client, the web server creates
objects to the servlet class and calls init() method at same time. This
is also called Lazy loading.
- So, First request will always slow (takes time to create object and call
init() then service() method). 2nd Request onwards only service() will
be called.

Eager Loading/Early loading:--


- On server startup only [before making first request], server creates
object to servlet class and calls init() method also at same time. This
is known as Early/Eager loading of Servlet.
- for this Programmer should provide <load-on-startup> tag with +ve
number. Default value for <load-on-startup> is “-1” (indicates lazy
loading)

ServletConfig:
- It is a memory holds data in key=value format, It is used to pass input
data to initmethod mainly.
- in web.xml file under <servlet> tag write code like
<init-param>
<param-name>mydata</param-name>
<param-value>Hello</param-value>
</init-param>
=>Then server created objects with data like.
=>To read data in init() method code is:-- String val =
config.getInitParameter(“key”); Here <param-name> behaves like key
<param-class> behaves like value

ServletContext:
- It is also called as global memory for all Servlets. =>It will store data
in key = value format both are type String only. =>To get
ServletContext object code is:
- In init() method :using config ServletContext sc =
config.getServletContext(); =>in service() method : using request
ServletContext sc =req.getServletContext(); ****)To store data
globally using web.xml
Syntax is:--
<contex-param>
<param-name>key</param-name> <param-value>val</param-value>
</context-param> ***)To read this, syntax is:--
String val=sc.getInitParammeter(“key”)

What are cookies ?


- Allocates memory at

Two Types :
1. InMemroy Cookies :
a. allocate memory inside browsers memory [ RAM]
b. destroyed onced brwoseer window is closed.
c. suitable for ST
2. Persistent Cookies :
a. Allocate memory in clients machine HDD.
b. will not be deleted
c. suitable for remember me option.
Session Tracking ?
1. Hidden Form Fields :
- No data secrecy . Can have only text data. Not recommneded.
- Syntax :
- <input type=”hidden” name=”hello” value=”world”>
- String s = req.getParameter(“hello”):
2. Http Cookies
- allocate memory at client side no burden on server.
- Persistence cookies maintain expire data
- can add only text contect , can be viewed in browser. can be deleted
in middle fo session.
3. HttpSession with Cookies:
HttpSession object allocates memory in the server and remembers
data across multiple requests during a session.
- can have both text java obj as values
- session creation and invalidation is our control.
- less network traffic
- allocate memory in server
- we must only work with Http Servlet comp
- cookies are deleted form browser then ST FAILS
Syntax :
HttpSession session = new HttpSession();
To create :
session.setAttribute(“name”, “ajay”);
to Remove :
session.removeAttribute(“name”):
to invalidate :
session.invalidate():
4. HttpSession with URL Rewriting
- appednign sessionId to the url that foes tot the browser.
JDBC
What is JDBC ?
- JDBC API will act as mediator between Java Program and Database
software
- JDBC API means classes and interfaces defined in two packages.
1. Java Sql
2. Javax.Sql (Extended)

DriverManager :
● It is a class present in java.sql pkg
● responsible for managing all db objs and to register and
unregister db drivers.
○ DiverManager.registerDriver(driver);
○ DiverManager.unregisterDriver(driver);
● also responsible to establish connection to the db with the help
of driver sw.
○ Connection con = DiverManager.getConnection(..);
Driver :
● without a driver sw we can’t touch db.
● It acts as a bridge bw java app and db.
● responsible for converting ajva calls into db specific calls and vice
versa.
What are types of JDBC Driver ?
1. Type 1 : JDBC ODBC Bridge Driver
2. Type 2 : Native Driver
3. Type 3 : Middleware / Network Protocol Driver
4. Type 4 : All Java Driver /thin driver

Which driver should we use ?


● Type 4 : if our app news only one DB eg.standalone app or small scale
web app
● Type 3 : if our app works with multiple DB. eg large scale webapp or
enterprise

Steps to develop JDBC APP ?


1. Load and Register Driver class.
○ Class.forName(“com.mysql.cj.jdbc.Driver”)
○ DriverManager.registerDriver(driver)
○ static block will be executed internally and registration
happens.
○ From java 1.6v we are not required to load or register driver.
2. Get Connection from DB
○ Connection con = DriverManager.getConnection(url, uname,
pass)
3. Create Statement Object
○ Statement stmt = con.createStatement();
4. Execute the query
○ int rowsaffected = stmt.executeUpdate(INSERT_QUERY)
5. process the result

6. close connection
What is Statement ?

What is Prepared Statement


=> PreparedStatement is used to execute both SELECT & NON-SELECT
Queries.
=> PreparedStatement will support for Positional Parameters ( ? ) in the
Query
=> Postional Parameters are used to supply dynamic values to Query in the
Run time.
=> When we want to execute same query multiple times with different
values then it is highly recommended to use PreparedStatement.

Difference bw statement and prepareStatement ?


statement PreparedStatement

At the time of creating statement At the time of creating ps obj, we


obj , we are not required to provide have to provide sql query
any query. Hence statement obj is compulsory, which will be send to
not associated with any query and db. hence, ps is always associated
we can use it for multiple queries with only one query.

Whenever we are using execute Whenever we are using the execute


method, every time query will be method, every time query won’t be
compiled and executed. compiled, it will only executed.

stmt obj only works for static query ps obj can work for both static and
dynamic queries.

Relatively performance is slow Relatively performance is faster

Best choice when we want to work Best choice when we want to work
with multiple queries. with one querie but required to
execute multiple times.

there maybe chance of sql injection no chance


attack.

Inserting data values & large object Inserting data values & large object
is difficult. is easy[ CLOB & BLOB ]

How many execute methods are there ?


1. executeQuery()
○ used for select query
○ returns ResultSet -> represents a group of records.
2. executeUpdate()
○ used for non select query
○ returns int -> represents no of rows affected
3. execute()
○ If we don't know type of query at the beginning then we use
execute.
a. returns boolean value .
○ true -> select -> ResultSet
○ false-> non select -> int
○ can be used to execute stored procedures.
4. executeBatch()
○ If we want to execute group of SQL queries then we use
executeBatch()

Explain ResultSet
- ResultSet will represent data given by our select query
- ResultSet will maintains cursor to point the rows
- Initially ResultSet cursor will be available before first record
- We need to move RS cursor to next position by calling next ( )
method

Note: By Default ResultSet is FORWARD_DIRECTIONAL

1) TYPE_FORWARD_ONLY ( by default )
2) TYPE_SCROLL_INSENSITIVE

3) TYPE_SCROLL_SENSITIVE

=> INSENSITIVE & SENSITIVE ResultSets are scrollable and Bi-Directional

=> ResuletSet concurrency will represent changes of ResultSet data

1) CONCUR_READ_ONLY

2) CONCUR_UPDATABLE

-> CONCUR_READ_ONLY will allow only read operation on the ResultSet

-> CONCUR_UPDATABLE will allow update operations also on the ResultSet

BatchProcessing:-
This concept is used to execute multiple SQLs at a time, instead of sending
them one by one. It saves only execution time by reducing network calls
between Java Application and Database
For this we use JDBC Batch

Example :
Statement stmt = con.createStatement();

stmt.addBatch("INSERT INTO BOOKS VALUES(106, 'AI',


2800.00)");
stmt.addBatch("INSERT INTO BOOKS VALUES(107, 'ML',
3800.00)");
stmt.addBatch("INSERT INTO BOOKS VALUES(108, 'DS',
4800.00)");

int[] count = stmt.executeBatch();

System.out.println("Records Effected ::" + count.length);

con.close();
What are Transactions in JDBC
Single Unit amount of work is called as Transaction

=> We can execute multiple Queries in single transaction

Note: Every Transaction should follow ACID Properties

Note: When we are performing NON-SELECT OPERATIONS (insert / update/


delete) with Database then Transaction is mandatory.

=> For Select Operations Transaction is optional.

=> When we are performing multiple operations in single transaction then


either all operations should be success or none of the operation should be
success.

Transcation Commit - to save the operation permanently

Transaction Rollback - to undo the operation

=> In JDBC, transaction will be committed by default for every non select
query execution because by default Transaction Auto Commit is true.
con.setAutoCommit ( true ) ; // this is default behaviour of Connection
obj

=> If we want to manage Transactions in JDBC we need to set AutoCommit


as False.

con.setAutoCommit ( false ) ;

Note: When Auto Commit is false, we need to commit the transaction


programmatically to save our operation in database.
Connection Pooling
===================

=> Connection Pooling is the process of getting fixed no.of connections


from database and store them into a pool for re-usability.

=> If we don't use Connection Pooling concept then our project will run into
Connections Exhausted Problem (No connections available to
communicate with db)

=> If we use DriverManager.getConnection ( ) it will give physical


connection with database. It is not at all recommended to use Physical
Connections.

=> Always we need to use Logical Connections to perform DB operations.


To use Logical connections we need to setup Connection Pool.

Note: With the connection pooling we can improve performance of the


application.

We can setup Connection Pool in 2 ways

1) Client Side Connection Pool

Ex: DBCP, C3P0, Hikari etc....

2) Server Managed Connection Pool

Ex: Tomcat, JBoss, WebLogic etc...


JSP
What is Jsp ?
● JSP is the extension of Servlet but it provides more functionalities.
● Container : JSP Container [ Jasper in Tomcat ]

Features of JSP ?
● provides tag based programming and 9 implicit objs
● we can place jsp in public as well as private areas.
● custom tags

How Jsp works ?


● jsp container internally uses servletcontainer and also gives on e jsp
page compiler [JSPC].
● The process of converting jsp into servlet is called as page
compilation.

Why jsp over servleet ?


● servlet req strong knowledge of java
● designing html code in servlet is complicated
● mix up of presentation and business logic
● for every req we have to write service() method manually.

What scripting tags In jsp ?


1. Scriptlet
a. to place java code which goes to jspService() method.
b. we can call method in it but can’t defined new method as java
doesn’t support nested methods.
c. <% %>
2. Expression
a. evaluates given expression and generate the output
b. if used effectively , no need to use out.print()
c. <%= %>
3. Declaration
a. we can place method definition
b. code goes outside of jspService, so we ccan use to place global
variable declaration, inner classes, interfaces defn
c. <%! %>

What are Directive Tags ?


1. Page Directive :
a. gives global instructions to jspc to generate the code
b. importing packagres, autoflash mode, etc
c. <%@ %>
d. Attributes :
i. info
ii. extends
iii. import
iv. session
v. errorPage
vi. isErrorPage
vii. pageEncodign
viii. language
ix. autoflash
x. contentType
2. Include Directive :
a. use to include cod of the destination we b comp
b. persforms code inclusion
c. <%@include file=””%>

3. Taglib Directive :
a. to include jsp tag libraries.
b. <%@taglib %>

What is JSTL :
library that contains readily available jsp tags.

You might also like