UNIT –IV
Java Server Pages
JSP technology is used to create web application just like Servlet technology. It can be thought of as
an extension to Servlet because it provides more functionality than servlet such as expression
language, JSTL, etc.
A JSP page consists of HTML tags and JSP tags. The JSP pages are easier to maintain than Servlet
because we can separate designing and development. It provides some additional features such as
Expression Language, Custom Tags, etc.
Advantages of JSP over Servlet
There are many advantages of JSP over the Servlet. They are as follows:
1) Extension to Servlet
JSP technology is the extension to Servlet technology. We can use all the features of the Servlet in
JSP. In addition to, we can use implicit objects, predefined tags, expression language and Custom tags
in JSP, that makes JSP development easy.
2) Easy to maintain
JSP can be easily managed because we can easily separate our business logic with presentation logic.
In Servlet technology, we mix our business logic with the presentation logic.
3) Fast Development: No need to recompile and redeploy
If JSP page is modified, we don't need to recompile and redeploy the project. The Servlet code needs
to be updated and recompiled if we have to change the look and feel of the application.
4) Less code than Servlet
In JSP, we can use many tags such as action tags, JSTL, custom tags, etc. that reduces the code.
Moreover, we can use EL, implicit objects, etc.
The Lifecycle of a JSP Page
The JSP pages follow these phases:
o Translation of JSP Page
o Compilation of JSP Page
o Classloading (the classloader loads class file)
o Instantiation (Object of the Generated Servlet is created).
o Initialization ( the container invokes jspInit() method).
o Request processing ( the container invokes _jspService() method).
o Destroy ( the container invokes jspDestroy() method).
Elements of JSP
The Scriptlet
A scriptlet can contain any number of JAVA language statements, variable or method declarations, or
expressions that are valid in the page scripting language.
Following is the syntax of Scriptlet −
<% code fragment %>
JSP Declarations
A declaration declares one or more variables or methods that you can use in Java code later in the JSP
file. You must declare the variable or method before you use it in the JSP file.
Following is the syntax for JSP Declarations −
<%! declaration; [ declaration; ]+ ... %>
JSP Expression
A JSP expression element contains a scripting language expression that is evaluated, converted to a
String, and inserted where the expression appears in the JSP file
Following is the syntax of JSP Expression −
<%= expression %>
JSP Directives
A JSP directive affects the overall structure of the servlet class. It usually has the following form −
<%@ directive attribute="value" %>
There are three types of directive tag −
S.No. Directive & Description
1 <%@ page ... %>
Defines page-dependent attributes, such as scripting language, error page, and
buffering requirements.
<%@ include ... %>
2
Includes a file during the translation phase.
<%@ taglib ... %>
3
Declares a tag library, containing custom actions, used in the page
Control-Flow Statements
You can use all the APIs and building blocks of Java in your JSP programming including decision-
making statements, loops, etc.
Decision-Making Statements
The if...else block starts out like an ordinary Scriptlet, but the Scriptlet is closed at each line with
HTML text included between the Scriptlet tags.
<%!int day =3; %>
<html>
<head><title>IF...ELSE Example</title></head>
<body>
<%if(day ==1|| day ==7){ %>
<p>Today is weekend</p>
<%}else{ %>
<p>Today is not weekend</p>
<%} %>
</body>
</html>
The above code will generate the following result −
Today is not weekend
Loop Statements
You can also use three basic types of looping blocks in Java: for, while, and do…while blocks in
your JSP programming.
Let us look at the following for loop example −
<%!int fontSize; %>
<html>
<head><title>FOR LOOP Example</title></head>
<body>
<%for( fontSize=1; fontSize <=3; fontSize++){ %>
<font color = "green" size = "<%= fontSize %>">
JSP Tutorial
</font><br/>
<%}%>
</body>
</html>
The above code will generate the following result −
JSP Tutorial
JSP Tutorial
JSP Tutorial
JSP Implicit Objects
There are 9 jsp implicit objects. These objects are created by the web container that are available to
all the jsp pages.
The available implicit objects are out, request, config, session, application etc.
A list of the 9 implicit objects is given below
Object Type
out JspWriter
request HttpServletRequest
response HttpServletResponse
config ServletConfig
application ServletContext
session HttpSession
pageContext PageContext
page Object
exception Throwable
JSP Declaration Tag
The JSP declaration tag is used to declare fields and methods.
The code written inside the jsp declaration tag is placed outside the service() method of auto generated
servlet.
So it doesn't get memory at each request.
Syntax of JSP declaration tag
The syntax of the declaration tag is as follows:
<%! field or method declaration %>
Example of JSP declaration tag that declares field
In this example of JSP declaration tag, we are declaring the field and printing the value of the declared
field using the jsp expression tag.
index.jsp
<html>
<body>
<%! int data=50; %>
<%= "Value of the variable is:"+data %>
</body>
</html>
Example of JSP declaration tag that declares method
In this example of JSP declaration tag, we are defining the method which returns the cube of given
number and calling this method from the jsp expression tag. But we can also use jsp scriptlet tag to call
the declared method.
index.jsp
<html>
<body>
<%!
int cube(int n){
return n*n*n*;
}
%>
<%= "Cube of 3 is:"+cube(3) %>
</body>
</html>
session implicit object
In JSP, session is an implicit object of type HttpSession.The Java developer can use this object to
set,get or remove attribute or to get session information.
Example of session implicit object
index.html
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>
welcome.jsp
<html>
<body>
<%
String name=request.getParameter("uname");
out.print("Welcome "+name);
session.setAttribute("user",name);
<a href="second.jsp">second jsp page</a>
%>
</body>
</html> second.jsp
<html>
<body>
<%
String name=(String)session.getAttribute("user");
out.print("Hello "+name);
%>
</body>
</html>
JSP application implicit object
In JSP, application is an implicit object of type ServletContext.
The instance of ServletContext is created only once by the web container when application or project
is deployed on the server.
This object can be used to get initialization parameter from configuaration file (web.xml). It can also
be used to get, set or remove attribute from the application scope.
This initialization parameter can be used by all jsp pages.
Example of application implicit object:
index.html
<form action="welcome">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form> web.xml file
<web-app>
<servlet>
<servlet-name>sonoojaiswal</servlet-name>
<jsp-file>/welcome.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>sonoojaiswal</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
<context-param>
<param-name>dname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</context-param>
</web-app> welcome.jsp
<%
out.print("Welcome "+request.getParameter("uname"));
String driver=application.getInitParameter("dname");
out.print("driver name is="+driver);
%>
Database Programming with JDBC
DBC 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).
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 −
JDBC Drivers Types
JDBC driver implementations vary because of the wide variety of operating systems and hardware
platforms in which Java operates. Sun has divided the implementation types into four categories,
Types 1, 2, 3, and 4, which is explained below −
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.
Using ODBC, requires configuring on your system a Data Source Name (DSN) that represents the
target database.
When Java first came out, this was a useful driver because most databases only supported ODBC
access but now this type of driver is recommended only for experimental use or when no other
alternative is available.
The JDBC-ODBC Bridge that comes with JDK 1.2 is a good example of this kind of driver.
Type 2: JDBC-Native API
In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls, which are unique to
the database. These drivers are typically provided by the database vendors and used in the same
manner as the JDBC-ODBC Bridge. The vendor-specific driver must be installed on each client
machine.
If we change the Database, we have to change the native API, as it is specific to a database and they
are mostly obsolete now, but you may realize some speed increase with a Type 2 driver, because it
eliminates ODBC's overhead.
The Oracle Call Interface (OCI) driver is an example of a Type 2 driver.
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.
You can think of the application server as a JDBC "proxy," meaning that it makes calls for the client
application. As a result, you need some knowledge of the application server's configuration in order to
effectively use this driver type.
Your application server might use a Type 1, 2, or 4 driver to communicate with the database,
understanding the nuances will prove helpful.
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.
<%@ page import="java.sql.*" %>
<% Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); %>
<HTML>
<HEAD>
<TITLE>The Publishers Database Table </TITLE>
</HEAD>
<BODY>
<H1>The Publishers Database Table </H1>
<%
Connection connection = DriverManager.getConnection(
"jdbc:odbc:data", "userName", "password");
Statement statement = connection.createStatement() ;
ResultSet resultset = statement.executeQuery("select * from Publishers") ;
%>
<TABLE BORDER="1">
<TR>
<TH>ID</TH>
<TH>Name</TH>
<TH>City</TH>
<TH>State</TH>
<TH>Country</TH>
</TR>
<% while(resultset.next()){ %>
<TR>
<TD><%= resultset.getString(1) %></td>
<TD><%= resultset.getString(2) %></TD>
<TD><%= resultset.getString(3) %></TD>
<TD><%= resultset.getString(4) %></TD>
<TD><%= resultset.getString(5) %></TD>
</TR>
<% } %>
</TABLE>
</BODY>
</HTML>
Development of Java Beans in JSP
jsp:useBean action tag
The jsp:useBean action tag is used to locate or instantiate a bean class. If bean object of the Bean class
is already created, it doesn't create the bean depending on the scope. But if object of bean is not
created, it instantiates the bean.
Syntax of jsp:useBean action tag
<jsp:useBean id= "instanceName" scope= "page | request | session | application"
class= "packageName.className" type= "packageName.className"
beanName="packageName.className | <%= expression >" >
</jsp:useBean>
Attributes and Usage of jsp:useBean action tag
1. id: is used to identify the bean in the specified scope.
2. scope: represents the scope of the bean. It may be page, request, session or application. The
default scope is page.
o page: specifies that you can use this bean within the JSP page. The default scope is
page.
o request: specifies that you can use this bean from any JSP page that processes the same
request. It has wider scope than page.
o session: specifies that you can use this bean from any JSP page in the same session
whether processes the same request or not. It has wider scope than request.
o application: specifies that you can use this bean from any JSP page in the same
application. It has wider scope than session.
3. class: instantiates the specified bean class (i.e. creates an object of the bean class) but it must
have no-arg or no constructor and must not be abstract.
4. type: provides the bean a data type if the bean already exists in the scope. It is mainly used
with class or beanName attribute. If you use it without class or beanName, no bean is
instantiated.
5. beanName: instantiates the bean using the java.beans.Beans.instantiate() method.
Simple example of jsp:useBean action tag
Calculator.java (a simple Bean class)
package com.javatpoint;
public class Calculator{
public int cube(int n){return n*n*n;}
index.jsp file
<jsp:useBean id="obj" class="com.javatpoint.Calculator"/>
<%
int m=obj.cube(5);
out.print("cube of 5 is "+m);
%>
Servlets
Java Servlets are programs that run on a Web or Application server and act as a middle layer between
a requests coming from a Web browser or other HTTP client and databases or applications on the
HTTP server.
Using Servlets, you can collect input from users through web page forms, present records from a
database or another source, and create web pages dynamically.
Servlets Architecture
The following diagram shows the position of Servlets in a Web Application.
Servlets Tasks
Servlets perform the following major tasks −
Read the explicit data sent by the clients (browsers). This includes an HTML form on a Web
page or it could also come from an applet or a custom HTTP client program.
Read the implicit HTTP request data sent by the clients (browsers). This includes cookies,
media types and compression schemes the browser understands, and so forth.
Process the data and generate the results. This process may require talking to a database,
executing an RMI or CORBA call, invoking a Web service, or computing the response
directly.
Send the explicit data (i.e., the document) to the clients (browsers). This document can be sent
in a variety of formats, including text (HTML or XML), binary (GIF images), Excel, etc.
Send the implicit HTTP response to the clients (browsers). This includes telling the browsers
or other clients what type of document is being returned (e.g., HTML), setting cookies and
caching parameters, and other such tasks.
Servlets - Life Cycle
A servlet life cycle can be defined as the entire process from its creation till the destruction. The
following are the paths followed by a servlet.
The servlet is initialized by calling the init() method.
The servlet calls service() method to process a client's request.
The servlet is terminated by calling the destroy() method.
Finally, servlet is garbage collected by the garbage collector of the JVM.
The init() Method
The init method is called only once. It is called only when the servlet is created, and not called for any
user requests afterwards. So, it is used for one-time initializations, just as with the init method of
applets.
publicvoid init()throwsServletException{
// Initialization code...
The service() Method
The service() method is the main method to perform the actual task. The servlet container (i.e. web
server) calls the service() method to handle requests coming from the client( browsers) and to write
the formatted response back to the client.
publicvoid service(ServletRequest request,ServletResponse response)
throwsServletException,IOException{
The doGet() Method
A GET request results from a normal request for a URL or from an HTML form that has no
METHOD specified and it should be handled by doGet() method
publicvoid doGet(HttpServletRequest request,HttpServletResponse response)
throwsServletException,IOException{
// Servlet code
The doPost() Method
A POST request results from an HTML form that specifically lists POST as the METHOD and it
should be handled by doPost() method.
publicvoid doPost(HttpServletRequest request,HttpServletResponse response)
throwsServletException,IOException{
// Servlet code
The destroy() Method
The destroy() method is called only once at the end of the life cycle of a servlet. This method gives
your servlet a chance to close database connections, halt background threads, write cookie lists or hit
counts to disk, and perform other such cleanup activities.
publicvoid destroy(){
// Finalization code...