Chapter 3 & 4 JSP& JDBC Handout 2019

Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

Java Server Pages (JSP)

A JavaServer page (JSP) is a template for a Web page that uses Java code to generate an
HTML document dynamically.
JSP have access to the entire family of Java APIs, including the JDBC API to access
enterprise databases. JSP is a technology for developing web pages that support dynamic
content which helps developers insert java code in HTML pages by making use of special
JSP tags, most of which start with <% and end with %>.
JSPs are run in a server-side & translated into equivalent Java servlets.
Because they are servlets, JSP pages have all the advantages of servlets:
• Better performance and scalability than CGI scripts because they are persistent in
memory and multithreaded.
• No special client setup is required.
• built-in HTTP sessions
• They have full access to Java technology But, in addition, JSP have advantages of
their own:
• They are automatically recompiled when necessary.
• Simpler than servlets.
• Greater compatibility with Web development tools.

The following is the list of other advantages of using JSP over other
technologies:
o vs. Active Server Pages (ASP): First, the dynamic part is written in Java, not Visual
Basic or other MS specific language, so it is more powerful and easier to use. Second, it
is portable to other operating systems and non-Microsoft Web servers.
o vs. Pure Servlets: It is more convenient to write (and to modify!) regular HTML than
to have plenty of println statements that generate the HTML.
o o vs. Server-Side Includes (SSI): SSI is really only intended for simple inclusions,
not for "real" programs that use form data, make database connections, and the like.
o vs. JavaScript: JavaScript can generate HTML dynamically on the client but can
hardly interact with the web server to perform complex tasks like database access and
image processing etc.
o vs. Static HTML: Regular HTML, of course, cannot contain dynamic information.

JSP, Servlet and JDBC prepared by Abdo A. @wku ,2019 1


Why Use JSP?
JavaServer Pages often serve the same purpose as programs implemented using the
Common Gateway Interface (CGI).
But JSP offer several advantages in comparison with the CGI.
Performance is significantly better because JSP allows embedding Dynamic
Elements in HTML Pages itself instead of having a separate CGI files.
JSP are always compiled before it's 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.
A JSP life cycle can be defined as the entire process from its creation till the destruction.
1. JSP Compilation:
JSP engine first checks to see whether it needs to compile the page
 Parsing the JSP.
 Turning the JSP into a servlet.
 Compiling the servlet.
2. JSP Initialization: invokes the jspInit()
 Before servicing any requests.
 performed only once and initialize database connections, open files, and create
lookup tables in the jspInit method
3. JSP Execution: _jspService(HttpServletRequest request, HttpServletResponse
response)
 The method is invoked once per a request and is responsible for generating
responses to all seven of the HTTP methods

JSP……….. HTML……………
<body color=“#FFFFFF”> <body color=“#FFFFFF”>
The time now is The time now is
<%= new java.util.Date() %> Tue Nov 5 16:15:11 PST 2002
</body> </body>

