advance java ebook(jdbc+servlet+jsp)_PISBMS03
advance java ebook(jdbc+servlet+jsp)_PISBMS03
Here
JSP:-JSP stands for Java server page and which is response from web
application to client.
JDBC
->Before understand about JDBC let understand about storage first.
Field Storage:-Field Storage are related to our variable and this memory is generated to
hold single data value and this is also a temporary storage in program. All primitive
datatype variables are nothing but field storage only.
Note:- both Field Storage and Object Storage are temporary storage because these
storage will be destroyed automatically when JVM shutdown.
o File Storage
o Database Storage
File Storage:- It is a Storage which is managed by operating System and it is
recommended for Files storage Not for Web application Data ,
->File Storage is ok for local files and data but if we talk about any web
application perspective then there is lot of limitation due to which we are
unable to use File Storage for web application.
Data Redundancy:-
Atomicity Problem:
->Any operation on database must be atomic , which means it must
happen entirely or not at all. It is possible in database but in file storage
atomicity is impossible.
Multiple-access
->In database multiple users are allowed to access data at same time
simultaneously means they can perform reading /writing operation same
time which is not possible in File Storage.
Security
->as compared to File Storage Security is very high in database .
Database Storage
->database is the permanent storage which is installed into computer.which is
used to store data of web application (client details,application details..etc).
->There are lots of database available in market like Mysql,Oracle..etc.
->In database we can store data in well organized format which make easy to
insert and fetch data from it.
->it solves all the data storage issue present in File Storage.
->lets talk about JAVA application.
Developer can use any database its depends on there requirement. So when we want to
establish communication between database like(Mysql,Oracle..etc) then java app must
be developed with such Classes and Interfaces that which helps to establish
communication between java application and database.
->java need to take help of “java.sql” package and need support of JDBC driver.
Driver:-
->JDBC driver is a software it enable java application to interact with
database.
->Type-1 driver having more number of conversions and consumes more execution
time and degrades the performance.
-> we need to install Microsoft provided ODBC native library in our Machine.
->more conversion happens like Java to ODBC and from ODBC to database native.
-> In Type-2 driver,the Client Machine is installed with DataBase related Libraries these
Libraries will Support Type-2 driver to convert JDBC calls into DataBase Specific calls for
connection.
DisAdvantage:
->In Type-2 driver the Application will become DataBase dependent application.
->We can use Type-4 driver for any kind of Java application development.
->it is Fast.
->here JDBC calls are converted into database specific calls directly.
->if you have not downloaded Oracle database software then first download
it.
->as you download Database we need its database jar file support to connect
with that database.
Etc.
To know port no and service name of oracle open ‘tnsnames.ora’ file present
inside oracle folder .
(b)prepareStatement()
(c)prepareCall()
(d)setAutoCommit()
(e)getAutoCommit()
(f)commit()
(g)rollback()
(h)setSavepoint()
(i)releaseSavepoint()
(j)close()
->as we discuss ‘Connection’ is an interface and we also know that we can’t create
object for Interface .
java.lang.String,java.lang.String)throws java.sql.SQLException;
Types of Statements in JDBC:
=>Statements in JDBC are categorized into three types:
o 1.Statement
o 2.PreparedStatement
o 3.CallableStatement
Above three statements contains various method which helps us to deal with
database queries. Let see some imp methods.
Statement:
->'Statement' is an interface from java.sql package and which is used to
execute normal queries like create , insert , reterive (select), update and
delete by providing some method support.
o executeQuery()
o executeUpdate()
o execute()
executeQuery():
->executeQuery() method is used to execute ‘select’ queries.
executeUpdate()
-> executeUpdate() method is used to execute Non-Select queries like
Create,Insert,Update and Delete.
Execute()
->execute() method can be used to execute any kind of sql statements ‘select’
as well as ‘non-select’.
Step3:- add Database –jar libarary to our java project in our case (ojdbc).
Our db table
-> ResultSet is an interface from java.sql package and which holds the result
of 'select' query.
(ii)getInt()
(iii)getFloat()
(iv)getLong()
(v)next()
next() method:
PreparedStatement:
-> PreparedStatement is an interface from java.sql package and which is
parameterized queries).
(i)executeQuery()
(ii)executeUpdate()
ResultSet rs = ps.executeQuery();
executeUpdate():
CallableStatement:
->'CallableStatement' is an interface from java.sql package and which is used
to execute 'Procedures and Functions' on DataBase product.
define Procedure?
->to execute procedure and function we will use execute() method. This
method is available in PreparedStatement only. internally CallableStatement
inherits PreparedStatemnt so it is available in it also.
create or replace procedure Proc_name
(para_list) is
begin
query1;
query2;
...
end;
/
define Function?
Note:Functions in SQL will use 'return' statement to return the value after execution.
structure of Function:
begin
query1;
query2;
....
return var;
end;
/
Types of Procedures:
=>The Procedures which take the data from JavaPrograms and update DataBase tables
are known as 'IN Parameter Procedures'.
=>The Procedures which take the data from DB Tables and send to the Java Programs
are known as 'OUT Parameter Procedures'.
ex
define registerOutParameter() method?
->registerOutParameter() method specify the type of data recorded in
Parameter-Index-fields and registerOutParameter() method is available
from 'CallableStatement'.
C-Consistency
I-Isolation
D-Durability:
A-Atomicity
=>The process of Commiting the Transaction after completing all the
"SubStatements execution",is known as Automicity.
Note:
C-Consistency
=>The resources which are selected for Transaction will be same until the
transaction is completed is known as Consistency.
I-Isolation
->To deal with the transcation management we use the following methods
from ‘java.sql.Connection’ interface .
o setAutoCommit()
o getAutoCommit()
o commit()
o rollback()
o setSavepoint()
o releaseSavepoint()
setAutoCommit():- actually java application will perform commit operation
automatically . so by using this method we can set it to false.
Rollback():-we use rollback() method to get original state of buffer when the
transcation failed. We specify the rollback operation using savepoint.
->In connection pooling the users take connection from the pool and uses
that connection to perform some operations and return connection to the
pool.
(a)addBatch()
(b)executeBatch()
(c)clearBatch()
1) addBatch():
=>This method is used to add the query to the batch.
Method Signature:
syntax:
stm.addBatch("query");
2) executeBatch():
syntax:
3) clearBatch():
syntax:
stm.clearBatch();
Batch Processing using 'PreparedStatement'
(b)executeBatch() - Statement
(c)clearBatch() - Statement
Note:
ResultSet
->based on Control over the cursor, the ResultSet Object are
Categorized into two types.
o Non-Scrollable ResultSet Object.
o Scrollable ResultSet Object.
Non-Scrolable ResultSet Object:-
->In this non-scrollable resultset Object the cursor is moved only in
One direction, which means the cursor moves from top-of the table
data to bottom-of the table data.(Top-Bottom)
Scrollable ResultSet Object:-
->In Scrollable ResultSet Object the cursor can be moved in two
directions , which means top to bottom of the table data and bottom
to top table data.
Note:-we use scrollable resultSet with statement & prepared
statement.
Ex:-
Ex:-Statement stm = con.createStatement(type,mode);
Ex:-PreparedStatement ps = con.prepareStatement("query",type,mode);
Ex:-
Type:
public static final int TYPE_FORWARD_ONLY=1003
Mode:
public static final int CONCUR_READ_ONLY=1007
Note:
'type' specifies the direction of the cursor and 'mode' specifies the
action to be performed(read or update).
The following are some Methods used to control cursor on Scrollable
ResultSet object:
Web Applications:
2. JSP Container.(Jasper)
File->new ->dynamic web project and click on next->name the project and finish.
->go to tomcat folder (in my case it is installed in c drive) and select Lib folder inside that
select servlet-api.jar file.
Note:- while adding
servlet-api.jar file .
please take care that if
you are getting option of
class path inside libraries
then you need to select
class path and add there
.in my case no classpath
inside libraries so using
directly
Now we have added servlet api in our project we are ready to create servlet
program.
Step4:- Now we need to add Tomcat server to Eclipse IDE because servlet is
a server side program to execute it we need server environment .
->select console and choose server option and click on given blue link.
Select tomcat9
->above diagram is explaning every thing.this big box is web container means as we run
our program web container came into picture. Inside webcontainer lots of object are
created few are most important to understand.
ServletContext:
ServletConfig:
=>This ServletRequest object will hold the data submitted from HTML forms.
ServletResponse:
PrintWriter pw = res.getWriter();
setContentType() method ?
res.setContentType("text/html");
->now create servlet program which accept request came from this form submittion.
As off now we have created one servlet program by implementing Servlet. Means by
using ‘javax.servlet.Servlet’ interface. But this interface is not preferable because the
objects are Not-Serializable which means Object cannot travel over network.
GenericServlet program..
RequestDispatcher
->RequestDispatcher is an interface from ‘javax.servlet’ package and which
provides the following methods to establish communication b/w servlet
programs.
Methods of requestDispatcher.
o forward()
o Include()
Note:- RequestDispatcher is an interface which means we cannot create it’s object .
Syn:-
->The second servlet can also be replaced with JSP file or HTML file.
syn
RequestDispatcher rd = req.getRequestDispatcher("html/jsp/servlet");
rd.forward(req, res);
Include Communication process:
->in simple words in include communication process the response is
generated from FirstServlet , but the generated response is added with the
response of secondServlet .
syntax:
rd.include(req,res);
Ex_Application:(Demonstrating forward() and include() methods)
->
ServletContext:
->ServletContext is an interface from javax.servlet package and which is
instantiated automatically when application is deployed.
->there is only one ServletContext object per web application.
->if any information is shared in many serrvlet then servlet context is better
place.
ServletContext object.
ServletConfig:
=>ServletConfig is an interface from 'javax.servlet' package and which is
Servlet program.
ServletConfig sc = this.getServletConfig();
syntax:
wt is the diff b/w
o (i)getParameter()
o (ii)getInitParameter()
object.
o setAttribute()
o getAttribute()
o removeAttribute()
setAttribute():- this method is used to set data (attribute) to the objects like
instead of web.xml.
Task:- create one web application includes database and complete flow.
HttpServlet
->HttpServlet is an abstract class from ‘javax.servlet.http’ package.
This is protocol dependent (HTTP protocol dependent).
->as we know we have Servlet,GenericServlet and now HttpServlet
..so like wise others we need to extend our servlet with HttpServlet .
->HttpServlet provides method like doPost() , doGet()..etc.
define request?
POST request:
->The request which is used to post(send) the data to the Server is known as POST
request. The Post request is generated by declaring method=”POST” on form tag.
syntax:
</form>
-> Through POST request we can send any type of data (Text,Audio,Video,Image and
Animation) and UnLimited data.
-> The data which is sent through the POST request is secured.
GET request:
->The request which is used to get the data from the Server is known as GET request.
syntax:
....
</form>
Exp:
http://localhost:8082/codemines/abc
<form action="url">
</form>
Note:
->Through GET request we can send only text data and we can send only limited data
upto few kb.(Based on Browser).
-> The data which is sent through the GET request is NotSecured because which is
attached to the query-string and display in the address bar.
Session Tracking /session management
->session tracking is a way to maintain state(data) of an user . in simple word
process of tracking the status of user from login to logout is know as session
tracking.
->following are the techniques used in session tracking.
o URL Re-writing.
o Hidden Form Fields
o Cookie (imp)
o HttpSession (imp)
->session tracking technique are used to send the information from one
servlet to another servlet in the process of Tracking users.
Url Re-Writing :
=>The process of adding parameter-values to the url-pattern is known as
Syn
url-pattern?para1_name=value¶2_name=value¶3_name=value&...
ex
input.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="firstServlet" method="post">
UserName:<input type="text" name="uname"><br>
MailId:<input type="text" name="mid"><br>
PhoneNo:<input type="text" name="phno"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
@WebServlet("/firstservlet")
@Override
IOException{
PrintWriter pw = res.getWriter();
res.setContentType("text/html");
pw.println
("<a href='secondservlet?uname="+uName+"&mid="+mId+"&phno="+
phNo+"'>ViewInfo</a>");
}
@WebServlet("/secondservlet")
@Override
IOException{
PrintWriter pw = res.getWriter();
res.setContentType("text/html");
pw.println("UserName:"+req.getParameter("uname"));
pw.println("<br>MailId:"+req.getParameter("mid"));
pw.println("<br>PhoneNo:"+req.getParameter("phno"));}}
Hidden Form fields:
->The process of declaring <input type="hidden"> in form tag of HTML is known as
Hidden Form Field.
->The data in Hidden form fields are not displayed to the End-Users.Using these Hidden
form fields we can send information from one Servlet to another Servlet.
input.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="firstservlet" method="post">
UserName:<input type="text" name="uname"><br>
MailId:<input type="text" name="mid"><br>
PhoneNo:<input type="text" name="phno"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
@WebServlet("/firstservlet")
IOException{
PrintWriter pw = res.getWriter();
res.setContentType("text/html");
pw.println
pw.println("</form>");
@WebServlet("/secondservlet")
IOException{
PrintWriter pw = res.getWriter();
res.setContentType("text/html");
pw.println("UserName:"+req.getParameter("uname"));
pw.println("<br>MailId:"+req.getParameter("mid"));
pw.println("<br>PhoneNo:"+req.getParameter("phno"));
Cookie
->The small piece of information available b/w multiple client request is know as
‘Cookie’.
res.addCookie(ck);
NOTE:- This addCookie() method is available from 'HttpServletResponse'.
step-3 : Get cookies from the request object using getCookies() method
Cookie c[] = req.getCookie();
ex:-
HttpSession:
->HttpSession is an interface from javax.servlet.http package and which is used to
transfer the information from one Servlet to another Servlet .
Note:
syntax-1:
HttpSession hs = req.getSession( );
=>In this syntax it checks the session object is available or not,
syntax-2:
HttpSession hs = req.getSession(false);
=>In this syntax it checks the session object is available or not,
=>this method is having parameter flase. Means it will help to get session which is already available and if not
available then it will create new one.
Every session will have SessionID. And Session ID is a unique number, server assigns to a specific user,
during his visit(session). And defaultely, session ID is attached to a cookie and this cookie will be shared
from client to server (and server to client) during its requests/responses. And server will identify session
based on session id which is retrieved from cookie.
2.FilterChain
3.FilterConfig
1. Filter:
o Init()
o doFilter
o destroy
2. FilterChain:
Note:
=>The Filter program is mapped using Annotation or web.xml
@WebFilter("/url-pattern")
<filter>
<init-param>
</init-param>
</filter>
<filter-mapping>
</filter-mapping>
</web-app>
Servlet Collaboration process?
->in simple process of exchanging information b/w Servlet programs is know as Servlet
Collaboration process.
o Using ‘RequestDispatcher’
o Using ‘sendRedirect() ‘ method.
(a) using 'RequestDispatcher':
Communication process:
->in this web application are executed in same webserver or different webserver.
syntax:
ex
Note:- server make use of browser and redirect to that URL.
Note:-When we use RequestDispatcher the same Old request is
forwarded to next Servlet Program in communication process.
Note:-When we use sendRedirect() method then app1 will take help
of browser and generate new request to app2.
Some important Annotations in Servlet Programming:
(i) @WebServlet
(ii) @WebFilter
(iii) @WebListener
Servlet Life-cycle
->in real life also every one have there life cycle which means from starting stage to end
stage. Similarly Servlet life-Cycle defines different state of Servlet program from Starting
to Ending of Servlet Program.
o Loading process
o Instantiation process
o Initialization process
o Request handling process
o Destroying process.
1. Loading Process:- process of identifying the servlet program based on URL-pattern
and loading in WebContainer is know as Loading Process.
GenericServlet:
(i)init()
(ii)service()
(iii)destroy()
HttpServlet:
(i)init()
(ii)doPost()/doGet()
(iii)destroy()
Filter:
(i)init()
(ii)doFilter()
(iii)destroy()
3. Initialization Process:- process making the programming component ready which can
be used by following methods like service(),doPost(),doGet(),doFilter().
Note:
->service() method is executed for all the multiple requests generated from Multiple
users.
5. Destroying process:
JSP Programming:(Part-3)
->JSP stands for ‘Java Server Page’ and which is response from web-
application.
->JSP is tag based programming language and which is more easy when
compared to Servlet Programming.
->in more simple words you can say JSP program are combination of both
HTML code and JAVA code.
->JSP provides various tags to write java code part of JSP program.
1. Scripting tags
o Scriptlet tag
o Expression tag
o Declarative tag
2. Directive tags
o Page
o Include
o Taglib
3. Action tags
o Jsp:include
o Jsp:forward
o Jsp:param
o Jsp:useBean
o Jsp:setProperty
o Jsp:getProperty
1. Scripting tags
->it is used to write java code as part of JSP program.
->Scriptlet tag is used to write normal Java Code part of JSP programs.
syntax:
->Expression tag is used to assign the value to variable or which is used to display the
data to the WebBrowser.
syntax:
syntax:
2. Directive tags:
-> The tags which are used to specify the directions in translation process are known as
Directive Tags.
(a) page:
->'page' directive tag specifies the translator to add the related attribute to current JSP
page.
syntax:
List of attributes:
1.import
2.contentType
3.extends
4. info
5.buffer
6.language
7.isELIgnored
8. isThreadSafe
9. autoFlush
10.session
11.pageEncoding
12.errorPage
13.isErrorPage
(b) include:
->'include' directive tag specifies the file to be included to current JSP page.
syntax:
Exp:
(c) taglib:
->'taglib' directive tag specifies to add specified url to current JSP page and which is used
part of EL(Expression Lang) and JSTL (JSP Standard Tag Lib).
syntax:
Ex:-
The following are the implicit objects generated in JSP programming:
1. application - javax.servlet.ServletContext
2. config - javax.servlet.ServletConfig
3. request - javax.servlet.http.HttpServletRequest
4. response - javax.servlet.http.HttpServletResponse
5. out - javax.servlet.jsp.JspWriter
6. session - javax.servlet.http.HttpSession
7. exception - java.lang.Throwable
8. page - java.lang.Object
9. pageContext - javax.servlet.jsp.PageContext
3. Action tags:
->Action Tags are used to include some basic actions like inserting some other page
resources ,forwarding the request to another page, creating or locating the JavaBean
instances and,setting and retriving the bean properties in JSP pages.
Note:
2.<jsp:forward>
3.<jsp:param>
4.<jsp:useBean>
5.<jsp:setProperty>
6.<jsp:getProperty>
1. <jsp:include> :
->This action tag allows to include a static or dynamic resource such as HTML or JSP
specified by a URL to be included in the current JSP while processing request.
-If the resource is static then its content is included in the JSP page.
->If the resource is dynamic then its result is included in the JSP page.
page : Takes a relative URL,which locates the resource to be included in the JSP page.
<jsp:include page="/Header.html"/>
<jsp:include page="<%=mypath%>"/>
2. <jsp:forward>:
-> This action tag forwards a JSP request to another resource and which can be either
static or dynamic.
->If the resource is dynamic then we can use a jsp:param tag to pass name and value of
the parameter to the resource.
Exp:
<jsp:forward page="/Header.html"/>
<jsp:forward page="<%=mypath%>"/>
3. <jsp:param>:
->This action tag is used to hold the parameter with value and which is to be forwarded
to the next resource.
4. <jsp:useBean>:
=>This tag is used to instantiate a JavaBean,or locate an existing bean instance and
assign it to a variable name(id).
syntax:
<jsp:useBean attributes>
</jsp:useBean>
(a)id
(b)scope
(c)class
(d) beanName
(e)type
(a) id:
->which represents the variable name assigned to id attribute of <jsp:useBean> tag and
which holds the reference of JavaBean instance.
(b) scope:
=>which specifies the scope in which the bean instance has to be created or located.
scope can be the following:
(i)page scope : within the JSP page,until the page sends response.
(ii)request scope : JSP page processing the same request until a JSP sends response.
(e) type :
->The "type" attribute takes a qualified className or interfaceName, which can be the
classname given in the class or beanName attribute or its super type.
5. <jsp:setProperty>:
->This action tag sets the value of a property in a bean, using the bean's setter methods.
Types of attributes:
(a)name
(b)property
(c)value
(d)param
(a) name:
->The name attribute takes the name of already existing bean as a reference variable to
invoke the setter method.
(b) property:
->which specifies the property name that has to be set,and specifies the setter method
that has to be invoked.
(c) value:
->The value attribute takes the value that has to be set to the specified bean property.
(d) param:
->which specify the name of the request parameter whose value to be assigned to bean
property.
6. <jsp:getProperty>:
->This action tag gets the value of a property in a bean by using the bean's getter
method and writes the value to the current JspWriter.
Types of attributes:
(a) name
(b)property
(a) name:
->The name attribute takes the reference variable name on which we want to invoke
the getter method.
(b) property:
->which gets the value of a bean property and invokes the getter method of the bean
property.
Two types of development models are used in Java for Web applications, and these
models are classified based on the different approaches used to develop Web
applications.
1. Model-1 Architecture
2. Model-2 Architecture(MVC)
1. Model-1 Architecture:
The Model-1 architecture was the first development model used to develop Web
applications and this model uses JSP to design applications and, which is responsible for
all the activities and functionalities provided by the application.
(i).Applications are inflexible and difficult to maintain. A single change in one page may
cause changes in other pages, leading to unpredictable results.
(ii).Involves the developer at both the page development and the business logic
implementation stages.
(iii).Increases the complexity of a program with the increase in the size of the JSP page.
->The draw backs in the Model-1 architecture led to the introduction of a new model
called Model-2. this Model-2 architecture is based on the MVC design model.
->MVC Stands for Model View Controller.
View: Shows the contents of a Model.The View component accesses enterprise data
through the Model component and specifies how that data should be presented and this
View Component is designed by JSP.
Controller: Receives HTTP requests. The Controller component receives requests from a
client, determines the business logic to be performed, and delegates the responsibility
for producing the next phase of the user interface to an appropriate view component.
->Offers great flexibility to the presentation logic, which can be modified without
effecting the business logic.
syntax of EL:
$(expression)
requestScope : It maps the given attribute name with the value set in the request
scope.
sessionScope : It maps the given attribute name with the value set in the session scope.
applicationScope : It maps the given attribute name with the value set in the application
scope.
Note:
->we use "taglib" directive tag to declare JSTL Tags.
javax.servlet.jsp.jstl-1.2.1.jar
javax.servlet.jsp.jstl-api-1.2.1.jar
(ii) These jars must be available within 'lib' folder of 'WEB-INF' in deployment directory
(1)Core Tags:
->These JSTL core tags provides variable support,URL management, flow control etc.
(Basic code writing)
syntax:
<%=...%> tag.
*imp
context-relative URLs.
JSP LifeCycle:
->JSP LifeCycle demonstrates diff states of JSP program from Starting of the program to
the ending of the program.
(2)Compilation process
(3)Loading process
(4)Instantiation process
(5)Initialization process
(7)Destroying process
(1)Translation process:
->The process of separating JavaCode from JSP program is known as Translation process.
=>The process of compiling the SourceCode and generating the ByteCode is known as
Compilation process.
->The process of loading the JSP program for execution is known as Loading process.
=>The process of creating object for JSP program is known as Instantiation process.
(i)_jspInit()
(ii)_jspService()
(iii) _jspDestroy()
define Event-Deligation-Process?
=>when the event is performed on Source Object then the related Listener is executed
automatically and handles the event by executing related method.
1. Source Object
2. Event Class
2. Listener
3. Methods
Source Object : ServletContext object
Listener : ServletContextListener
Methods : contextInitialized(),contextDestroyed()
Listener : ServletRequestListener
Methods : requestInitialized(),requestDestroyed()
Source Object : HttpSession Object
Listener : HttpSessionListener
Methods : sessionCreated(),sessionDestroyed()
If you are using recent version eclipse then you won’t get webcontent folder
you will get webapp so you need to put all your html,jsp ..etc in webapp
only.