Fsad LM 3

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 56

FULL STACK APPLICATION DEVELOPMENT UNIT-IV

UNIT-IV
JSP, JDBC
SYLLABUS:
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.

INTRODUCTION TO WEB SERVERS:


A Web server is a computer or virtual machine used to run web
applications. The primary function of a web server is to store, process and
deliver web pages to clients. The communication between client and server
takes place using the Hypertext Transfer Protocol (HTTP). Pages delivered are
most frequently HTML documents, which may include images, style
sheets and scripts in addition to text content. A user agent, commonly a web
browser, initiates communication by making a request for a specific resource
using HTTP and the server responds with the content of that resource or
an error message if unable to do so.
The computer in which a web server program runs is also usually called
a "web server". So, the term "web server" is used to represent both the server
program and the computer in which the server program runs.
Any computer can be turned into a Web server by installing server
software and connecting the machine to the Internet. There are many Web
server software applications. Some of them are:
 Apache Tomcat Server
 Microsoft's Internet Information Services (IIS) Windows Server
 Oracle Weblogic Server
 Google Web Server

Department of Information Technology A.Y.2022-23 III-I SRGEC Page 1


FULL STACK APPLICATION DEVELOPMENT UNIT-IV

Characteristics of web servers:


A web server computer is just like any other computer. The basic
characteristics of web servers are:
 It is always connected to the internet so that clients can access the web
pages hosted by the web server.
 It always has an application called "web server" running.
 In short, a "web server" is a computer that is connected to the
internet/intranet and has software called "web server". The web server
program will always be running in the computer. When a user tries to
access a website hosted by the web server, it is actually the web server
program that delivers the web page that the client asks for.
 All web sites in the internet are hosted in web servers sitting in various
parts of the world.
TOMCAT WEB SERVER:
 Apache Tomcat, often referred to as Tomcat.
 It is an open-source web server developed by the Apache Software
Foundation (ASF).
 Tomcat implements several Java EE specifications including Java
Servlet, Java Server Pages(JSP), Java EL, and Web Socket, and provides
a "pure Java" HTTP web server environment in which Java code can
run.

Installing APACHE TOMCAT:-

Department of Information Technology A.Y.2022-23 III-I SRGEC Page 2


FULL STACK APPLICATION DEVELOPMENT UNIT-IV

Accepting License Agreement:

Choosing Components to be installed:

Department of Information Technology A.Y.2022-23 III-I SRGEC Page 3


FULL STACK APPLICATION DEVELOPMENT UNIT-IV

Configuring Port Number, Username & Password:

Department of Information Technology A.Y.2022-23 III-I SRGEC Page 4


FULL STACK APPLICATION DEVELOPMENT UNIT-IV

Choosing the JVM:-

Choosing the Installation location:

Department of Information Technology A.Y.2022-23 III-I SRGEC Page 5


FULL STACK APPLICATION DEVELOPMENT UNIT-IV

Installation Progress:

Department of Information Technology A.Y.2022-23 III-I SRGEC Page 6


FULL STACK APPLICATION DEVELOPMENT UNIT-IV

Starting TOMCAT Service:

Go to this following directory and click on Tomcat7.exe to start the server.

D:\Program Files\Apache Software Foundation\Tomcat 7.0\bin

Department of Information Technology A.Y.2022-23 III-I SRGEC Page 7


FULL STACK APPLICATION DEVELOPMENT UNIT-IV

Testing TOMCAT:
To test the server - assuming you're running Tomcat on the same machine as
the browser and that you're using the default port for Tomcat (8080) But we
changed it to 2025 while installing- open a browser and enter the following
URL in the Location/Address field:
http://localhost:2025/
The Tomcat main page is shown in the browser and you can now run all servlet
and JSP examples bundled with Tomcat to make sure everything works.

Department of Information Technology A.Y.2022-23 III-I SRGEC Page 8


FULL STACK APPLICATION DEVELOPMENT UNIT-IV

TOMCAT Directory Structure:

The TOMCAT Working Directory consists of following folders:


 Bin--- Contains bootstrap.jar, tomcat-juli.jar,tomcat7.exe and tomcat7w.exe

 Conf--- Contains server configuration files including server.xml and global


web.xml

Department of Information Technology A.Y.2022-23 III-I SRGEC Page 9


FULL STACK APPLICATION DEVELOPMENT UNIT-IV

 Libs-Contains Library files required to run JSP and Servlet Applications

 Logs--- Contains TOMCAT log files

Department of Information Technology A.Y.2022-23 III-I SRGEC Page 10


FULL STACK APPLICATION DEVELOPMENT UNIT-IV

 Temp--- Directory used by JVM for temporary files


 Webapps--- Contains servlet and JSP applications to be served by TOMCAT

 Work--- Contains files and directories created by JSP container. This


directory holds the servlet equivalent of JSP

 Notice.file--- Contains general info about the product.


 License.txt--- Contains license for the product

Department of Information Technology A.Y.2022-23 III-I SRGEC Page 11


FULL STACK APPLICATION DEVELOPMENT UNIT-IV

Introduction to JSP:

Java Server Pages (JSP) is a technology that helps software developers create dynamically
generated web pages based on HTML,XML or other document types.

Servlet is a Java code based programming. To know servlet, strong Java knowledge is required.
However, while working with ASP.net, PHP like technologies we can go for tag-based
programming which is easier. So in initial days programmer did not like Servlet. To attract non-
java programmers like ASP.net programmers and PHP programmer Sun Microsystems has
introduced a server side technology which is tag based all features of servlet.

