0% found this document useful (0 votes)
7 views29 pages

WT Unit V

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views29 pages

WT Unit V

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Unit – V

• It stands for Java Server Pages.


• It is a server side technology.
• It is used for creating web application.
• It is used to create dynamic web content.
• In this JSP tags are used to insert JAVA code into HTML pages.
• It is an advanced version of Servlet Technology.
• It is a Web based technology helps us to create dynamic and platform independent
web pages.
• In this, Java code can be inserted in HTML/ XML pages or both.
• JSP is first converted into servlet by JSP container before processing the client’s
request.

Steps for Execution of JSP are following:-


• Create html page from where request will be sent to server eg try.html.
• To handle to request of user next is to create .jsp file Eg. new.jsp
• Create project folder structure.
• Create XML file eg my.xml.
• Create WAR file.
• Start Tomcat
• Run Application

Features of JSP
Coding in JSP is easy.
Reduction in the length of Code.
Connection to Database is easier.
Make Interactive websites.
Portable, Powerful, flexible and easy to maintain.
No Redeployment and No Re-Compilation.
Extension to Servlet.
Advantages of using JSP
• It does not require advanced knowledge of JAVA
• It is capable of handling exceptions
• Easy to use and learn
• It can tags which are easy to use and understand
• Implicit objects are there which reduces the length of code
• It is suitable for both JAVA and non JAVA programmer
Disadvantages of using JSP
• Difficult to debug for errors.
• First time access leads to wastage of time
• It’s output is HTML which lacks features.
JavaServer Pages (JSP) is a technology for developing Webpages that supports dynamic
content. This helps developers insert java code in HTML pages by making use of special JSP
tags, most of which start with <% and end with %>.
A JavaServer Pages component is a type of Java servlet that is designed to fulfill the role of
a user interface for a Java web application
Why use JSP:
JavaServer Pages often serve the same purpose as programs implemented using
the Common Gateway Interface (CGI). But JSP offers several advantages in comparison
with the CGI.
• Performance is significantly better because JSP allows embedding Dynamic Elements
in HTML Pages itself instead of having separate CGI files.
• JSP are always compiled before they are processed by the server unlike CGI/Perl
which requires the server to load an interpreter and the target script each time the
page is requested.
• JavaServer Pages are built on top of the Java Servlets API, so like Servlets, JSP also has
access to all the powerful Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP, etc.
• JSP pages can be used in combination with servlets that handle the business logic,
the model supported by Java servlet template engines
Difference between Servlet and JSP:

JDBC:
Java DataBase Connectivity, commonly known as JDBC, is an API for Java programming
language that defines how a client may access a database. JDBC API uses JDBC driver
written in Java. JDBC is platform independent.
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.
The JDBC library includes APIs for each of the tasks mentioned below that are commonly
associated with database usage.
• Making a connection to a database.
• Creating SQL or MySQL statements.
• Executing SQL or MySQL queries in the database.
• Viewing & Modifying the resulting records.
Fundamentally, JDBC is a specification that provides a complete set of interfaces that allows
for portable access to an underlying database. Java can be used to write different types of
executables, such as:
• Java Applications
• Java Applets
• Java Servlets
• Java ServerPages (JSPs)
• Enterprise JavaBeans (EJBs).
All of these different executables are able to use a JDBC driver to access a database, and
take advantage of the stored data. JDBC provides the same capabilities as ODBC, allowing
Java programs to contain database independent code.

Components of JDBC:

JDBC has four major components that are used for the interaction with the database.
1. JDBC API
2. JDBC Test Suite
3. JDBC Driver Manger
4. JDBC ODBC Bridge Driver

1) JDBC API: JDBC API provides various interfaces and methods to establish easy connection
with different databases.

1. javax.sql.*;
2. java.sql.*;

2) JDBC Test suite: JDBC Test suite facilitates the programmer to test the various operations
such as deletion, updation, insertion that are being executed by the JDBC Drivers.

3) JDBC Driver manager: JDBC Driver manager loads the database-specific driver into an
application in order to establish the connection with the database. The JDBC Driver manager
is also used to make the database-specific call to the database in order to do the processing
of a user request.

4) JDBC-ODBC Bridge Drivers: JDBC-ODBC Bridge Drivers are used to connect the database
drivers to the database. The bridge does the translation of the JDBC method calls into the
ODBC method call. It makes the usage of the sun.jdbc.odbc package that encompasses the
native library in order to access the ODBC (Open Database Connectivity) characteristics.

