Professional Documents
Culture Documents
Introduction To JSP
Java Server Page (JSP) is a technology for controlling the content or appearance of Web pages
through the use of servlets, small programs that are specified in the Web page and run on the Web
server to modify the Web page before it is sent to the user who requested it.
Sun Microsystems, the developer of Java, also refers to the JSP technology as the Servlets
application program interface (API). JSP is comparable to Microsoft's Active Server Page (ASP)
technology. Whereas a Java Server Page calls a Java program that is executed by the Web server,
an Active Server Page contains a script that is interpreted by a script interpreter before the page is
sent to the user.
An HTML page that contains a link to a Java servlet is sometimes given the file name suffix
of .JSP.
Characteristics:
JSPs can be used to create servlets, by including specific tags in the JSP code. In this way, they
provide a fast technology to create dynamic pages.
JSP pages share the Write Once, Run Anywhere™ characteristics of Java technology.
JSP is a specification, not a product. Developers are able to choose a “best of breed”
approach.
JSP pages are compiled, not interpreted, which can lead to better performance.
JSP pages support both scripting and access to the full Java language and can be extended
through the use of custom tags.
Language Structure:
Comment tag: A hidden comment marks text or lines that the JSP container
should ignore. A hidden comment is useful when you want to comment out
part of your JSP page. The JSP container does not process anything within
JSP Syntax:
Example:
Scriptlet tag: A scriptlet can contain any number of language statements, variable or method
declarations, or expressions that are valid in the page scripting language. Within a scriptlet, we
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. Write any other statement valid in the scripting language used in the JSP page.
Any text, HTML tags, or JSP elements we write must be outside the scriptlet. Scriptlets are
executed at request time, when the JSP container processes the request.
JSP Syntax:
<% code fragment %>
Examples:
<%
String name = null; int a=10,b=20;
if (a>b)
out.println(a+” is big”); else
out.println(b+” is big”);
%>
Declaration tag: A declaration declares one or more variables or methods that you can use in
Java code later in the JSP page. We must declare the variable or method before you use it in the
JSP page.
We can declare any number of variables or methods within one declaration element, as long
as you end each declaration with a semicolon.
JSP Syntax:
<%! declaration; [ declaration; ]+ ... %>
Examples:
<%! int i = 0; %> <%! int a, b, c; %>
<%! Circle a = new Circle(2.0); %>
The main difference between scriptlet tag and decleration tag is scriptlet tag can only declare
variables not methods. But decleration tag can declare variables as well as methods.
Expression tag: An expression element contains a scripting language expression that is
evaluated, converted to a String, and inserted into the response where the expression appears in
the JSP page. The expression element can contain any expression that is a valid page scripting
language.
JSP Syntax
<%= expression %> Examples
<%! int a = 2+3; %> Value of a is <%= a %>
Directive tag: 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.
Syntax:
<%@ directive attribute="value" %>
Directives can have a number of attributes which you can list down as key-value pairs and
separated by commas.
The blanks between the @ symbol and the directive name, and between the last attribute
and the closing %>, are optional.
There are three types of directive tag:
Directive Description
<%@ page ... %> Defines page-dependent attributes, such as scripting
language, error page, and buffering requirements.
<%@ include ... %> Includes a file during the translation phase.
<%@ taglib ... %> Declares a tag library, containing custom actions,
used in the page
The page Directive: The page directive applies to an entire JSP page and any of its static
include files, which together are called a translation unit.
A static include file is a file whose content becomes part of the calling JSP page. The page
directive does not apply to any dynamic resources
We can use the page directive more than once in a translation unit, but you can only use each
attribute, except import, once
Syntax:<%@ page attribute="value" %>
Advantages:
JSP uses simplified scripting language based syntax for embedding HTML into JSP.
JSP pages easily combine static templates, including HTML or XML fragments, with code
that generates dynamic content.
JSP containers provide easy way for accessing standard objects and actions.
JSP use HTTP as default request /response communication paradigm and thus make JSP
ideal as Web Enabling Technology.
JSP pages are compiled dynamically into servlets when requested, so page authors can
easily make updates to presentation code. JSP pages can also be precompiled if desired.
JSP tags for invoking JavaBeans components manage these components completely,
shielding the page author from the complexity of application logic.
Developers can offer customized JSP tag libraries that page authors access using an XML-
like syntax.
Web authors can change and edit the fixed template portions of pages without affecting the
application logic. Similarly, developers can make logic changes at the component level
without editing the individual pages that use the logic.
Comparison Between Java And Java Server Pages:
Writing jsp program: To create the first jsp page, write some html code as given below, and
save it by .jsp extension. Example: index.jsp.
Here in this example we are using the scriptlet tag to put java code in the JSP page.
<html>
<body>
<% out.print(2*5); %> </body>
</html>
Put it in a folder and paste the folder in the web-apps directory in apache tomcat to run the jsp
page.
The directory structure of JSP page is same as servlet. We contains the jsp page outside the
WEB-INF folder or in any directory.
The directory structure of a web application consists of two parts. A private directory called
WEB-INF
A public resource directory which contains public resource folder. WEB-INF folder consists
of
1. web.xml
2. classes directory
3. lib directory
<html>
<head><title>Student Information</title> <%@page import="java.sql.*,java.util.*"%> </head>
<body bgcolor="DeepPink"> <%
try{
Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver"); String url = "jdbc:odbc:abc";
Connection con = DriverManager.getConnection(url,"",""); Statement stmt =
con.createStatement(); stmt.executeUpdate("insert into student values('abc',21);");
stmt.close();
con.close();
out.println("Records successfully inserted");}
catch(Exception e) { e.printStackTrace();}%>
</body></html>
The JDBC (Java Database Connectivity) API defines interfaces and classes for writing database
applications in Java by making database connections. Using JDBC you can send SQL, PL/SQL
statements to almost any relational database. JDBC is a Java API for executing SQL statements
and supports basic SQL functionality. It provides RDBMS access by allowing you to embed
SQL inside Java code. Because Java can run on a thin client, applets embedded in Web pages
can contain downloadable JDBC code to enable remote database access. You will learn how to
create a table, insert values into it, query the table, retrieve results, and update the table with the
help of a JDBC Program example.
Although JDBC was designed specifically to provide a Java interface to relational databases, you
may find that you need to write Java code to access non-relational databases as well.
JDBC Architecture
Java application calls the JDBC library. JDBC loads a driver which talks to the database. We can
change database engines without changing database code.
JDBC Basics – Java Database Connectivity Steps
Before you can create a java jdbc connection to the database, you must first import the
java.sql package.
import java.sql.*; The star ( * ) indicates that all of the classes in the package java.sql are to be
imported.
?
1 try {
2 Class.forName(”sun.jdbc.odbc.JdbcOdbcDriver”); //Or any other driver
3 }
4 catch(Exception x){
5 System.out.println( “Unable to load the driver class!” );
6 }
2. Creating a oracle jdbc Connection
The JDBC DriverManager class defines objects which can connect Java applications to a JDBC
driver. DriverManager is considered the backbone of JDBC architecture. DriverManager class
manages the JDBC drivers that are installed on the system. Its getConnection() method is used to
establish a connection to a database. It uses a username, password, and a jdbc url to establish a
connection to the database and returns a connection object. A jdbc Connection represents a
session/connection with a specific database. Within the context of a Connection, SQL, PL/SQL
statements are executed and results are returned. An application can have one or more
connections with a single database, or it can have many connections with different databases. A
Connection object provides metadata i.e. information about the database, tables, and fields. It
also contains methods to deal with transactions.
JDBC URL Example:: jdbc: <subprotocol>: <subname>•Each driver has its own subprotocol
•Each subprotocol has its own syntax for the source. We’re using the jdbc odbc subprotocol, so
the DriverManager knows to use the sun.jdbc.odbc.JdbcOdbcDriver.
?
try{
1
Connection dbConnection=DriverManager.getConnection(url,”loginName”,”Password”)
2
}
3
catch( SQLException x ){
4
System.out.println( “Couldn’t get connection!” );
5
}
6
Creating a jdbc Statement object
Once a connection is obtained we can interact with the database. Connection interface defines
methods for interacting with the database via the established connection. To execute SQL
statements, you need to instantiate a Statement object from your connection object by using the
createStatement() method.
Statement interface defines methods that are used to interact with database via the execution of
SQL statements. The Statement class has three methods for executing statements:
executeQuery(), executeUpdate(), and execute(). For a SELECT statement, the method to use is
executeQuery . For statements that create or modify tables, the method to use is executeUpdate.
Note: Statements that create a table, alter a table, or drop a table are all examples of DDL
statements and are executed with the method executeUpdate. execute() executes an SQL
statement that is written as String object.
ResultSet provides access to a table of data generated by executing a Statement. The table rows
are retrieved in sequence. A ResultSet maintains a cursor pointing to its current row of data. The
next() method is used to successively step through the rows of the tabular results.
ResultSetMetaData Interface holds information on the types and properties of the columns in a
ResultSet. It is constructed from the Connection object.
?
1 import javax.swing.JOptionPane;
2
3 public class TestJDBCDriverInstallation_Oracle {
4
5 public static void main(String[] args) {
6 StringBuffer output = new StringBuffer();
7 output.append(”Testing oracle driver installation \n”);
8 try {
9 String className = “sun.jdbc.odbc.JdbcOdbcDriver”;
10 Class driverObject = Class.forName(className);
11 output.append(”Driver : “+driverObject+”\n”);
12 output.append(”Driver Installation Successful”);
13 JOptionPane.showMessageDialog(null, output);
14 } catch (Exception e) {
15 output = new StringBuffer();
16 output.append(”Driver Installation FAILED\n”);
17 JOptionPane.showMessageDialog(null, output);
18 System.out.println(”Failed: Driver Error: ” + e.getMessage());
19 }
20 }
21 }
Download JDBC Sample Code
Java JDBC Connection Example, JDBC Driver Example
?
1 import java.sql.Connection;
2 import java.sql.DatabaseMetaData;
3 import java.sql.DriverManager;
4 import java.sql.SQLException;
5
6 public class JDBCDriverInformation {
7 static String userid=”scott”, password = “tiger”;
8 static String url = “jdbc:odbc:bob”;
9 static Connection con = null;
10 public static void main(String[] args) throws Exception {
11 Connection con = getOracleJDBCConnection();
12 if(con!= null){
13 System.out.println(”Got Connection.”);
14 DatabaseMetaData meta = con.getMetaData();
15 System.out.println(”Driver Name : “+meta.getDriverName());
16 System.out.println(”Driver Version : “+meta.getDriverVersion());
17
18 }else{
19 System.out.println(”Could not Get Connection”);
20 }
21 }
22
23 public static Connection getOracleJDBCConnection(){
24
25 try {
26 Class.forName(”sun.jdbc.odbc.JdbcOdbcDriver”);
27 } catch(java.lang.ClassNotFoundException e) {
28 System.err.print(”ClassNotFoundException: “);
29 System.err.println(e.getMessage());
30 }
31
32 try {
33 con = DriverManager.getConnection(url, userid, password);
34 } catch(SQLException ex) {
35 System.err.println(”SQLException: ” + ex.getMessage());
36 }
37
38 return con;
39 }
40