To deploy and run JavaServer Pages, a compatible web server with a servlet container, such as
Apache Tomcat or Jetty, is required.

Advantages of JSP over Servlets:

 Servlets are difficult to code which are overcome in JSP. Other way, we can say, JSP is
almost a replacement of Servlets, (by large, the better word is extension of Servlets),
where coding decreases more than half.
 In Servlets, both static code and dynamic code are put together. In JSP, they are
separated. For example,In Servlets:
out.println(“Hello Mr.” + str + ” you are great man”);

Department of Information Technology A.Y.2022-23 III-I SRGEC Page 12


FULL STACK APPLICATION DEVELOPMENT UNIT-IV

where str is the name of the client which changes for each client and is known as
dynamic content. The strings, “Hello Mr.” and “you are great man” are static content
which is the same irrespective of client. In Servlets, in println(), both are put together.
In JSP:
Hello Mr. // static content as HTML code
<%= str %> // dynamic content as JSP code
you are great man // static content as HTML code
 JSP needs no compilation, CLASSPATH setting and packaging.
 The objects of PrintWriter, ServletConfig, ServletContext, HttpSession and
RequestDispatcher etc. are created by the Programmer in Servlets and used. But in JSP,
they are builtin and are known as "implicit objects". That is, in JSP, Programmer never
creates these objects and straightaway use them as they are implicitly created and given
by JSP container. This decreases lot of coding.
 JSP needs no compilation by the Programmer. Programmer deploys directly a JSP source
code file in server where as incase of Servlets, the Programmer compiles manually a
Servlet file and deploys a .class file in server.
 No need to configure the jsp in web.xml.
 Whenever JSP modified, modifications reflected without recompilation, where as in
Servlet without compilation not possible to reflect the modification.

Department of Information Technology A.Y.2022-23 III-I SRGEC Page 13


FULL STACK APPLICATION DEVELOPMENT UNIT-IV

Anatomy of JSP page

A JSP page is simply a regular web page with JSP elements for generating the parts of the page
that differ for each request, as shown in Figure below.

Everything in the page that is not a JSP element is called template text . Template text can really
be any text: HTML, WML, XML, or even plain text. Since HTML is by far the most common
web page language in use today, most of the descriptions and examples in this book are HTML-
based, but keep in mind that JSP has no dependency on HTML; it can be used with any markup
language. Template text is always passed straight through to the browser.

When a JSP page request is processed, the template text and the dynamic content generated by
the JSP elements are merged, and the result is sent as the response to the browser.

JSP processing/Life Cycle Methods:


A JSP page cannot be sent as-is to the browser; all JSP elements must first be
processed by the server. This is done by turning the JSP page into a servlet,
and then executing the servlet.

Department of Information Technology A.Y.2022-23 III-I SRGEC Page 14


FULL STACK APPLICATION DEVELOPMENT UNIT-IV

JSP Container:
As a web server needs a servlet container to provide an interface to servlets, the
server needs a JSP container to process JSP pages. The JSP container is often
implemented as a servlet configured to handle all requests for JSP pages. In
fact, these two containers - a servlet container and a JSP container - are often
combined into one package under the name web container.
JSP Processing is done in 2 phases:
i) Translation Phase
ii) Request Processing Phase
i) Translation Phase:
A JSP container is responsible for converting the JSP page into a servlet (known
as the JSP page implementation class) and compiling the servlet. These two
steps form the translation phase. The JSP container automatically initiates the
translation phase for a page when the first request for the page is received. The
translation phase can also be initiated explicitly; this is referred to as
precompilation of a JSP page.
When a JSP container receives a jsp request, it checks for the jsp’s servlet
instance. If no servlet instance is available, then, the container creates the
servlet instance using following stages.
 Translation
 Compilation
 Loading
 Instantiation
 Initialization
Translation - In this step the JSP page is translated into the corresponding
Servlet.
Compilation - Once the JSP page has been translated into the corresponding
Servlet, the next obvious step is to compile that Servlet.
Loading & Instantiation - As is the case with any compiled class (.class file),
this servlet class also needs to be loaded into the memory before being used.
The default class loader of the Container will load this class. Once the class is
loaded, an instance of this class gets created.
Initialization: JspPage interface contains the jspInit() method, which is used
by the JSP container to initialize the newly created instance.
This jspInit() method is just like the init()method of the Servlet and it's called
only once during the entire life cycle of a JSP/Servlet.

Department of Information Technology A.Y.2022-23 III-I SRGEC Page 15


FULL STACK APPLICATION DEVELOPMENT UNIT-IV

ii) Request Processing Phase:


The JSP container is also responsible for invoking the JSP page
implementation class to process each request and generate the response. This
is called the request processing phase.
_jspService() is the method which is called every time the JSP is requested to
serve a request. This method normally executes in a separate thread of
execution and the main JSP thread keeps waiting for other incoming requests.
Every time a request arrives, the main JSP thread spawns a new thread and
passes the request (incoming request) and response (new) objects to
the_jspService() method which gets executed in the newly spawned thread.
The _jspDestroy() method is used to destroy the JSP Page. The destroy() method
defined in the servlet class is redefined by this method. If any cleanup is
required, then the page author can define this method. This method is called
only once during JSP page Life Cycle.

Department of Information Technology A.Y.2022-23 III-I SRGEC Page 16


FULL STACK APPLICATION DEVELOPMENT UNIT-IV

Figure: JSP Life Cycle/JSP Processing

LIFE CYCLE METHODS:

i). The jspInit()- The container calls the jspInit() to initialize the servlet
instance.It is called before any other method, and is called only once for a
servlet instance.