4. JSP Cleanup: jspDestroy()


 need to perform any cleanup( closing database connections or closing open files.

JSP, Servlet and JDBC prepared by Abdo A. @wku ,2019 2


A JSP life cycle can be defined as the entire process from its creation till the destruction.

JSP, Servlet and JDBC prepared by Abdo A. @wku ,2019 3


Components of a JSP Page
A. Directives are messages to a JSP container which describe what code should be
generated
 They do not send output to a client, but are used to define page attributes
 There are three types of directive tag: page, include and taglib
I. Page
 provides page-specific information to a JSP container.
 used to specify attributes for the JSP page as a whole.
Syntax as: <%@ page [attribute="value" attribute="value" ...] %>
The attributes are: language, extends, import, Session, buffer, autoflush,
isThreadSafe, info, isErrorPage, errorPage, contentType
Multiple page directives may be used on a single JSP or pages included via JSP as long as no
specific attribute, except import, occurs more than once.
<%@ page language="java" buffer="none" isThreadSafe="yes"
errorPage="/error.jsp" %>
II. include directive
 merges the contents of another file at translation time.
<%@ include file="header.html" %>
 To include a page at run time use <jsp:include page=”URL” flush=”true”/>
III. The taglib Directive
 to define custom JSP tags that look like HTML or XML tags and a tag library is a set
of user-defined tags that implement custom behavior.
 <%@ taglib uri="uri" prefix="prefixOfTag" >
B. Scripting Elements (including expressions, scriptlets, and declarations)
i. Expressions
 for accessing the value of a Java variable or other expression and merging that value
with the HTML in the page.
 The expression can have any data value, as long as it can be converted to a string.
<%= new java.util.Date() %>
out.print( new java.util.Date() );
ii. Scriptlets
• for directly inserting bits of Java code between chunks of template text.
<% for (int i=0; i<5; i++) { i%> <% } %>

JSP, Servlet and JDBC prepared by Abdo A. @wku ,2019 4


• It is identical to normal Java code (iteration, loops, and conditional statements)
but without needing a class declaration or any methods.
iii. Declarations
 To declare Java variables and methods called from an expression block within the JSP
file and must end with semicolon (;).
 do not generate output, they are used with JSP expressions or scriptlets.
<%! int pageCount = 0;
Void addCount() {
pageCount++; } %>
C. Actions
Dynamically to insert a file, reuse JavaBeans components, forward the user to another page,
or generate HTML for the Java plugin.
jsp:include - include a file at the time the page is
requested. jsp:useBean - find or instantiate a
JavaBean. jsp:setProperty - set the property of a
JavaBean.
jsp:getProperty - insert the property of a JavaBean into the output.
jsp:forward - forward the requester to a new page.
jsp:plugin - generate browser-specific code that makes an OBJECT or EMBED tag for the
Java plugin.
<jsp:include page="relative URL" flush="true" />
<jsp:forward page="date.jsp" />s
Comments
<%-- This is a hidden JSP comment --%>
<!-- This is a hidden JSP comment but can be seen by invoking the View page Source -->
Predefined Variables/Implicit Objects
To simplify code in JSP expressions and scriptlets, you are supplied with eight automatically
defined variables
The available variables are: request, response, out, session, application, config,
pageContext and page.
I. request-provides access to HTTP-protocol–specific header information sent by
the client.
request.getParameter(): to get the value of a form parameter.
request.getParameterValues(): to returns multiple values, for example
checkbox.

JSP, Servlet and JDBC prepared by Abdo A. @wku ,2019 5


request.getParameterNames(): to return complete list of all parameters in the
current request. request.getInputStream(): to read binary data stream coming
from the client.
request.getMethod() return type of method used by form
request.getRequestURI() return the values of form browser URI .
request.getHeader(headername) that returns the value of the given header
request. getHeaderNames()) that returns header name.
II. response- to manipulate HTTP-protocol–specific header information and return
data to the client.
response.setIntHeader("Refresh", 5);
response.setContentType(“text/html”);
response.sendRedirect(“http://www.google.com”);
III. out –This is the PrintWriter used to send output to the client.
•Note that out is used almost exclusively in scriptlets
IV. session -This is the HttpSession object associated with the request.
session.getAttribute("un");
session.setAttribute("user", request.getParameter("un"));
V. application-This is the ServletContext as obtained via
getServletConfig().getContext().
VI. config-This is the ServletConfig object for the page.
VII. pageContext -JSP introduced a new class called PageContext to encapsulate use of
server-specific features
Java database Connectivity (JDBC)
JDBC (the Java Database Connectivity) is the standard method of accessing databases from
Java. A JDBC driver translates standard JDBC calls into a network or database protocol or
into a database library API call that facilitates communication with the database. This
translation layer provides JDBC applications with database independence. If the back-end
database changes, only the JDBC driver need be replaced.

Type 1: JDBC-ODBC Bridge Driver

In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed on each client
machine. Most databases only supported ODBC access
Advantages: Almost any database in which ODBC driver is installed, can be accessed.
Disadvantages:

JSP, Servlet and JDBC prepared by Abdo A. @wku ,2019 6


 Performance decreased / ODBC's overhead
 Needs to be installed on the client machine.
Type 2: JDBC-Native API
 calls are converted into native C/C++ API calls, database.
 The vendor-specific driver must be installed on each client machine.
 The Oracle Call Interface (OCI) driver is an example of a Type 2 driver.
Advantage -Better performance than Type 1 since no jdbc to odbc translation is needed.
Disadvantages
o The vendor client library needs to be installed on the client machine.
o Cannot be used in internet due the client side software needed.
o Not all databases give the client side library.

Type 3: JDBC-Net pure Java

In a Type 3 driver, a three-tier approach is used to access databases. The JDBC clients use standard
network sockets to communicate with a middleware application server. The socket information is
then translated by the middleware application server into the call format required by the DBMS,
and forwarded to the database server.

This kind of driver is extremely flexible, since it requires no code installed on the client and a
single driver can actually provide access to multiple databases.

Your application server might use a Type 1, 2, or 4 driver to communicate with the database,
understanding the nuances will prove helpful.

Advantages
• Since the communication between client and the middleware server is database
independent, there is no need for the vendor db library on the client machine.
• Also the client to middleware needn't be changed for a new database.
• It can be used in internet since there is no client side software needed.
• At client side a single driver can handle any database.(It works if the middleware
supports that database)

Disadvantages
• Requires database specific coding to be done in the middle tier.
• An extra layer added may result in a time bottleneck.

JSP, Servlet and JDBC prepared by Abdo A. @wku ,2019 7


Type 4: 100% Pure Java

In a Type 4 driver, a pure Java-based driver communicates directly with the vendor's database
through socket connection. This is the highest performance driver available for the database
and is usually provided by the vendor itself. This kind of driver is extremely flexible, you
don't need to install special software on the client or server. Further, these drivers can be
downloaded dynamically. MySQL's Connector/J driver is a Type 4 driver. Because of the
proprietary nature of their network protocols, database vendors usually supply type 4 drivers.

Advantages- These drivers don't translate the requests into db request to ODBC or pass it
to client API for the database, nor do they need a middleware layer for request indirection.
Thus the performance is considerably improved.

Disadvantage – At client side, a separate driver is needed for each


database
Which Driver should be Used?
• If you are accessing one type of database, such as Oracle, Sybase, or Mysql, the
preferred driver type is 4.
• If your Java application is accessing multiple types of databases at the same time, type
3 is the preferred driver.
• Type 2 drivers are useful in situations, where a type 3 or type 4 driver is not available
yet for your database.
• The type 1 driver is not considered a deployment-level driver, and is typically used for
development and testing purposes only.

Connecting to Database

Before you can use JDBC to access a database, you must first establish a connection to the
database.

1. Loading drivers. The first step is Loading drivers involves registering the driver
class so the class is available.

To register the MySQL connector, use this statement:


Class.forName(“com.mysql.jdbc.Driver”);
To register the standard ODBC driver, use this statement instead:
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);

