Unit 3-JSP&JDBC
Unit 3-JSP&JDBC
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.
if (isOrderInfoValid(request)) {
saveOrderInfo(request);
out.println("<html>");
out.println(" <head>");
out.println(" <title>Order Confirmation</title>");
out.println(" </head>");
out.println(" <body>");
out.println(" <h1>Order Confirmation</h1>");
renderOrderInfo(request);
out.println(" </body>");
out.println("</html>");
}
}
JSP lets you solve these problems “by separating the request
processing and business logic code from the presentation”, as
illustrated in Figure 1.1. Instead of embedding HTML in the
code, you place all static HTML in JSP pages, just as in a
regular web page, and add a few JSP elements to generate the
dynamic parts of the page. The request processing can remain
the domain of servlet programmers, and the business logic can
be handled by JavaBeans and Enterprise JavaBeans (EJB)
components.
Advantages of JSP:
Introduction to JSP
JSP Overview
OUTPUT:
Directive,
Aaction, and
Scripting Elements.
1. Scriptlets
2. Expressions
3. Declarations
LIFE CYCLE
JSP Processing/ Life Cycle of JSP:
i) Translation Phase:
</body>
</html>
Example:
Main.html
a.jsp
Output:
JSP Expressions
Format
◦ <%= Java Expression %>
Result
◦ expression placed in _jspService inside out.print
Examples
◦ Current time: <%= new java.util.Date() %>
◦ <%= request.getRemoteHost() %>
XML-compatible syntax
◦ <jsp:expression>Java
Expression</jsp:expression>
Example:
Output:
Predefined Variables
request
◦ The HttpServletRequest (1st argument to
service/doGet)
response
◦ The HttpServletResponse (2nd arg to
service/doGet)
out
◦ The Writer (a buffered version of type JspWriter)
used to send output to the client
session
◦ The HttpSession associated with the request
(unless disabled with the session attribute of the
page directive)
application
◦ The ServletContext (for sharing data) as obtained
via getServletContext().
21 Chapter 3 - JSP and JDBC
FULL STACK TECHNOLOGIES
JSP Scriptlets
Format
◦ <% Java Code %>
Result
◦ Code is inserted verbatim into servlet's _jspService
Example
◦ <%
String queryData = request.getQueryString();
out.println("Attached GET data: " + queryData);
%>
◦ <% response.setContentType("text/plain"); %>
XML-compatible syntax
<jsp:scriptlet>Java Code</jsp:scriptlet>
JSP Declarations
Format
◦ <%! Java Code %>
Result
◦ Code is inserted verbatim into servlet's class
definition, outside of any existing methods
Examples
◦ <%! private int someField = 5; %>
◦ <%! private void someMethod(...) {...} %>
XML-compatible syntax
◦ <jsp:declaration>Java Code</jsp:declaration>
Example:
Output:
The code written inside the jsp declaration tag is placed outside
The jsp scriptlet tag can The jsp declaration tag can
method. method.
field and printing the value of the declared field using the jsp
expression tag.
index.jsp
1. <html>
2. <body>
5. </body>
6. </html>
this method from the jsp expression tag. But we can also use
index.jsp
1. <html>
2. <body>
3. <%!
5. return n*n*n*;
6. }
25 Chapter 3 - JSP and JDBC
FULL STACK TECHNOLOGIES
7. %>
9. </body>
10. </html>
Object Description
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.
Method Description
The following config method is the only one you might ever
use, and its usage is trivial:
config.getServletName();
pageContext.removeAttribute("attrName", PAGE_SCOPE);
The page object is really a direct synonym for the this object.
INTRODUCTION TO JDBC
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.
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 −
With type 4 drivers, the user needs a different driver for each
database.
Database Connectivity
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.
Steps to connect database in java using JDBC are given
below:
1. Load the JDBC driver.
2. Connection.
3. Statement.
4. Execute statement.
5. Close database connection.
Class.forName("driverClassName");
Class.forName("com.mysql.jdbc.Driver");
2. Create connection:
Second step is to open a database connection. DriverManager
class provides the facility to create a connection between a
database and the appropriate driver.To open a database
connection we can call getConnection() method of
DriverManager class.
Syntax:
Connection connection = DriverManager.getConnection(url,
user, password);
3. Create statement:
The statement object is used to execute the query against the
database. Connection interface acts as a factory for statement
object. A statement object can be any one of the Statement,
CallableStatement, and PreparedStatement types .To create a
statement object we have to call createStatement() method of
Connection interface. Connection interface also provides the
4. Execute statement:
Statement interface provides the methods to execute a
statement.
To execute a statement for select query use below:
Syntax:
ResultSet resultSet = stmt.executeQuery(selectQuery);
Example
<%@page import="java.sql.*" %>
<%
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
out.println("<h1>");
out.println("Loaded the Driver");
Connection
c=DriverManager.getConnection("jdbc:oracle:thin:@localhost:15
21:xe","system","manager");
out.println("Connect set");
}
catch(Exception e)
{
out.println(e.toString());
}
%>
Studying Javax.sql.* package
Provides the API for server side data source access and
processing from the JavaTM programming language. This
package supplements the java.sql package.
The javax.sql package provides for the following:
1. The DataSource interface as an alternative to
the DriverManager for establishing a connection with a
data source
2. Connection pooling and Statement pooling
3. Distributed transactions
4. Rowsets
Applications use the DataSource and RowSet APIs directly, but
the connection pooling and distributed transaction APIs are
used internally by the middle-tier infrastructure.
CRUD OPERATIONS.
Create a table
<%@page import="java.sql.*" %>
<%
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
out.println("<h1>");
out.println("Loaded the Driver");
Connection
c=DriverManager.getConnection("jdbc:oracle:thin:@localhost:15
21:xe","system","manager");
out.println("Connect set");
Statement stmt=c.createStatement();
String sql="CREATE TABLE studentbalu " + "(sno INTEGER not
Null,"+
" sname VARCHAR2(20)," +
" age
VARCHAR2(20))";
stmt.executeUpdate(sql);
System.out.println("Create table in given database...");
}
catch(Exception e)
{
out.println(e.toString());
}
%>
Insert operation
<%@page import="java.sql.*" %>
<%
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
out.println("<h1>");
out.println("Loaded the Driver");
Connection
c=DriverManager.getConnection("jdbc:oracle:thin:@localhost:15
21:xe","system","manager");
out.println("Connect set");
Statement stmt=c.createStatement();
String sql= sql = "INSERT INTO studentbalu VALUES (101,
'balu', 25)";
stmt.executeUpdate(sql);
System.out.println("Inserted records into the table...");
}
catch(Exception e)
{
out.println(e.toString());
}
%>
Update operation
<%@page import="java.sql.*" %>
<%
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
out.println("<h1>");
out.println("Loaded the Driver");
Connection
c=DriverManager.getConnection("jdbc:oracle:thin:@localhost:15
21:xe","system","manager");
out.println("Connect set");
Statement stmt=c.createStatement();
String sql= "UPDATE studentbalu " +
"SET age = 42 WHERE sno=101";
stmt.executeUpdate(sql);
System.out.println("Updated records into the table...");
}
catch(Exception e)
{
out.println(e.toString());
}
%>
Delete operation
<%@page import="java.sql.*" %>
<%
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
out.println("<h1>");
}
catch(Exception e)
{
out.println(e.toString());
}
%>
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
Output:
Newuser.jsp