public void jspInit(){


// Initialization code...
}

ii). The _jspservice()- The container calls the _jspservice() for each request,
passing it the request and the response objects.

void _jspService(HttpServletRequest request,


HttpServletResponse response)

Department of Information Technology A.Y.2022-23 III-I SRGEC Page 17


FULL STACK APPLICATION DEVELOPMENT UNIT-IV

{
// Service handling code...
}

iii). The jspDestroy()- The container calls this when it decides to take the
instance out of service. It is the last method called in the servlet instance.

public void jspDestroy()


{
// cleanup code goes here.
}

Figure: JSP Life Cycle Methods

Root Directory Structure:

Department of Information Technology A.Y.2022-23 III-I SRGEC Page 18


FULL STACK APPLICATION DEVELOPMENT UNIT-IV

This root directory structure we have to follow while developing applications using the
JSP/Servlets.

1. Root directory name can be user defined name.


2. WEB-INF is the sub folder of the ROOT folder. It contains we.xml file, and two sub folders
namely classes and lib.
3. web.xml is called deployment descriptor here we can register the servlets which we are using in
the application.
4. Classes folder contain the all servlets i.e;*.java files and its compiled files i.e;*.class.
5. Lib folder contains the library/jar files required to run the application.
6. All html, audio, image, video files required for application all we can place in the root directory
directly.

JSP Directives:

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. It usually has the following form:

<%@ directive attribute="value" %>

Directive Description

<%@ page ... %> defines page dependent properties such as language, session, errorPage etc.

<%@ include ... %> defines file to be included.

<%@ taglib ... %> declares tag library used in the page

We'll discuss about include and taglib directive later. You can place page directive anywhere in
the JSP file, but it is good practice to make it as the first statement of the JSP page.

Department of Information Technology A.Y.2022-23 III-I SRGEC Page 19


FULL STACK APPLICATION DEVELOPMENT UNIT-IV

The Page directive defines a number of page dependent properties which communicates with the
Web Container at the time of translation. Basic syntax of using the page directive is

<%@ page attribute="value" %>

where attributes can be one of the following :

 import attribute
 language attribute
 extends attribute
 session attribute
 isThreadSafe attribute
 isErrorPage attribute
 errorPage attribute
 contentType attribute
 autoFlush attribute
 buffer attribute

import attribute

The import attribute defines the set of classes and packages that must be imported in servlet class
definition. For example

<%@ page import="java.util.Date" %>

or

<%@ page import="java.util.Date,java.net.*" %>

language attribute

language attribute defines scripting language to be used in the page.

extends attribute

extends attribute defines the class name of the superclass of the servlet class that is generated
from the JSP page.

Department of Information Technology A.Y.2022-23 III-I SRGEC Page 20


FULL STACK APPLICATION DEVELOPMENT UNIT-IV

session attribute

session attribute defines whether the JSP page is participating in an HTTP session. The value is
either true or false.

isThreadSafe attribute

isThreadSafe attribute declares whether the JSP is thread-safe. The value is either true or false

isErrorPage attribute

isErrorPage attribute declares whether the current JSP Page represents another JSP's error page.

errorPage attribute

errorPage attribute indicates another JSP page that will handle all the run time exceptions thrown
by current JSP page. It specifies the URL path of another page to which a request is to be
dispatched to handle run time exceptions thrown by current JSP page.

contentType attribute

contentType attribute defines the MIME type for the JSP response.

autoFlush attribute

autoFlush attribute defines whether the buffered output is flushed automatically. The default
value is "true".

buffer attribute

buffer attribute defines how buffering is handled by the implicit out object.

include Directive:

The include directive is used to includes a file during the translation phase. This directive tells
the container to merge the content of other external files with the current JSP during the
translation phase. You may code include directives anywhere in your JSP page.

The general usage form of this directive is as follows:

Department of Information Technology A.Y.2022-23 III-I SRGEC Page 21


FULL STACK APPLICATION DEVELOPMENT UNIT-IV

<%@ include file="relative url" >

The filename in the include directive is actually a relative URL. If you just specify a filename
with no associated path, the JSP compiler assumes that the file is in the same directory as your
JSP.

You can write XML equivalent of the above syntax as follows:

<jsp:directive. include file="relative url" />

Taglib Directive:

The taglib directive is used to define tag library that the current JSP page uses. A JSP page might
include several tag library. JavaServer Pages Standard Tag Library (JSTL), is a collection of
useful JSP tags, which provides mahy commonly used core functionalities. It has support for
many general, structural tasks such as iteration and conditionals, readymade tags for
manipulating XML documents, internationalization tags, and for performing SQL operations.
Syntax of taglib directive is:

<%@ taglib prefix="prefixOfTag" uri="uriOfTagLibrary" %>

The prefix is used to distinguish the custom tag from other libary custom tag. Prefix is prepended
to the custom tag name. Every custom tag must have a prefix.

The URI is the unique name for Tag Library.

Department of Information Technology A.Y.2022-23 III-I SRGEC Page 22


FULL STACK APPLICATION DEVELOPMENT UNIT-IV

JSP Action Tags

There are many JSP action tags or elements. Each JSP action tag is used to perform some
specific tasks.

The action tags are used to control the flow between pages and to use Java Bean. The Jsp action
tags are given below.

We can dynamically insert a file, reuse the beans components, forward user to another page, etc.
through JSP Actions like include and forward.

Unlike directives, actions are re-evaluated each time the page is accessed.