JSP, Servlet and JDBC prepared by Abdo A. @wku ,2019 8


Note that the forName method throws ClassNotFoundException, so you have to enclose this
statement in a try/catch block. You can also register drivers with
DriverManager.registerDriver() method.

try {
Driver myDriver = new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver( myDriver );
}catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
A driver class loaded in this fashion should create an instance of itself and register it with the
driver manager. To use the JDBC-ODBC bridge in a Java application, a suitable ODBC data
source must be configured. The data source should be configured as a System DSN, not a
User DSN. The driver class name is sun.jdbc.odbc.JdbcOdbcDriver if the Sun JVM is being used.

Microsoft supplies ODBC drivers for its Access database product, as well as dBase, Excel,
FoxPro, and a number of others, including a text driver that can use ordinary text files (.txt
and .csv) as a simple database system.

2.Establishing Connections. After you register the driver class, you can call the static
getConnection method of the DriverManager class to open the connection.

This method takes three String parameters: the database URL, the user name, and a password.
Here’s an example:
 Class.forName("com.mysql.jdbc.Driver "); //step1
 String url = “jdbc:mysql://localhost:3306/gallery”;
 con = DriverManager.getConnection(url, “root”, “vertrigo”);//step2

DriverManager provides three different methods to get connection:

 DriverManager.getConnection(String url)
 DriverManager.getConnection(String url, String userID, String password)
 DriverManager.getConnection(String url, Properties prop)

Internally, DriverManager uses the same private worker method to handle each of these
methods.
The driver manager maintains a list of registered drivers.

