You are on page 1of 11

JAVA SERVER PAGES PROGRAMMING CONCEPTS

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

the <%-- and --%> characters.

JSP Syntax:

<%-- comment --%>

Example:

<%-- This comment will not be inclueded in the response --%>

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:

Java Server Pages


Java
Java is a programming language that JSP uses the syntax of java
can use the java to design data programming for server side scripting.
application software
Java file converts to byte code after JSP file converts to servlets code.
compilation
Java applets are client-side scripts JSP is server-side scripting that
that are created logically on a system requires the users webhost to provide
using java language and then a servlets runner and support for all
compiled and uploaded the languages.
Java programs allow the applet to User browser does not need anything
run on the browser is includes on to be turned on or enabled to run
most computer system pages coded
Java does need the support of JSP need support of servlets to run
servlets. the code.

Various Aspects Of Java Server Pages Programs


JSP provides programmers a simple means to embed java code in HTML code, whereas java
Servlets outputs HTML code. And all JSP code will be converted into servlets code by the servlets
container at the time of executing JSP files

JSP and Servelets:


Even though all jsp files are converted into servelets the jsp file is easy to deploy
because the JSP engine performs the recompilation for java code automatically. In
servlets the response(the HTML content) is written using Streams println() method i.e.
Html program is written with in java code. But in JSP the java logic is embaded within
html content.
JSP and ASP:
The main difference is the jsp is a product that provides platform independent so that it can run
on any JVM-enabled operating system. But the ASP is Microsoft product is not supporting
platform independence so that it only runs under Windows platform.

Writing And Executing JSP Programs

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

Executing JSP Programs:

Follow the following steps to execute this JSP page:


Start the server put the jsp file in a folder and deploy on the server visit the browser by the url
http://localhost:portno/contextRoot/jspfile e.g. http://localhost:8888/myapplication/index.jsp
Life Cycle Of JSP
JSP’s life cycle can be grouped into following phases.
JSP Page Translation:
A java servlet file is generated from the JSP source file. This is the first step in its tedious multiple
phase life cycle. In the translation phase, the container validates the syntactic correctness of the
JSP pages and tag files. The container interprets the standard directives and actions, and the
custom actions referencing tag libraries used in the page.
JSP Page Compilation:
The generated java servlet file is compiled into a java servlet class. Note: The translation of a
JSP source page into its implementation class can happen at any time between initial deployment
of the JSP page into the JSP container and the receipt and processing of a client request for the
target JSP page.
Class Loading:
The java servlet class that was compiled from the JSP source is loaded into the container.
Execution phase:
In the execution phase the container manages one or more instances of this class in response to
requests and other events. The interface JspPage contains jspInit() and jspDestroy(). The JSP
specification has provided a special interface HttpJspPage for JSP pages serving HTTP requests
and this interface contains _jspService().
Initialization:
jspInit() method is called immediately after the instance was created. It is called only once
during JSP life cycle.
_jspService() execution:
This method is called for every request of this JSP during its life cycle. This is where it serves
the purpose of creation. Oops! it has to pass through all the above steps to reach this phase. It
passes the request and the response objects. _jspService() cannot be overridden.
jspDestroy() execution:
This method is called when this JSP is destroyed. With this call the servlet serves its purpose
and submits itself to heaven (garbage collection). This is the end of jsp life cycle.
jspInit(), _jspService() and jspDestroy() are called the life cycle methods of the JSP.

Writing Dynamic Programs Using JSP.