There are 11 types of Standard Action Tags as following:

 jsp:useBean
 jsp:include
 jsp:setProperty
 jsp:getProperty
 jsp:forward
 jsp:plugin
 jsp:attribute
 jsp:body
 jsp:text
 jsp:param

Department of Information Technology A.Y.2022-23 III-I SRGEC Page 23


FULL STACK APPLICATION DEVELOPMENT UNIT-IV

 jsp:output
1. jsp:useBean:

This action name is used when we want to use beans in the JSP page.

With this tag, we can easily invoke a bean.

Syntax:

<jsp:useBean id="" class="" />

Here it specifies the identifier for this bean and class is full path of the bean class

2. jsp:include

It also used to insert a jsp file into another file, just like include directive.

It is added during request processing phase

Syntax:

<jsp:include page="page URL" flush="true/false">

3. jsp:setProperty

This property is used to set the property of the bean.

We need to define a bean before setting the property

Syntax:

<jsp:setproperty name="" property="" >

Here, the name defines the bean whose property is set and property which we want to set.

Also, we can set value and param attribute.

Here value is not mandatory, and it defines the value which is assigned to the property.

Department of Information Technology A.Y.2022-23 III-I SRGEC Page 24


FULL STACK APPLICATION DEVELOPMENT UNIT-IV

Here param is the name of the request parameter using which value can be fetched.

4. jsp:getProperty

This property is used to get the property of the bean.

It converts into a string and finally inserts into the output.

Syntax:

<jsp:getAttribute name="" property="" >

Here, the name of the bean from which the property has to be retrieved and bean should be
defined. The property attribute is the name of the bean property to be retrieved.

5. jsp:forward:

It is used to forward the request to another jsp or any static page.

Here the request can be forwarded with no parameters or with parameters.

Syntax:

<jsp:forward page="value">

Here value represents where the request has to be forwarded.

6. jsp:plugin

It is used to introduce Java components into jsp, i.e., the java components can be either an applet
or bean.

It detects the browser and adds <object> or <embed> tags into the file

Syntax:

<jsp:plugin type="applet/bean" code="objectcode" codebase="objectcodebase">

Here the type specifies either an object or a bean

Code specifies class name of applet or bean

Department of Information Technology A.Y.2022-23 III-I SRGEC Page 25


FULL STACK APPLICATION DEVELOPMENT UNIT-IV

Code base contains the base URL that contains files of classes

7. jsp:param

This is child object of the plugin object described above

It must contain one or more actions to provide additional parameters.

Syntax:

<jsp:params>

<jsp:param name="val" value="val"/ >

</jsp:params>

8. jsp:body

This tag is used to define the XML dynamically i.e., the elements can generate during request
time than compilation time.

It actually defines the XML, which is generated dynamically element body.

Syntax:

<jsp:body></jsp:body>

Here we write XML body tag within this tags.

9. jsp:attribute

This tag is used to define the XML dynamically i.e. the elements can be generated during request
time than compilation time

It actually defines the attribute of XML which will be generated dynamically.

Syntax:

<jsp:attribute></jsp:attribute>

Here we write attribute tag of XML.

Department of Information Technology A.Y.2022-23 III-I SRGEC Page 26


FULL STACK APPLICATION DEVELOPMENT UNIT-IV

10. jsp:text

It is used to template text in JSP pages.

Its body does not contain any other elements, and it contains only text and EL expressions.

Syntax:

<jsp:text>template text</jsp:text

Here template text refers to only template text (which can be any generic text which needs to be
printed on jsp ) or any EL expression.

11. jsp:output:

It specifies the XML declaration or the DOCTYPE declaration of jsp

The XML declaration and DOCTYPE are declared by the output

Syntax:

<jsp:output doctype-root-element="" doctype-system="">

Here, doctype-root-element indicates the root element of XML document in DOCTYPE.

Doctype-system indicates doctype which is generated in output and gives system literal

JSP Scripting elements:

JSP scripting elements enable you insert Java code into the servlet that will be generated from
the current JSP page. There are three forms:

 Scriptlets of the form <% code %> that are inserted into the servlets service method.
 Expressions of the form <%= expression%> that are evaluated and inserted into output.
 Declarations of the form <%! code %> that are inserted into the body of the servlet class,
outside of any existing methods.

Scriptlet Tag (Code Snippets)

Department of Information Technology A.Y.2022-23 III-I SRGEC Page 27


FULL STACK APPLICATION DEVELOPMENT UNIT-IV

Scriptlet Tag allows you to write java code inside JSP page. Scriptlet tag implements the
_jspService() method functionality by writing script/java code. Syntax of Scriptlet Tag is as
follows :

<%
java code
%>
Within a scriptlet, you 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.
Use any of the implicit objects or any object declared with a <jsp:useBean> element.
Write any other statement valid in the scripting language used in the JSP page.
In this example, Finding Addition of two numbers.
<%@page language="java" contentType="text/html"%>
<%
//declaring variables
int a=10;
int b=20;
int c=a+b;
%>
<center>
<h1>Addition is
<%
//printing results
out.println(c);
%>
</h1>
</center>

Department of Information Technology A.Y.2022-23 III-I SRGEC Page 28


FULL STACK APPLICATION DEVELOPMENT UNIT-IV

Output:

We have been using the above example since last few lessons and in this scriptlet tags are used.
Everything written inside the scriptlet tag is compiled as java codeJSP makes it so easy to
perform calculations, database interactions etc directly from inside the HTML code. Just write
your java code inside the scriptlet tags.

Declaration Tag(Decalarations)