JSP, Servlet and JDBC prepared by Abdo A. @wku ,2019 9


The key argument to DriverManager.getConnection() is a JDBC URL, which is a string with
three components separated by semicolons:
<protocol>:<subprotocol>:<subname> Where protocol is always jdbc.
subprotocol is a vendor-specific string that identifies the driver to be used.
For example, the JDBC-ODBC bridge uses the reserved value odbc as its
subprotocol. subname identifies the specific database to connect to.
This string contains whatever the driver needs to identify the database.
Examples of JDBC URLs are Jdbc:odbc:finance
Querying a Database
After you establish a connection, you can execute select statements to retrieve data.
To do so, you have to use several classes and interfaces:
3. Creating statements: the Connection class has two methods you’re likely to use.
The createStatement() method returns a Statement object, which you then use to
execute statements. The close() method closes the connection
4. Executing statements: the Statement interface contains the methods necessary to send
statements to the database for execution and return the results.
Use executeQuery() method to execute a select statement
Use executeUpdate() method to execute an insert, update, or delete statements.
5. Processing ResultSet: the ResultSet interface represents rows returned from a query.
It provides methods you can use to move from row to row and to get the data for a
column.
Statement createStatement (int type, int concur);

The first parameter of the createStatement o ResultSet.TYPE_FORWARD_ONLY


method specifies the type of result set that is o ResultSet.TYPE_SCROLL_INSENSITIVE
created, and can be one of the following: o ResultSet.TYPE_SCROLL_SENSITIVE
The second parameter indicates whether o ResultSet.CONCUR_READ_ONLY
the result set is read-only or updatable, and o ResultSet.CONCUR_UPDATABLE
can be one of the following:
statement = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
Executing a select statement  ResultSet rows = st.executeQuery(select);

6. The last step is to close the connection

JSP, Servlet and JDBC prepared by Abdo A. @wku ,2019 10


Navigating through the ResultSet
The ResultSet object returned by the executeQuery statement contains all the rows that are
retrieved by the select statement. You can only access one of those rows at a time. The
result set maintains a pointer called a cursor to keep track of the current row. You can use
the methods to move the cursor through a result set.
boolean absolute(int row)
If the row number is positive, the cursor moves to the given row number with respect to the
beginning of the result set. The first row is row 1, the second is row 2, and so on.

If the given row number is negative, the cursor moves to an absolute row position with respect
to the end of the result set. For example, calling the method absolute(-1) positions the cursor
on the last row and calling the method absolute(-2) moves the cursor to the next-to-last row,
and so on. An attempt to position the cursor beyond the first/last row in the result set leaves
the cursor before the first row or after the last row.

Calling absolute(1) is the same as calling first().


Calling absolute(-1) is the same as calling last().
Update Database
For a result set to be updated, it must have been produced by a Statement object created
with a concurrency type of ResultSet.CONCUR_UPDATABLE.
JDBC provides updateXXX() methods, where XXX is the JDBC data type, similar
to the existing getXXX() methods.
These methods take a column number or column name parameter, and a value
parameter.
rs.absolute(10);
double mySalary = rs.getDouble(“SALARY”);
mySalary *= 2.0;
rs.updateDouble(“SALARY”, mySalary);
rs.updateString(“HOME_PHONE”, unlisted);
rs.updateRow();
The following example illustrates this:
Inserting New Rows
New rows can be added to the result set and the underlying table with insertRow().
This involves a special cursor position known as the insert row.
The following example illustrates how this works:

JSP, Servlet and JDBC prepared by Abdo A. @wku ,2019 11


rs.moveToInsertRow();
rs.updateString(“name”, “David Jacques”);
rs.updateInt(“telephone”, 8954578693567);
rs.insertRow();
The above update can be done by using SQL statements.
Here is an example:
sql = “insert into customers values(‘David Jacques’, 8954578693567)”;
int i = stmt.executeUpdate(sql);

Using PreparedStatement Object


The PreparedStatement interface extends the Statement interface which gives you added
functionality with a couple of advantages over a generic Statement object.
This statement gives you the flexibility of supplying arguments dynamically.

PreparedStatement pstmt = null;