JDBC Drivers:
A JDBC driver is a software component enabling a java application to interact with
a database. JDBC requires drivers for each database. The JDBC driver gives out the
connection to the database and implements the protocol for transferring the query
and result between client and database. JDBC drivers are client side adaptors that
convert request from java program to a protocol that that the DBMS can understand.
There are four types of drivers:
1. JDBC-ODBC(Open Database Connectivity) Bridge Driver (Type 1)
2. Native API Driver (Type 2/Partially Java Driver)
3. Network Protocol Driver (Type 3/Fully Java Driver)
4. Thin Driver (Type 4/Fully Java Driver)

1. JDBC-ODBC Bridge Driver (Type 1)


• Uses ODBC bridge driver to connect to database.
• Converts JDBC methods call into function call.
• ODBC drivers need to be installed on client machine.
• This driver is platform dependent.
Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle recommends that you
use JDBC drivers provided by the vendor of your database instead of the JDBC-ODBC Bridge.
Advantages:
• easy to use.
• can be easily connected to any database.
Disadvantages:
• Does not support the complete java command set and are limited by the
functionality of the ODBC driver.
• Needs to be installed on client machine.
• Slow, as compared to other drivers
2. Native API Driver (Type 2/Partially Java Driver):
• It uses client side libraries of the database.
• The driver converts the JDBC method call into native call.
• Native drivers must be installed on client machines.
• Vendor client libraries need to be installed on client machine.
• It is not written entirely in java.

Advantage:
• Better performance as compared to Type 1 driver.
Disadvantages:
• Driver is platform dependent.
• The vendor client library needs to be installed.
• Native driver needs to be installed on each machine.

3. Network Protocol Driver (Type 3/Fully Java Driver):


• Uses middleware that convert JDBC call directly or indirectly into vendor specific database
protocol.
• Fully written in Java.
• Database specific coding to be done in middle tier

Advantage:
o No client side library is required because of application server that can perform many
tasks like auditing, load balancing, logging etc.
Disadvantages:
o Network support is required on client machine.
o Requires database-specific coding to be done in the middle tier.
o Maintenance of Network Protocol driver becomes costly because it requires
database-specific coding to be done in the middle tier.
4. Thin Driver (Type 4/Fully Java Driver):
• Converts JDBC calls directly into vendor specific database protocol.
• Fully written in Java.
• User needs different drivers for each database.
• Performance is good.
Advantage:
Performance is good as compared to other drivers.
No software is required for client or server side.
Disadvantage:
Different types of drivers required for different database.

Loading the driver:


In order to begin with, you first need to load the driver or register it before using it in the
program. Registration is to be done once in your program. You can register a driver in one
of two ways mentioned below as follows:
1. Class.forName()
2. DriverManager.registerDriver()
1. Class.forName()
Here we load the driver’s class file into memory at the runtime. No need of using new or
create objects. The following example uses Class.forName() to load the Oracle driver as
shown below as follows:
Class.forName(“oracle.jdbc.driver.OracleDriver”);
2. DriverManager.registerDriver()
DriverManager is a Java inbuilt class with a static member register. Here we call the
constructor of the driver class at compile time. The following example uses
DriverManager.registerDriver()to register the Oracle driver as shown below:
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver())
Establishing connection:
To connect with a database, you need to follow the steps given below:
Step1: Register the driver: To develop a basic JDBC application, first of all, you need to
register the driver with the DriverManager.
You can register a driver in two ways, one is using registerDriver() method of
the DriverManager class and, using forName() method of the class named Class.
The registerDriver() method accepts an object of the Driver class, it registers the specified
Driver with the DriverManager.

The forName() method loads the specified class into the memory and thus it automatically
gets registered.

Example:

Closing the connection:


The close() method of the Connection interface is used to close the connection. It is as
shown below as follows:
con.close();
MVC Architecture:
MVC is an architecture that separates business logic, presentation and data.
In MVC,
• M stands for Model
• V stands for View
• C stands for controller.
MVC is a systematic way to use the application where the flow starts from the view layer,
where the request is raised and processed in controller layer and sent to model layer to
insert data and get back the success or failure message.