We know that at the end a JSP page is translated into Servlet class. So when we declare a
variable or method in JSP inside Declaration Tag, it means the declaration is made inside the
Servlet class but outside the service(or any other) method. You can declare static member,
instance variable and methods inside Declaration Tag.

Syntax of Declaration Tag :

<%!

declaration

%>

Example of Declaration Tag

<%@page language="java" contentType="text/html"%>


<%!
//declaring variables outside of _jspService()
int c;
//delaring methods outside of the _jspService()

Department of Information Technology A.Y.2022-23 III-I SRGEC Page 29


FULL STACK APPLICATION DEVELOPMENT UNIT-IV

public int addition(int a,int b)


{
c=a+b;
return c;
}
%>
<center><h1>Addition is
<%
//printing results
out.println(addition(10,40));
%></h1></center>
Output:

JSP expression tag(Expressions)

The code placed within JSP expression tag is written to the output stream of the response. So you
need not write out.print() to write data. It is mainly used to print the values of variable or
method.

Syntax of JSP expression tag

<%=

Statement

%>

Department of Information Technology A.Y.2022-23 III-I SRGEC Page 30


FULL STACK APPLICATION DEVELOPMENT UNIT-IV

Example of JSP expression tag

In this example of jsp expression tag, we are simply displaying a welcome message.

<html>

<body>

<%= "welcome to jsp" %>

</body>

</html>

Example of JSP expression tag that prints current time,Host,Session ID.

To display the current time, we have used the getTime() method of Calendar class. The
getTime() is an instance method of Calendar class, so we have called it after getting the instance
of Calendar class by the getInstance() method.

index.jsp:

<%@page language="java" contentType="text/html"%>

<html>

<head></head>

<body>

Current Time:<%= java.util.Calendar.getInstance().getTime()%><br>

Your Hostname:<%=request.getRemoteHost()%><br>

Session Id:<%=session.getId()%><br>

</body>

</html>

Department of Information Technology A.Y.2022-23 III-I SRGEC Page 31


FULL STACK APPLICATION DEVELOPMENT UNIT-IV

Output:

Implicit Objects:

JSP Implicit Objects are the Java objects that the JSP Container makes available to developers in
each page and developer can call them directly without being explicitly declared. JSP Implicit
Objects are also called pre-defined variables.

JSP supports nine Implicit Objects which are listed below:

Object Description

Request This is the HttpServletRequest object associated with the


request.

Response This is the HttpServletResponse object associated with the


response to the client.

Out This is the PrintWriter object used to send output to the client.

Session This is the HttpSession object associated with the request.

application This is the ServletContext object associated with application

Department of Information Technology A.Y.2022-23 III-I SRGEC Page 32


FULL STACK APPLICATION DEVELOPMENT UNIT-IV

context.

Config This is the ServletConfig object associated with the page.

pageContext This encapsulates use of server-specific features like higher


performance JspWriters.

Page This is simply a synonym for this, and is used to call the
methods defined by the translated servlet class.

Exception The Exception object allows the exception data to be accessed


by designated JSP.

The request Object:

The request object is an instance of a javax.servlet.http.HttpServletRequest object. Each time a


client requests a page the JSP engine creates a new object to represent that request.

The request object provides methods to get HTTP header information including form data,
cookies, HTTP methods etc.

The response Object:

The response object is an instance of a javax.servlet.http.HttpServletResponse object. Just as the


server creates the request object, it also creates an object to represent the response to the client.

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.

The out Object:

The out implicit object is an instance of a javax.servlet.jsp.JspWriter object and is used to send
content in a response.

Department of Information Technology A.Y.2022-23 III-I SRGEC Page 33


FULL STACK APPLICATION DEVELOPMENT UNIT-IV

The initial JspWriter object is instantiated differently depending on whether the page is buffered
or not. Buffering can be easily turned off by using the buffered='false' attribute of the page
directive.

The session Object:

The session object is an instance of javax.servlet.http.HttpSession and behaves exactly the same
way that session objects behave under Java Servlets.

The session object is used to track client session between client requests. We would see complete
usage of session object in coming chapter: JSP - Session Tracking

The application Object:

The application object is direct wrapper around the ServletContext object for the generated
Servlet and in reality an instance of a javax.servlet.ServletContext object.

This object is a representation of the JSP page through its entire lifecycle. This object is created
when the JSP page is initialized and will be removed when the JSP page is removed by the
jspDestroy() method.

The config Object:

The config object is an instantiation of javax.servlet.ServletConfig and is a direct wrapper


around the ServletConfig object for the generated servlet.

This object allows the JSP programmer access to the Servlet or JSP engine initialization
parameters such as the paths or file locations etc.

The pageContext Object:

The pageContext object is an instance of a javax.servlet.jsp.PageContext object. The


pageContext object is used to represent the entire JSP page.

This object is intended as a means to access information about the page while avoiding most of
the implementation details.

Department of Information Technology A.Y.2022-23 III-I SRGEC Page 34


FULL STACK APPLICATION DEVELOPMENT UNIT-IV

This object stores references to the request and response objects for each request. The
application, config, session, and out objects are derived by accessing attributes of this object.

The page Object:

This object is an actual reference to the instance of the page. It can be thought of as an object that
represents the entire JSP page.

The page object is really a direct synonym for the this object.

The exception Object:

The exception object is a wrapper containing the exception thrown from the previous page. It is
typically used to generate an appropriate response to the error condition.

Syntax of JSP declaration tag

The syntax of the declaration tag is as follows:


1. <%! field or method declaration %>

Difference between JSP Scriptlet tag and Declaration tag:


Jsp Scriptlet Tag Jsp Declaration Tag

