Chapter 3 & 4 JSP& JDBC Handout 2019
Chapter 3 & 4 JSP& JDBC Handout 2019
Chapter 3 & 4 JSP& JDBC Handout 2019
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……….. 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>
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:
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.
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.
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.
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.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.
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.
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.
• 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.
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.
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.
session.setMaxInactiveInterval(180);
This method marks the session as being inactive and unbinds all objects bound
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.