Model Layer
• This is the data layer which consists of the business logic of the system.
• It consists of all the data of the application
• It also represents the state of the application.
• It consists of classes which have the connection to the database.
• The controller connects with model and fetches the data and sends to the view layer.
• The model connects with the database as well and stores the data into a database
which is connected to it.
View Layer
• This is a presentation layer.
• It consists of HTML, JSP, etc. into it.
• It normally presents the UI of the application.
• It is used to display the data which is fetched from the controller which in turn
fetching data from model layer classes.
• This view layer shows the data on UI of the application.
Controller Layer
• It acts as an interface between View and Model.
• It intercepts all the requests which are coming from the view layer.
• It receives the requests from the view layer and processes the requests and does the
necessary validation for the request.
• This request is further sent to model layer for data processing, and once the request
is processed, it sends back to the controller with required information and displayed
accordingly by the view.
Advantages of MVC Architecture
• Easy to maintain
• Easy to extend
• Easy to test
• Navigation control is centralized

Executing SQL statement in JSP pages:


The <sql:query> tag executes an SQL SELECT statement and saves the result in a scoped
variable.
Attribute
The <sql:query> tag has the following attributes −

Output:
JSP Implicit Objects
JSP supports nine automatically defined variables, which are also
called implicit objects. These variables are:

The request Object


The request object is an instance of a javax.servlet.http.HttpServletRequest object. Each time a
client requests a page the JSP engine creates a new object to represent that request.
The request object provides methods to get the HTTP header information including form data,
cookies, HTTP methods etc.
We can cover a complete set of methods associated with the request object in a subsequent
chapter − JSP - Client Request.
Example of JSP request implicit object
index.html
1. <form action="welcome.jsp">
2. <input type="text" name="uname">
3. <input type="submit" value="go"><br/>
4. </form>
welcome.jsp
1. <%
2. String name=request.getParameter("uname");
3. out.print("welcome "+name);
4. %>
Output

The response Object


The response object is an instance of a javax.servlet.http.HttpServletResponse object. Just as
the server creates the request object, it also creates an object to represent the response to the
client.
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.
We will cover a complete set of methods associated with the response object in a subsequent
chapter − JSP - Server Response.

Example of response implicit object


index.html

1. <form action="welcome.jsp">
2. <input type="text" name="uname">
3. <input type="submit" value="go"><br/>
4. </form>
welcome.jsp
1. <%
2. response.sendRedirect("http://www.google.com");
3. %>
Output

The out Object


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 JspWriter object contains most of the same methods as the java.io.PrintWriter class.
However, JspWriter has some additional methods designed to deal with buffering. Unlike the
PrintWriter object, JspWriter throws IOExceptions.
Following table lists out the important methods that we will use to write boolean char, int, double,
object, String, etc.

S.No. Method & Description

1 out.print(dataType dt)
Print a data type value

out.println(dataType dt)
2
Print a data type value then terminate the line with new line character.

out.flush()
3
Flush the stream.
Example of out implicit object
In this example we are simply displaying date and time.

index.jsp
1. <html>
2. <body>
3. <% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
4. </body>
5. </html>
Output

The session Object


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 will cover the
complete usage of session object in a subsequent chapter − JSP - Session Tracking.

Example of session implicit object


index.html
1. <html>
2. <body>
3. <form action="welcome.jsp">
4. <input type="text" name="uname">
5. <input type="submit" value="go"><br/>
6. </form>
7. </body>
8. </html>
welcome.jsp
1. <html>
2. <body>
3. <%
4.
5. String name=request.getParameter("uname");
6. out.print("Welcome "+name);
7.
8. session.setAttribute("user",name);
9.
10. <a href="second.jsp">second jsp page</a>
11.
12. %>
13. </body>
14. </html>
second.jsp
1. <html>
2. <body>
3. <%
4.
5. String name=(String)session.getAttribute("user");
6. out.print("Hello "+name);
7.
8. %>
9. </body>
10. </html>

Output
The application Object
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.
By adding an attribute to application, you can ensure that all JSP files that make up your web
application have access to it.
We will check the use of Application Object in JSP - Hits Counter chapter.

Example of application implicit object:


index.html

1. <form action="welcome">
2. <input type="text" name="uname">
3. <input type="submit" value="go"><br/>
4. </form>
web.xml file