The jsp scriptlet tag can only The jsp declaration tag can declare
declare variables not methods. variables as well as methods.

The declaration of scriptlet tag is The declaration of jsp declaration


placed inside the _jspService() tag is placed outside the
method. _jspService() method.

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>

Department of Information Technology A.Y.2022-23 III-I SRGEC Page 35


FULL STACK APPLICATION DEVELOPMENT UNIT-IV

</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>
PASSING CONTROL AND DATA BETWEEN JSP PAGES, REQUESTS:

 Sometimes, we need to handover the control to another page, with the


necessary data passed to it.
Passing Control & Data
 Sometimes, a jsp page wants to pass the control to another server-side
program for further processing.
 This is done by using <jsp:forward> action element.

<jsp:forward page=”targetPageURL”/>

 Once the jsp engine encounters the <jsp:forward> action, it stops the
processing of the current page and starts the processing of the target
page specified by the page attribute. The rest of the original page is never
processed further.
 The HttpServletRequest and HttpServletResponse objects are passed
to the target page. So, the target page can access all information passed
to the original page.
 We can pass additional parameters to the target page using the
<jsp:param> action element along with the <jsp:forward>

Department of Information Technology A.Y.2022-23 III-I SRGEC Page 36


FULL STACK APPLICATION DEVELOPMENT UNIT-IV

<jsp:forward page=”next.jsp” >

<jsp:param name=”parameterName” value=”parameterValue”/>

</jsp:forward>

The target page can access these parameters in the same way as the original
parameters using the getParameter() method or by using $
{param.parameterName} .

Example:
One.jsp:

<jsp:forward page="two.jsp">

<jsp:param name="college" value="Seshadri Rao Gudlavalleru Engineering College"/>

<jsp:param name="branch" value="COmputer Science and Engineering"/>

</jsp:forward>

Two.jsp:

<%@page language="java" contentType="text/html"%>

<center><h1>This Data form One.jsp</h1></center>

<center><h1>Hello Your College is <%=request.getParameter("college")%></h1>

<center><h1>Hello Your Branch is ${param.branch}</h1>

Now open browser and type:

http://localhost:2025/Passing Control/one.jsp in the browser

Department of Information Technology A.Y.2022-23 III-I SRGEC Page 37


FULL STACK APPLICATION DEVELOPMENT UNIT-IV

SHARING SESSION AND APPLICATION DATA:


Sharing Session data
 The objects having request scope are available in all pages across a
single request. However, sometimes objects should be shared among
multiple requests.
Example:
Online examination system allows different users. Different users have
different sets of data such as expiry time, number of questions answered
and so on.
 JSP pages requested from the same browser must share the same user
name that was provided during the login procedure. This type of
information can be shared through session scope.
 The objects having session scope are available to all pages requested by
the same browser.
 The implicit object session is one such object.
 This session object can be used to store and retrieve other objects.
 So, objects may be shared across pages in the same session using this
session object.

Example:

Login.html:

Department of Information Technology A.Y.2022-23 III-I SRGEC Page 38


FULL STACK APPLICATION DEVELOPMENT UNIT-IV

<HTML>

<HEAD>

</HEAD>

<BODY bgcolor='#999900'>

<center>

<form name='login' action='one.jsp'>

<table>

<tr><td colspan='2' align='center'><h2>Login Page</h2></td></tr>

<tr><td>Username</td><td><input type='text' name='username'></td></tr>

<tr><td>Password</td><td><input type='password' name='password'></td></tr>

<tr><td><input type='submit' value='Login'></td>

<td><input type='reset' value='Reset'></td>

</tr>

</table>

</form>

</center>

</BODY>

</HTML>

One.jsp:

<%@page language="java" contentType="text/html"%>

<%

String username=request.getParameter("username");

//Sharing data using session

session.setAttribute("username",username);

%>

Department of Information Technology A.Y.2022-23 III-I SRGEC Page 39


FULL STACK APPLICATION DEVELOPMENT UNIT-IV

<h1><a href="two.jsp">Click here to get your name</a></h1>

Two.jsp:

<%@page language="java" contentType="text/html"%>

<center><h1>This Data form One.jsp</h1></center>

<%

//Getting the shared data from session

String username=(String)session.getAttribute("username");

%>

<%if(username!=null){%>

<center><h1>Hello <%=username%></h1></center>

<%}else{%>

</center><h1>user session expired<a href="login.html">click here to login</a></h1></center>

<%}%>

Output:

Open browser and type following url

http://localhost:2025/Sharing session/login.html

Sharing Application Data :

 The objects that have application scope are shared across all pages of
an application that are requested through any browser.
 Implicit object used is application.

Example: The following example counts the number of visitors to a


specific web site. The counter will be incremented for different users
accessing the website through different browsers.

Example:

Count.jsp:

<%@page language="java" contentType="text/html"%>

Department of Information Technology A.Y.2022-23 III-I SRGEC Page 40


FULL STACK APPLICATION DEVELOPMENT UNIT-IV

<%

//Getting the count data from application

Integer count=(Integer)application.getAttribute("count");

%>

<%if(count==null)

count=1;

else

count++;

application.setAttribute("count",count);

%>

<center><h1>No of Visiotrs<%=count%></h1></center>

Output:

Open the browser and type following url:

http://localhost:2025/Sharing Application/count.jsp

Department of Information Technology A.Y.2022-23 III-I SRGEC Page 41


FULL STACK APPLICATION DEVELOPMENT UNIT-IV

Refresh browser out will be changed here refreshed browser for 4 times.