Generating dynamic content in Web applications is important when the content must reflect the
most current and available data and personalized information. One of the main advantages of
JavaServer Pages is the ability to generate dynamic content. JSPs generate dynamic HTML pages
by using Java control structures like for loops and if statements. As a result, forms can be
generated dynamically following some specified logical layout.
Example: Multilayered dynamic jsp program to find biggest of three numbers Big3.html
<html>
<head><title>Find the biggest among three numbers</title> </head>
<body bgcolor="orange">
<h1> Find the biggest among three numbers </h1>
<form action="big3.jsp" method="post">
<table>
<tr><td>Enter the First Number :</td> <td><input type="text" name="num1" ></td></tr>
<tr><td>Enter the Second Number :</td> <td><input type="text" name="num2"
></td></tr>
<tr><td>Enter the Third Number : </td> <td><input type="text" name="num3" ></td></tr>
<tr><td><input type="submit" value="Find Big" ></td></tr> </table>
</form></body></html>
In the above program user input three numbers in the text box and press find big button when the
button is pressed. Then form tag post the values that entered in text box to jsp program which is
mentioned in form tag i.e. big3.jsp
Big3.jsp <%@ page import="java.lang.*" %>
<html>
<body bgcolor="orange"> <%
int num1=Integer.parseInt(request.getParameter("num1"));
int num2= Integer.parseInt(request.getParameter("num2"));
int num3= Integer.parseInt(request.getParameter("num3"));
%>
<h1>Biggest Number is:
<%if ((num1>num2) && (num1>num3)) out.println(num1);
else if (num2>num3) out.println(num2);
else out.println(num3);%></h1></body></html>
In jsp program the values accepted from html page is in string form it us converted into
integer and then perform the logic and then below output is produced.

Database program through JSP


Accessing database in JSP is same as in java programs. To execute database program in JSP we
have to know the following.
Structure of JDBC:
Create a Connection object: Calling a getConnection class method of the DriverManager class
creates a Connection object, and establishes a connection with a database.
Generate a Statement object: The Connection object generates a Statement object.
Pass a SQL statement: A SQL statement that executes within the database environment is passed
to the Statement object.
Loop over the rows of the result set: A Boolean value returns to indicate whether there is a row
to advance to.
For each row, retrieve the values: We can use the getData( ) method to get the value from a
column on the current row.
Configuring Jdbc Odbc Bridge:
Click Start button select settings. Select control panel in settings. Select Switch to classic view
in control panel, Select administrative tool and select data ources(ODBC) in administrative
tools.
Select System DSN in data sources add Microsoft Access Driver(*.mdb,*.accdb) press finish.
Give name to data source and select create button. Give name (stud.mdb) for database and select
database folder in desired drive click OK.
The JDBC process
The programming involved to establish a JDBC connection is fairly simple. Here are these
simple four steps:
 Import JDBC Packages: import java.sql.* ;
 Register JDBC Driver: Class.forName( ) method to dynamically load the driver's class
file into memory, which automatically registers it.
 Create Connection Object:Connection using the DriverManager.getConnection( )
method.
 Closing JDBC connections: To close above opened connection you should call close ( )
method.
Example: database program through JSP Program.
stud.jsp.

<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. Loading a database driver,


In this step of the jdbc connection process, we load the driver class by calling Class.forName()
with the Driver class name as an argument. Once loaded, the Driver class creates an instance of
itself. A client can connect to Database Server through JDBC Driver. Since most of the Database
servers support ODBC driver therefore JDBC-ODBC Bridge driver is commonly used.
The return type of the Class.forName (String ClassName) method is “Class”. Class is a class in
java.lang package.

?
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 Syntax:: jdbc: <subprotocol>: <subname>

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 statement = dbConnection.createStatement();

A statement object is used to send and execute SQL statements to a database.

Three kinds of Statements

Statement: Execute simple sql queries without parameters.


Statement createStatement()
Creates an SQL Statement object.

Prepared Statement: Execute precompiled sql queries with or without parameters.


PreparedStatement prepareStatement(String sql)
returns a new PreparedStatement object. PreparedStatement objects are precompiled
SQL statements.

Callable Statement: Execute a call to a database stored procedure.


CallableStatement prepareCall(String sql)
returns a new CallableStatement object. CallableStatement objects are SQL stored procedure
call statements.
Executing a SQL statement with the Statement object, and returning a jdbc resultSet.

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.

Test JDBC Driver Installation

?
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

You might also like