String SQL = "Update Employees SET age = ? WHERE id = ?";
pstmt = con.prepareStatement(SQL);
All parameters in JDBC are represented by the ? symbol, which is known as the parameter
marker. You must supply values for every parameter before executing the SQL statement.

The setXXX() methods bind values to the parameters. If you forget to supply the values, you
will receive an SQLException. Each parameter marker is referred to by its ordinal position.
All of the Statement object's methods for interacting with the database execute(),
executeQuery(), and executeUpdate() also work with the PreparedStatement object.
String SQL = " INSERT INTO SECURITY VALUES (?, ?)";
pstmt = con.prepareStatement(SQL); pstmt.setString(1, “John”);
pstmt.setString(2, “abc”);
int suc = pstmt.executeUpdate();

Batch Updating

JDBC 2.0 introduced the capability to submit a group of update statements to be executed as a
batch. In some cases, this can represent a significant performance improvement.
The methods used in connection with batch updates are these:
clearBatch resets a batch to the empty state.
addBatch adds an update statement to the batch.
executeBatch submits the batch and collects update counts.

JSP, Servlet and JDBC prepared by Abdo A. @wku ,2019 12


Cookies and Session
The most widely used technique for persistent client data storage involves HTTP cookies. A
cookie is a small, named data element the server passes to a client with a Set-Cookie header as
part of the HTTP response. The client is expected to store the cookie and return it to the
server with a Cookie header on subsequent requests to the same server. Along with the name
and value, the cookie may contain

• An expiration date, after which the client is no longer expected to retain the cookie.
If no date is specified, the cookie expires as soon as the browser session ends.
• A domain name, such as example.com, which restricts the subset of URLs for which
the cookie is valid. If unspecified, the cookie is returned with all requests to the
originating Web server.
• A path name that further restricts the URL subset.
• A secure attribute, which, if present, indicates the cookie should only be returned if
the connection uses a secure channel, such as SSL.
The Anatomy of a Cookie- Cookies are usually set in an HTTP header.
A JSP that sets a cookie might send headers that looks something like this:
HTTP/1.1 200 OK
Date: Fri, 04 Feb 2013 21:03:38 GMT
Server: Apache/1.3.9 (UNIX) PHP/5.0
Set-Cookie: name=xyz; expires=Friday, 04-Feb-07 22:03:38 GMT; path=/;
domain=tutorialspoint.com
Connection: close
Content-Type: text/html
As you can see, the Set-Cookie header contains a name value pair, a GMT date, a path and a
domain. The name and value will be URL encoded. The expires field is an instruction to the
browser to "forget" the cookie after the given time and date.

Setting cookies with JSP involves three steps:

A. Creating a Cookie object:


You call the Cookie constructor with a cookie name and a cookie value, both of which are
strings.
Cookie ck = new Cookie("key","value");
Keep in mind, neither the name nor the value should contain white space or any of the
following characters: [ ] ( ) = , " / ? @ : ;

JSP, Servlet and JDBC prepared by Abdo A. @wku ,2019 13


B. Setting the maximum age:
You use setMaxAge to specify how long (in seconds) the cookie should be valid.
Following would set up a cookie for 24 hours.
cookie.setMaxAge(60*60*24); C. Sending the Cookie into
the HTTP response headers:
You use response.addCookie to add cookies in the HTTP response header as follows:
response.addCookie(ck);
When Web Server invokes a jsp, the cookies sent by the browser are included in the request
object. These cookies are retrieved as an array of cookie objects using the following code:
Cookie cook[] = request.getCookies();
Once you have the cookie objects, you can search for your specific cookie.
You can use the getName() method to look at each cookie’s name:
String foo = cook[0].getName();
If the user’s browser does not accept cookies it does not include cookies in subsequent
requests. In this case, the result of request.getCookies() returns null (or an array without the
cookie you added). In general, the jsp author has no way to determine in advance whether a
particular client will accept cookies.

Reading Cookies with JSP -To read cookies, call the getCookies( ) method of request
object.

Then cycle through the array, and use getName() and getValue() methods to access each
cookie and associated value.

JSP, Servlet and JDBC prepared by Abdo A. @wku ,2019 14