JDBC(Java 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. If we want to save our application data permanently in initial days of programming we
use the concept files. Files are used to store the data permanently but files are having following
limitations.
1. Files are having only operating system level security, files are not having programming level
security.
2. Files are complex to work. i.e; to write and retrieve data from files is complex task.
3. There is no relationships exist between the files.
4. There is no query language for files.
5. Files are having unstructured data.
The JDBC library includes APIs for each of the tasks mentioned below that are commonly
associated with database usage.

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.

Department of Information Technology A.Y.2022-23 III-I SRGEC Page 42


FULL STACK APPLICATION DEVELOPMENT UNIT-IV

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 −

Common JDBC Components


The JDBC API provides the following interfaces and classes −
 DriverManager: This class manages a list of database drivers. Matches
connection requests from the java application with the proper database driver
using communication sub protocol. The first driver that recognizes a certain
subprotocol under JDBC will be used to establish a database Connection.
 Driver: This interface handles the communications with the database server.
You will interact directly with Driver objects very rarely. Instead, you use
DriverManager objects, which manages objects of this type. It also abstracts
the details associated with working with Driver objects.
 Connection: This interface with all methods for contacting a database. The
connection object represents communication context, i.e., all communication
with database is through connection object only.
 Statement: You use objects created from this interface to submit the SQL
statements to the database. Some derived interfaces accept parameters in
addition to executing stored procedures.

Department of Information Technology A.Y.2022-23 III-I SRGEC Page 43


FULL STACK APPLICATION DEVELOPMENT UNIT-IV

 ResultSet: These objects hold data retrieved from a database after you execute
an SQL query using Statement objects. It acts as an iterator to allow you to
move through its data.
 SQLException: This class handles any errors that occur in a database
application.

JDBC Drivers:
JDBC drivers are divided into four types or levels. They are:
Type 1: JDBC-ODBC Bridge driver (Bridge)
Type 2: Native-API/partly Java driver (Native)
Type 3: AllJava/Net-protocol driver (Middleware)
Type 4: All Java/Native-protocol driver (Pure)

Type 1 JDBC Driver:


JDBC-ODBC Bridge driver:
The Type 1 driver translates all JDBC calls into ODBC calls and sends them to the
ODBC driver. ODBC is a generic API. The JDBC-ODBC Bridge driver is recommended
only for experimental use or when no other alternative is available.

Advantage
The JDBC-ODBC Bridge allows access to almost any database, since the database's
ODBC drivers are already available.
Disadvantages
1. Since the Bridge driver is not written fully in Java, Type 1 drivers are not portable.
2. A performance issue is seen as a JDBC call goes through the bridge to the ODBC

Department of Information Technology A.Y.2022-23 III-I SRGEC Page 44


FULL STACK APPLICATION DEVELOPMENT UNIT-IV

driver, then to the database, and this applies even in the reverse process. They are the
slowest of all driver types.
3. The client system requires the ODBC Installation to use the driver.
4. Not good for the Web.

Type 2 JDBC Driver


Native-API/partly Java driver
The distinctive characteristic of type 2 jdbc drivers are that Type 2 drivers convert
JDBC calls into database-specific calls i.e. this driver is specific to a particular
database. Some distinctive characteristic of type 2 jdbc drivers are shown below.
Example: Oracle will have oracle native api.

Advantage:
The distinctive characteristic of type 2 jdbc drivers are that they are typically offer
better performance than the JDBC-ODBC Bridge as the layers of communication
(tiers) are less than that of Type 1 and also it uses Native api which is Database
specific.
Disadvantages:
1. Native API must be installed in the Client System and hence type 2 drivers cannot
be used for the Internet.
2. Like Type 1 drivers, it’s not written in Java Language which forms a portability
issue.
3. If we change the Database we have to change the native api as it is specific to a

Department of Information Technology A.Y.2022-23 III-I SRGEC Page 45


FULL STACK APPLICATION DEVELOPMENT UNIT-IV

database
4. Mostly obsolete now
5. Usually not thread safe.
Type 3 JDBC Driver:
All Java/Net-protocol driver:
Type 3 database requests are passed through the network to the middle-tier server.
The middle-tier then translates the request to the database. If the middle-tier server
can in turn use Type1, Type 2 or Type 4 drivers.

Advantages:
1. This driver is server-based, so there is no need for any vendor database library to be
present on client machines.
2. This driver is fully written in Java and hence Portable. It is suitable for the web.
3. There are many opportunities to optimize portability, performance, and scalability.
4. The net protocol can be designed to make the client JDBC driver very small and fast
to load.
5. The type 3 driver typically provides support for features such as caching
(connections, query results, and so on), load balancing, and advanced
system administration such as logging and auditing.
6. This driver is very flexible allows access to multiple databases using one driver.
7. They are the most efficient amongst all driver types.
Disadvantages:

Department of Information Technology A.Y.2022-23 III-I SRGEC Page 46


FULL STACK APPLICATION DEVELOPMENT UNIT-IV

It requires another server application to install and maintain. Traversing the recordset
may take longer, since the data comes through the backend server.
Type 4 JDBC Driver:
Native-protocol/all-Java driver:
The Type 4 uses java networking libraries to communicate directly with the database
server.

Advantage
1. The major benefit of using a type 4 jdbc drivers are that they are completely written
in Java to achieve platform independence and eliminate deployment administration
issues. It is most suitable for the web.
2. Number of translation layers is very less i.e. type 4 JDBC drivers don't have to
translate database requests to ODBC or a native connectivity interface or to pass the
request on to another server, performance is typically quite good.
3. You don’t need to install special software on the client or server. Further, these
drivers can be downloaded dynamically.
Disadvantage
With type 4 drivers, the user needs a different driver for each database.

Department of Information Technology A.Y.2022-23 III-I SRGEC Page 47


FULL STACK APPLICATION DEVELOPMENT UNIT-IV

Database Programming using JDBC:


Steps to connect database:

1)Loading an appropriate driver