1. <web-app>
2.
3. <servlet>
4. <servlet-name>sonoojaiswal</servlet-name>
5. <jsp-file>/welcome.jsp</jsp-file>
6. </servlet>
7.
8. <servlet-mapping>
9. <servlet-name>sonoojaiswal</servlet-name>
10. <url-pattern>/welcome</url-pattern>
11. </servlet-mapping>
12.
13. <context-param>
14. <param-name>dname</param-name>
15. <param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
16. </context-param>
17.
18. </web-app>
welcome.jsp

1. <%
2.
3. out.print("Welcome "+request.getParameter("uname"));
4.
5. String driver=application.getInitParameter("dname");
6. out.print("driver name is="+driver);
7.
8. %>

Output
The config Object
The config object is an instantiation of javax.servlet.ServletConfig and is a direct wrapper around
the ServletConfig object for the generated servlet.
This object allows the JSP programmer access to the Servlet or JSP engine initialization
parameters such as the paths or file locations etc.
The following config method is the only one you might ever use, and its usage is trivial −
config.getServletName();
This returns the servlet name, which is the string contained in the <servlet-name> element defined
in the WEB-INF\web.xml file.

Example of config implicit object:


index.html

1. <form action="welcome">
2. <input type="text" name="uname">
3. <input type="submit" value="go"><br/>
4. </form>
web.xml file

1. <web-app>
2.
3. <servlet>
4. <servlet-name>sonoojaiswal</servlet-name>
5. <jsp-file>/welcome.jsp</jsp-file>
6.
7. <init-param>
8. <param-name>dname</param-name>
9. <param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
10. </init-param>
11.
12. </servlet>
13.
14. <servlet-mapping>
15. <servlet-name>sonoojaiswal</servlet-name>
16. <url-pattern>/welcome</url-pattern>
17. </servlet-mapping>
18.
19. </web-app>
welcome.jsp

1. <%
2. out.print("Welcome "+request.getParameter("uname"));
3.
4. String driver=config.getInitParameter("dname");
5. out.print("driver name is="+driver);
6. %>
Output

The pageContext Object


The pageContext object is an instance of a javax.servlet.jsp.PageContext object. The
pageContext object is used to represent the entire JSP page.
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.
The pageContext object also contains information about the directives issued to the JSP page,
including the buffering information, the errorPageURL, and page scope.
The PageContext class defines several fields, including PAGE_SCOPE, REQUEST_SCOPE,
SESSION_SCOPE, and APPLICATION_SCOPE, which identify the four scopes. It also supports
more than 40 methods, about half of which are inherited from the javax.servlet.jsp.JspContext
class.
One of the important methods is removeAttribute. This method accepts either one or two
arguments. For example, pageContext.removeAttribute ("attrName") removes the attribute
from all scopes, while the following code only removes it from the page scope −
pageContext.removeAttribute("attrName", PAGE_SCOPE);
The use of pageContext can be checked in JSP - File Uploading chapter.
Example of pageContext implicit object
index.html
1. <html>
2. <body>
3. <form action="welcome.jsp">
4. <input type="text" name="uname">
5. <input type="submit" value="go"><br/>
6. </form>
7. </body>
8. </html>
welcome.jsp
1. <html>
2. <body>
3. <%
4.
5. String name=request.getParameter("uname");
6. out.print("Welcome "+name);
7.
8. pageContext.setAttribute("user",name,PageContext.SESSION_SCOPE);
9.
10. <a href="second.jsp">second jsp page</a>
11.
12. %>
13. </body>
14. </html>
second.jsp
1. <html>
2. <body>
3. <%
4.
5. String name=(String)pageContext.getAttribute("user",PageContext.SESSION_SCOPE);
6. out.print("Hello "+name);
7.
8. %>
9. </body>
10. </html>
Output

The page 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.

For using this object it must be cast to Servlet type.For example:


<% (HttpServlet)page.log("message"); %>
Since, it is of type Object it is less used because you can use this object directly in jsp.For example:
<% this.log("message"); %>
The exception 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.

Example of exception implicit object:


error.jsp
1. <%@ page isErrorPage="true" %>
2. <html>
3. <body>
4.
5. Sorry following exception occured:<%= exception %>
6.
7. </body>
8. </html>

JSP Comments
Since JSP is built on top of HTML, we can write comments in JSP file
like html comments as
<-- This is HTML Comment -->
These comments are sent to the client and we can look it with view
source option of browsers. We can put comments in JSP files as:
<%-- This is JSP comment --%>
This comment is suitable for developers to provide code level
comments because these are not sent in the client response.

You might also like