<html>
<head> </head>
<body>
<h1>Reading Cookies</h1>
<%
Cookie ck = null;
Cookie[] cookies = null;
// Get an array of Cookies associated with this domain
cookies = request.getCookies();
if( cookies != null ){
out.println("<h2> Found Cookies Name and Value</h2>");
for (int i = 0; i < cookies.length; i++){
ck = cookies[i];
out.print("Name : " + ck.getName( ) + ", ");
out.print("Value: " + ck.getValue( ) + " <br/>");
}
}
else
out.println("<h2>No cookies founds</h2>");
%>
</body>
</html>
Delete Cookies with JSP -To delete cookies is very simple with the following three
steps: Read an already existing cookie and store it in Cookie object.
Set cookie age as zero using setMaxAge() method to delete an existing cookie.
Add this cookie back into response header.
<% Cookie ck = null;
Cookie[] cookies = null;
cookies = request.getCookies();
if( cookies != null ){
for (int i = 0; i < cookies.length; i++)
{ ck = cookies[i];
if((ck.getName( )).compareTo("first_name") == 0 ){
ck.setMaxAge(0);
response.addCookie(ck);
out.print("Deleted cookie: " + ck.getName( ) + "<br/>");
} }
}else{
out.println("<h2>No cookies founds</h2>");
} %>

JSP, Servlet and JDBC prepared by Abdo A. @wku ,2019 15


Creating Sessions
In a JSP page, session creation is automatic. If a JSP page doesn’t need to use a session as
<%@ page session=”false” %>
 This relieves the servlet engine from having to create and maintain a session when it
isn’t needed.
 When the session is first created, the client (Web browser) doesn’t yet know about it.
 When the session ID has been sent to the client and the client sends it back in the next
request, the client is said to join the session.
 A servlet or JSP page can detect whether this has happened with the isNew() method:
if (session.isNew()) {
// store values on session
}
session.isNew() is true if the session is newly created and the client hasn’t yet been
informed or if the client has been informed, but chooses not to participate. Objects are
bound to a session with the setAttribute() method:
 session.setAttribute(attribute, value);
 Objects are bound to a session with the setAttribute() method:
o session.setAttribute(attribute, value);
 Example:
 session.setAttribute("username", request.getParameter(“un”));
 Objects can be retrieved from a session with the getAttribute() method:
 String userID = (String) session.getAttribute(attribute);
 Usually, if you stored an attribute in a session, you know its name and type, and you can
request it directly in this manner.
 You can also get a list of attribute names, however, from the getAttributeNames() method
out.println("Objects in this session:");
out.println("<PRE>");
Enumeration enames = session.getAttributeNames();
while (enames.hasMoreElements()) {
String name = (String) enames.nextElement();
Object value = session.getAttribute(name);
out.println(name + " = " + value);
}
out.println("</PRE>");

JSP, Servlet and JDBC prepared by Abdo A. @wku ,2019 16


Destroying Sessions

Once created, a session ordinarily persists until it times out or is shut down. Timeout refers
to the maximum length of time between requests that the session will remain valid. This is an
important consideration because the server has no way of knowing whether a client has
finished working with a session, other than by being told explicitly or by waiting a fixed length
of time.

Applications can use the setMaxInactiveInterval() method to set time period:

session.setMaxInactiveInterval(180);

The argument supplied to setMaxInactiveInterval() is a number of seconds.

The current value can be obtained with getMaxInactiveInterval(). If a negative value is


specified, the session never times out. When an object is no longer needed, it can be
removed from the session with removeAttribute(): session.removeAttribute("username");
This happens automatically when the session is closed, but situations may occur when an
attribute needs to be removed earlier than this. In some cases, a definite end to the session
can be provided. session.invalidate();

This method marks the session as being inactive and unbinds all objects bound

to it. Example: // check to see if the session is new

if (session.isNew()) {
//we send a redirect to login page
response.sendRedirect("http://www.learnweblogic.com/login"); }
Use sessions to mark login status. Create a new session only on login and look for a session
to confirm login status. When the user logs out, invalidate the session. Use filters to apply
security checks consistently throughout your Web application.

JSP, Servlet and JDBC prepared by Abdo A. @wku ,2019 17

You might also like