Class.forName(“Driver Name”);

Example:

Class.forName(“com.mysql.jdbc.Driver”);

2)Get the Connection Object

Connection con=DriverManager.getConnection(url,username,password);

Example:

Connection con=DriverManager.getConnection(“jdb

c:mysql://localhost:3306/test”,”root”,”root”);

3)Get the statement Object

Statement st=con.createStatement();

PrepareSatement ps=con.prepareStatement(“Pass Query Here Only”);

4)Pass sql queries to the database using executeQuery() or executeUpdate()

st.executeUpdate(“insert into register values(‘anand’,’kodad’)”);

st.executeUpdate(“insert into register values(‘teja’,’eluru’)”);

5)Get the result and show the result

ResultSet rs=st.executeQuery(“select * from register”);

while(rs.next())

System.out.println(“Name= ”+rs.getString(1));

System.out.println(“Location= ”+rs.getString(2));

Department of Information Technology A.Y.2022-23 III-I SRGEC Page 48


FULL STACK APPLICATION DEVELOPMENT UNIT-IV

6)Close the connection

Con.close();
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
Root Directory

Retrieve.jsp:
<%@page import="java.sql.*"%>
<%
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/gec","root","root");
PreparedStatement ps=con.prepareStatement("select * from employee");
ResultSet rs=ps.executeQuery();%>
<center>
<table border='1'>

Department of Information Technology A.Y.2022-23 III-I SRGEC Page 49


FULL STACK APPLICATION DEVELOPMENT UNIT-IV

<tr>
<th>Employee Number</th>
<th>Name</th>
</tr>
<%while(rs.next())
{%>
<tr>
<td><%=rs.getString(1)%></td>
<td><%=rs.getString(2)%></td>
</tr>
<%}
%>
</table>
<center>
<%
}
catch(Exception e)
{
out.println(e);
}
%>

Output:

Department of Information Technology A.Y.2022-23 III-I SRGEC Page 50


FULL STACK APPLICATION DEVELOPMENT UNIT-IV

 Write a JSP to Insert one record into dept table and Display them.
Root directory

Insert.jsp:
<%@page import="java.sql.*"%>
<%
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/gec","root","ro
ot");
PreparedStatement ps=con.prepareStatement("insert into dept
values(1,'sales','Gudlavalleru')");
int i=ps.executeUpdate();
if(i!=0)
{
out.println("<h1>Inserted Data Successfully...</h1>");
}
}
catch(Exception e)

Department of Information Technology A.Y.2022-23 III-I SRGEC Page 51


FULL STACK APPLICATION DEVELOPMENT UNIT-IV

{
out.println(e);
}
%>

Output:

WRITE A JSP TO STORE USER_ID AND PASSWORD and Display

Root Directory:

Department of Information Technology A.Y.2022-23 III-I SRGEC Page 52


FULL STACK APPLICATION DEVELOPMENT UNIT-IV

Login.html:
<HTML>
<HEAD>
</HEAD>
<BODY bgcolor='#999900'>
<center>
<form name='login' action='insert.jsp' method="post">
<table>
<tr><td colspan='2' align='center'><h2>Login Page</h2></td></tr>
<tr><td>Enter Name</td><td><input type='text'
name='name'></td></tr>
<tr><td>Enter Password</td><td><input type='password'
name='password'></td></tr>
<tr><td><input type='submit' value='Login'></td>
<td><input type='reset' value='Reset'></td>
</tr>
</table>
</form>
</center>
</BODY>
</HTML>
Insert.jsp:
<%@page import="java.sql.*"%>
<%
String name=request.getParameter("name");
String password=request.getParameter("password");
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/gec","root","root");
PreparedStatement ps1=con.prepareStatement("select * from user where
name=? and password=?");

Department of Information Technology A.Y.2022-23 III-I SRGEC Page 53


FULL STACK APPLICATION DEVELOPMENT UNIT-IV

ps1.setString(1,name);
ps1.setString(2,password);
ResultSet rs=ps1.executeQuery();
if(rs.next())
{
out.println("<h1>User Already Exist</h1>");
}
else
{
PreparedStatement ps2=con.prepareStatement("insert into user values(?,?)");
ps2.setString(1,name);
ps2.setString(2,password);
int i=ps2.executeUpdate();
out.println("<h1>Details Instered Sucessfully</h1>");
}
}
catch(Exception e)
{
out.println(e);
}
%>

Department of Information Technology A.Y.2022-23 III-I SRGEC Page 54


FULL STACK APPLICATION DEVELOPMENT UNIT-IV

Now try to insert same data

Department of Information Technology A.Y.2022-23 III-I SRGEC Page 55


FULL STACK APPLICATION DEVELOPMENT UNIT-IV

Accessing Database using Type 4 Driver


<%@page import="java.sql.*"%>
<%
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/gec","root","root");
PreparedStatement ps=con.prepareStatement("select * from employee");
ResultSet rs=ps.executeQuery();%>
<%while(rs.next()){
out.println(rs.getString(1));
out.println(rs.getString(2));
}
catch(Exception e)
{
out.println(e);
}
%>

Department of Information Technology A.Y.2022-23 III-I SRGEC Page 56

You might also like