Fsad LM 3
Fsad LM 3
Fsad LM 3
UNIT-IV
JSP, JDBC
SYLLABUS:
JSP: JSP architecture, Life Cycle, Creating Simple JSP Pages, JSP Basic tags, Implicit Objects.
JDBC: Introduction to JDBC, JDBC architecture, JDBC Drivers, Database Connectivity, CRUD
operations.
Installation Progress:
Testing TOMCAT:
To test the server - assuming you're running Tomcat on the same machine as
the browser and that you're using the default port for Tomcat (8080) But we
changed it to 2025 while installing- open a browser and enter the following
URL in the Location/Address field:
http://localhost:2025/
The Tomcat main page is shown in the browser and you can now run all servlet
and JSP examples bundled with Tomcat to make sure everything works.
Introduction to JSP:
Java Server Pages (JSP) is a technology that helps software developers create dynamically
generated web pages based on HTML,XML or other document types.
Servlet is a Java code based programming. To know servlet, strong Java knowledge is required.
However, while working with ASP.net, PHP like technologies we can go for tag-based
programming which is easier. So in initial days programmer did not like Servlet. To attract non-
java programmers like ASP.net programmers and PHP programmer Sun Microsystems has
introduced a server side technology which is tag based all features of servlet.
To deploy and run JavaServer Pages, a compatible web server with a servlet container, such as
Apache Tomcat or Jetty, is required.
Servlets are difficult to code which are overcome in JSP. Other way, we can say, JSP is
almost a replacement of Servlets, (by large, the better word is extension of Servlets),
where coding decreases more than half.
In Servlets, both static code and dynamic code are put together. In JSP, they are
separated. For example,In Servlets:
out.println(“Hello Mr.” + str + ” you are great man”);
where str is the name of the client which changes for each client and is known as
dynamic content. The strings, “Hello Mr.” and “you are great man” are static content
which is the same irrespective of client. In Servlets, in println(), both are put together.
In JSP:
Hello Mr. // static content as HTML code
<%= str %> // dynamic content as JSP code
you are great man // static content as HTML code
JSP needs no compilation, CLASSPATH setting and packaging.
The objects of PrintWriter, ServletConfig, ServletContext, HttpSession and
RequestDispatcher etc. are created by the Programmer in Servlets and used. But in JSP,
they are builtin and are known as "implicit objects". That is, in JSP, Programmer never
creates these objects and straightaway use them as they are implicitly created and given
by JSP container. This decreases lot of coding.
JSP needs no compilation by the Programmer. Programmer deploys directly a JSP source
code file in server where as incase of Servlets, the Programmer compiles manually a
Servlet file and deploys a .class file in server.
No need to configure the jsp in web.xml.
Whenever JSP modified, modifications reflected without recompilation, where as in
Servlet without compilation not possible to reflect the modification.
A JSP page is simply a regular web page with JSP elements for generating the parts of the page
that differ for each request, as shown in Figure below.
Everything in the page that is not a JSP element is called template text . Template text can really
be any text: HTML, WML, XML, or even plain text. Since HTML is by far the most common
web page language in use today, most of the descriptions and examples in this book are HTML-
based, but keep in mind that JSP has no dependency on HTML; it can be used with any markup
language. Template text is always passed straight through to the browser.
When a JSP page request is processed, the template text and the dynamic content generated by
the JSP elements are merged, and the result is sent as the response to the browser.
JSP Container:
As a web server needs a servlet container to provide an interface to servlets, the
server needs a JSP container to process JSP pages. The JSP container is often
implemented as a servlet configured to handle all requests for JSP pages. In
fact, these two containers - a servlet container and a JSP container - are often
combined into one package under the name web container.
JSP Processing is done in 2 phases:
i) Translation Phase
ii) Request Processing Phase
i) Translation Phase:
A JSP container is responsible for converting the JSP page into a servlet (known
as the JSP page implementation class) and compiling the servlet. These two
steps form the translation phase. The JSP container automatically initiates the
translation phase for a page when the first request for the page is received. The
translation phase can also be initiated explicitly; this is referred to as
precompilation of a JSP page.
When a JSP container receives a jsp request, it checks for the jsp’s servlet
instance. If no servlet instance is available, then, the container creates the
servlet instance using following stages.
Translation
Compilation
Loading
Instantiation
Initialization
Translation - In this step the JSP page is translated into the corresponding
Servlet.
Compilation - Once the JSP page has been translated into the corresponding
Servlet, the next obvious step is to compile that Servlet.
Loading & Instantiation - As is the case with any compiled class (.class file),
this servlet class also needs to be loaded into the memory before being used.
The default class loader of the Container will load this class. Once the class is
loaded, an instance of this class gets created.
Initialization: JspPage interface contains the jspInit() method, which is used
by the JSP container to initialize the newly created instance.
This jspInit() method is just like the init()method of the Servlet and it's called
only once during the entire life cycle of a JSP/Servlet.
i). The jspInit()- The container calls the jspInit() to initialize the servlet
instance.It is called before any other method, and is called only once for a
servlet instance.
ii). The _jspservice()- The container calls the _jspservice() for each request,
passing it the request and the response objects.
{
// Service handling code...
}
iii). The jspDestroy()- The container calls this when it decides to take the
instance out of service. It is the last method called in the servlet instance.
This root directory structure we have to follow while developing applications using the
JSP/Servlets.
JSP Directives:
JSP directives provide directions and instructions to the container, telling it how to handle certain
aspects of JSP processing.
A JSP directive affects the overall structure of the servlet class. It usually has the following form:
Directive Description
<%@ page ... %> defines page dependent properties such as language, session, errorPage etc.
<%@ taglib ... %> declares tag library used in the page
We'll discuss about include and taglib directive later. You can place page directive anywhere in
the JSP file, but it is good practice to make it as the first statement of the JSP page.
The Page directive defines a number of page dependent properties which communicates with the
Web Container at the time of translation. Basic syntax of using the page directive is
import attribute
language attribute
extends attribute
session attribute
isThreadSafe attribute
isErrorPage attribute
errorPage attribute
contentType attribute
autoFlush attribute
buffer attribute
import attribute
The import attribute defines the set of classes and packages that must be imported in servlet class
definition. For example
or
language attribute
extends attribute
extends attribute defines the class name of the superclass of the servlet class that is generated
from the JSP page.
session attribute
session attribute defines whether the JSP page is participating in an HTTP session. The value is
either true or false.
isThreadSafe attribute
isThreadSafe attribute declares whether the JSP is thread-safe. The value is either true or false
isErrorPage attribute
isErrorPage attribute declares whether the current JSP Page represents another JSP's error page.
errorPage attribute
errorPage attribute indicates another JSP page that will handle all the run time exceptions thrown
by current JSP page. It specifies the URL path of another page to which a request is to be
dispatched to handle run time exceptions thrown by current JSP page.
contentType attribute
contentType attribute defines the MIME type for the JSP response.
autoFlush attribute
autoFlush attribute defines whether the buffered output is flushed automatically. The default
value is "true".
buffer attribute
buffer attribute defines how buffering is handled by the implicit out object.
include Directive:
The include directive is used to includes a file during the translation phase. This directive tells
the container to merge the content of other external files with the current JSP during the
translation phase. You may code include directives anywhere in your JSP page.
The filename in the include directive is actually a relative URL. If you just specify a filename
with no associated path, the JSP compiler assumes that the file is in the same directory as your
JSP.
Taglib Directive:
The taglib directive is used to define tag library that the current JSP page uses. A JSP page might
include several tag library. JavaServer Pages Standard Tag Library (JSTL), is a collection of
useful JSP tags, which provides mahy commonly used core functionalities. It has support for
many general, structural tasks such as iteration and conditionals, readymade tags for
manipulating XML documents, internationalization tags, and for performing SQL operations.
Syntax of taglib directive is:
The prefix is used to distinguish the custom tag from other libary custom tag. Prefix is prepended
to the custom tag name. Every custom tag must have a prefix.
There are many JSP action tags or elements. Each JSP action tag is used to perform some
specific tasks.
The action tags are used to control the flow between pages and to use Java Bean. The Jsp action
tags are given below.
We can dynamically insert a file, reuse the beans components, forward user to another page, etc.
through JSP Actions like include and forward.
Unlike directives, actions are re-evaluated each time the page is accessed.
jsp:useBean
jsp:include
jsp:setProperty
jsp:getProperty
jsp:forward
jsp:plugin
jsp:attribute
jsp:body
jsp:text
jsp:param
jsp:output
1. jsp:useBean:
This action name is used when we want to use beans in the JSP page.
Syntax:
Here it specifies the identifier for this bean and class is full path of the bean class
2. jsp:include
It also used to insert a jsp file into another file, just like include directive.
Syntax:
3. jsp:setProperty
Syntax:
Here, the name defines the bean whose property is set and property which we want to set.
Here value is not mandatory, and it defines the value which is assigned to the property.
Here param is the name of the request parameter using which value can be fetched.
4. jsp:getProperty
Syntax:
Here, the name of the bean from which the property has to be retrieved and bean should be
defined. The property attribute is the name of the bean property to be retrieved.
5. jsp:forward:
Syntax:
<jsp:forward page="value">
6. jsp:plugin
It is used to introduce Java components into jsp, i.e., the java components can be either an applet
or bean.
It detects the browser and adds <object> or <embed> tags into the file
Syntax:
Code base contains the base URL that contains files of classes
7. jsp:param
Syntax:
<jsp:params>
</jsp:params>
8. jsp:body
This tag is used to define the XML dynamically i.e., the elements can generate during request
time than compilation time.
Syntax:
<jsp:body></jsp:body>
9. jsp:attribute
This tag is used to define the XML dynamically i.e. the elements can be generated during request
time than compilation time
Syntax:
<jsp:attribute></jsp:attribute>
10. jsp:text
Its body does not contain any other elements, and it contains only text and EL expressions.
Syntax:
<jsp:text>template text</jsp:text
Here template text refers to only template text (which can be any generic text which needs to be
printed on jsp ) or any EL expression.
11. jsp:output:
Syntax:
Doctype-system indicates doctype which is generated in output and gives system literal
JSP scripting elements enable you insert Java code into the servlet that will be generated from
the current JSP page. There are three forms:
Scriptlets of the form <% code %> that are inserted into the servlets service method.
Expressions of the form <%= expression%> that are evaluated and inserted into output.
Declarations of the form <%! code %> that are inserted into the body of the servlet class,
outside of any existing methods.
Scriptlet Tag allows you to write java code inside JSP page. Scriptlet tag implements the
_jspService() method functionality by writing script/java code. Syntax of Scriptlet Tag is as
follows :
<%
java code
%>
Within a scriptlet, you can do any of the following:
Declare variables or methods to use later in the JSP page.
Write expressions valid in the page scripting language.
Use any of the implicit objects or any object declared with a <jsp:useBean> element.
Write any other statement valid in the scripting language used in the JSP page.
In this example, Finding Addition of two numbers.
<%@page language="java" contentType="text/html"%>
<%
//declaring variables
int a=10;
int b=20;
int c=a+b;
%>
<center>
<h1>Addition is
<%
//printing results
out.println(c);
%>
</h1>
</center>
Output:
We have been using the above example since last few lessons and in this scriptlet tags are used.
Everything written inside the scriptlet tag is compiled as java codeJSP makes it so easy to
perform calculations, database interactions etc directly from inside the HTML code. Just write
your java code inside the scriptlet tags.
Declaration Tag(Decalarations)
We know that at the end a JSP page is translated into Servlet class. So when we declare a
variable or method in JSP inside Declaration Tag, it means the declaration is made inside the
Servlet class but outside the service(or any other) method. You can declare static member,
instance variable and methods inside Declaration Tag.
<%!
declaration
%>
The code placed within JSP expression tag is written to the output stream of the response. So you
need not write out.print() to write data. It is mainly used to print the values of variable or
method.
<%=
Statement
%>
In this example of jsp expression tag, we are simply displaying a welcome message.
<html>
<body>
</body>
</html>
To display the current time, we have used the getTime() method of Calendar class. The
getTime() is an instance method of Calendar class, so we have called it after getting the instance
of Calendar class by the getInstance() method.
index.jsp:
<html>
<head></head>
<body>
Your Hostname:<%=request.getRemoteHost()%><br>
Session Id:<%=session.getId()%><br>
</body>
</html>
Output:
Implicit Objects:
JSP Implicit Objects are the Java objects that the JSP Container makes available to developers in
each page and developer can call them directly without being explicitly declared. JSP Implicit
Objects are also called pre-defined variables.
Object Description
Out This is the PrintWriter object used to send output to the client.
context.
Page This is simply a synonym for this, and is used to call the
methods defined by the translated servlet class.
The request object provides methods to get HTTP header information including form data,
cookies, HTTP methods etc.
The response object also defines the interfaces that deal with creating new HTTP headers.
Through this object the JSP programmer can add new cookies or date stamps, HTTP status codes
etc.
The out implicit object is an instance of a javax.servlet.jsp.JspWriter object and is used to send
content in a response.
The initial JspWriter object is instantiated differently depending on whether the page is buffered
or not. Buffering can be easily turned off by using the buffered='false' attribute of the page
directive.
The session object is an instance of javax.servlet.http.HttpSession and behaves exactly the same
way that session objects behave under Java Servlets.
The session object is used to track client session between client requests. We would see complete
usage of session object in coming chapter: JSP - Session Tracking
The application object is direct wrapper around the ServletContext object for the generated
Servlet and in reality an instance of a javax.servlet.ServletContext object.
This object is a representation of the JSP page through its entire lifecycle. This object is created
when the JSP page is initialized and will be removed when the JSP page is removed by the
jspDestroy() method.
This object allows the JSP programmer access to the Servlet or JSP engine initialization
parameters such as the paths or file locations etc.
This object is intended as a means to access information about the page while avoiding most of
the implementation details.
This object stores references to the request and response objects for each request. The
application, config, session, and out objects are derived by accessing attributes of this object.
This object is an actual reference to the instance of the page. It can be thought of as an object that
represents the entire JSP page.
The page object is really a direct synonym for the this object.
The exception object is a wrapper containing the exception thrown from the previous page. It is
typically used to generate an appropriate response to the error condition.
The jsp scriptlet tag can only The jsp declaration tag can declare
declare variables not methods. variables as well as methods.
</html>
Example of JSP declaration tag that declares method:
In this example of JSP declaration tag, we are defining the method which
returns the cube of given number and calling this method from the jsp
expression tag. But we can also use jsp scriptlet tag to call the declared
method.
index.jsp
<html>
<body>
<%!
int cube(int n){
return n*n*n*;
}
%>
<%= "Cube of 3 is:"+cube(3) %>
</body>
</html>
PASSING CONTROL AND DATA BETWEEN JSP PAGES, REQUESTS:
<jsp:forward page=”targetPageURL”/>
Once the jsp engine encounters the <jsp:forward> action, it stops the
processing of the current page and starts the processing of the target
page specified by the page attribute. The rest of the original page is never
processed further.
The HttpServletRequest and HttpServletResponse objects are passed
to the target page. So, the target page can access all information passed
to the original page.
We can pass additional parameters to the target page using the
<jsp:param> action element along with the <jsp:forward>
</jsp:forward>
The target page can access these parameters in the same way as the original
parameters using the getParameter() method or by using $
{param.parameterName} .
Example:
One.jsp:
<jsp:forward page="two.jsp">
</jsp:forward>
Two.jsp:
Example:
Login.html:
<HTML>
<HEAD>
</HEAD>
<BODY bgcolor='#999900'>
<center>
<table>
</tr>
</table>
</form>
</center>
</BODY>
</HTML>
One.jsp:
<%
String username=request.getParameter("username");
session.setAttribute("username",username);
%>
Two.jsp:
<%
String username=(String)session.getAttribute("username");
%>
<%if(username!=null){%>
<center><h1>Hello <%=username%></h1></center>
<%}else{%>
<%}%>
Output:
http://localhost:2025/Sharing session/login.html
The objects that have application scope are shared across all pages of
an application that are requested through any browser.
Implicit object used is application.
Example:
Count.jsp:
<%
Integer count=(Integer)application.getAttribute("count");
%>
<%if(count==null)
count=1;
else
count++;
application.setAttribute("count",count);
%>
<center><h1>No of Visiotrs<%=count%></h1></center>
Output:
http://localhost:2025/Sharing Application/count.jsp
Refresh browser out will be changed here refreshed browser for 4 times.
JDBC stands for Java Database Connectivity, which is a standard Java API for database-
independent connectivity between the Java programming language and a wide range of
databases. If we want to save our application data permanently in initial days of programming we
use the concept files. Files are used to store the data permanently but files are having following
limitations.
1. Files are having only operating system level security, files are not having programming level
security.
2. Files are complex to work. i.e; to write and retrieve data from files is complex task.
3. There is no relationships exist between the files.
4. There is no query language for files.
5. Files are having unstructured data.
The JDBC library includes APIs for each of the tasks mentioned below that are commonly
associated with database usage.
JDBC Architecture:
The JDBC API supports both two-tier and three-tier processing models for database
access but in general, JDBC Architecture consists of two layers −
JDBC API: This provides the application-to-JDBC Manager connection.
JDBC Driver API: This supports the JDBC Manager-to-Driver Connection.
The JDBC API uses a driver manager and database-specific drivers to provide
transparent connectivity to heterogeneous databases.
The JDBC driver manager ensures that the correct driver is used to access each data
source. The driver manager is capable of supporting multiple concurrent drivers
connected to multiple heterogeneous databases.
Following is the architectural diagram, which shows the location of the driver
manager with respect to the JDBC drivers and the Java application −
ResultSet: These objects hold data retrieved from a database after you execute
an SQL query using Statement objects. It acts as an iterator to allow you to
move through its data.
SQLException: This class handles any errors that occur in a database
application.
JDBC Drivers:
JDBC drivers are divided into four types or levels. They are:
Type 1: JDBC-ODBC Bridge driver (Bridge)
Type 2: Native-API/partly Java driver (Native)
Type 3: AllJava/Net-protocol driver (Middleware)
Type 4: All Java/Native-protocol driver (Pure)
Advantage
The JDBC-ODBC Bridge allows access to almost any database, since the database's
ODBC drivers are already available.
Disadvantages
1. Since the Bridge driver is not written fully in Java, Type 1 drivers are not portable.
2. A performance issue is seen as a JDBC call goes through the bridge to the ODBC
driver, then to the database, and this applies even in the reverse process. They are the
slowest of all driver types.
3. The client system requires the ODBC Installation to use the driver.
4. Not good for the Web.
Advantage:
The distinctive characteristic of type 2 jdbc drivers are that they are typically offer
better performance than the JDBC-ODBC Bridge as the layers of communication
(tiers) are less than that of Type 1 and also it uses Native api which is Database
specific.
Disadvantages:
1. Native API must be installed in the Client System and hence type 2 drivers cannot
be used for the Internet.
2. Like Type 1 drivers, it’s not written in Java Language which forms a portability
issue.
3. If we change the Database we have to change the native api as it is specific to a
database
4. Mostly obsolete now
5. Usually not thread safe.
Type 3 JDBC Driver:
All Java/Net-protocol driver:
Type 3 database requests are passed through the network to the middle-tier server.
The middle-tier then translates the request to the database. If the middle-tier server
can in turn use Type1, Type 2 or Type 4 drivers.
Advantages:
1. This driver is server-based, so there is no need for any vendor database library to be
present on client machines.
2. This driver is fully written in Java and hence Portable. It is suitable for the web.
3. There are many opportunities to optimize portability, performance, and scalability.
4. The net protocol can be designed to make the client JDBC driver very small and fast
to load.
5. The type 3 driver typically provides support for features such as caching
(connections, query results, and so on), load balancing, and advanced
system administration such as logging and auditing.
6. This driver is very flexible allows access to multiple databases using one driver.
7. They are the most efficient amongst all driver types.
Disadvantages:
It requires another server application to install and maintain. Traversing the recordset
may take longer, since the data comes through the backend server.
Type 4 JDBC Driver:
Native-protocol/all-Java driver:
The Type 4 uses java networking libraries to communicate directly with the database
server.
Advantage
1. The major benefit of using a type 4 jdbc drivers are that they are completely written
in Java to achieve platform independence and eliminate deployment administration
issues. It is most suitable for the web.
2. Number of translation layers is very less i.e. type 4 JDBC drivers don't have to
translate database requests to ODBC or a native connectivity interface or to pass the
request on to another server, performance is typically quite good.
3. You don’t need to install special software on the client or server. Further, these
drivers can be downloaded dynamically.
Disadvantage
With type 4 drivers, the user needs a different driver for each database.
Class.forName(“Driver Name”);
Example:
Class.forName(“com.mysql.jdbc.Driver”);
Connection con=DriverManager.getConnection(url,username,password);
Example:
Connection con=DriverManager.getConnection(“jdb
c:mysql://localhost:3306/test”,”root”,”root”);
Statement st=con.createStatement();
while(rs.next())
System.out.println(“Name= ”+rs.getString(1));
System.out.println(“Location= ”+rs.getString(2));
Con.close();
Accessing a database from a JSP Page:
Sample programs to access database from JSP:
Write a JSP to display employee number and name from emp table
Root Directory
Retrieve.jsp:
<%@page import="java.sql.*"%>
<%
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/gec","root","root");
PreparedStatement ps=con.prepareStatement("select * from employee");
ResultSet rs=ps.executeQuery();%>
<center>
<table border='1'>
<tr>
<th>Employee Number</th>
<th>Name</th>
</tr>
<%while(rs.next())
{%>
<tr>
<td><%=rs.getString(1)%></td>
<td><%=rs.getString(2)%></td>
</tr>
<%}
%>
</table>
<center>
<%
}
catch(Exception e)
{
out.println(e);
}
%>
Output:
Write a JSP to Insert one record into dept table and Display them.
Root directory
Insert.jsp:
<%@page import="java.sql.*"%>
<%
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/gec","root","ro
ot");
PreparedStatement ps=con.prepareStatement("insert into dept
values(1,'sales','Gudlavalleru')");
int i=ps.executeUpdate();
if(i!=0)
{
out.println("<h1>Inserted Data Successfully...</h1>");
}
}
catch(Exception e)
{
out.println(e);
}
%>
Output:
Root Directory:
Login.html:
<HTML>
<HEAD>
</HEAD>
<BODY bgcolor='#999900'>
<center>
<form name='login' action='insert.jsp' method="post">
<table>
<tr><td colspan='2' align='center'><h2>Login Page</h2></td></tr>
<tr><td>Enter Name</td><td><input type='text'
name='name'></td></tr>
<tr><td>Enter Password</td><td><input type='password'
name='password'></td></tr>
<tr><td><input type='submit' value='Login'></td>
<td><input type='reset' value='Reset'></td>
</tr>
</table>
</form>
</center>
</BODY>
</HTML>
Insert.jsp:
<%@page import="java.sql.*"%>
<%
String name=request.getParameter("name");
String password=request.getParameter("password");
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/gec","root","root");
PreparedStatement ps1=con.prepareStatement("select * from user where
name=? and password=?");
ps1.setString(1,name);
ps1.setString(2,password);
ResultSet rs=ps1.executeQuery();
if(rs.next())
{
out.println("<h1>User Already Exist</h1>");
}
else
{
PreparedStatement ps2=con.prepareStatement("insert into user values(?,?)");
ps2.setString(1,name);
ps2.setString(2,password);
int i=ps2.executeUpdate();
out.println("<h1>Details Instered Sucessfully</h1>");
}
}
catch(Exception e)
{
out.println(e);
}
%>