Web Dev With Java
Web Dev With Java
JAVA
CIT-303
2|Page
PREFACE
The text book has been written to cover the syllabus of Web
Development with JAVA 3rd year D.A.E (CIT) according to the new scheme of
studies. The book has been written in order to cater the needs of latest
concepts and needs of the course i.e.Web Development with JAVA and to be
able to attempt D.A.E Examination of PBTE Lahore.
The aim of bringing out this book is to enable the students to have
sound knowledge of the subject. Every aspect has been discussed to present
the subject matter in the most concise, compact lucid & simple manner to
help the subject without any difficulty. Frequent use of illustrative figures has
been made for clarity. Short Questions and Self-tests have also been included
at the end of each chapter which will serve as a quick learning tool for
students.
AUTHORS
3|Page
MANUAL DEVELOPMENT COMMITTEE
(GCT Kamalia)
4|Page
Table of Contents
5|Page
2.2 INSTALATION OF IDE (ECLIPSE/ NETBEANS) ----------------------------------------------- 20
2.1.1 INSTALLATION PROCESS OF NETBEANS: ----------------------------------------------------------- 21
2.2 STANDARD DIRECTORY STRUCTURE OF JAVA WEB APPLICATION ------------------ 24
2.3 DEVELOPMENT OF WEB APPLICATION ----------------------------------------------------- 26
2.3.1 WEB APPLICATION DEVELOPMENT STAGES ------------------------------------------------------- 26
PART I: SHORT QUESTIONS ----------------------------------------------------------------------------- 29
PART II: LONG QUESTIONS ------------------------------------------------------------------------------ 29
MULTIPLE CHOICE QUESTIONS ------------------------------------------------------------------------ 30
REFERENCES --------------------------------------------------------------------------------------------------- 31
JAVASCRIPT ------------------------------------------------------------------------------------------------- 55
6|Page
4.4 USING JQUERY --------------------------------------------------------------------------------------- 59
4.4.1 JQUERY SYNTAX ------------------------------------------------------------------------------------- 59
4.4.2 JQUERY HIDE AND SHOW --------------------------------------------------------------------------- 59
4.5 JQUERY SELECTORS---------------------------------------------------------------------------------- 60
4.5.1 THE ELEMENT SELECTOR ---------------------------------------------------------------------------- 60
4.5.2 THE #ID SELECTOR ----------------------------------------------------------------------------------- 60
4.5.3 THE .CLASS SELECTOR ------------------------------------------------------------------------------- 61
4.6 APPLY VALIDATION ON HTML FORM -------------------------------------------------------------- 61
PART I: SHORT QUESTIONS ----------------------------------------------------------------------------- 63
PART II: LONG QUESTIONS ------------------------------------------------------------------------------ 63
MULTIPLE CHOICE QUESTIONS ------------------------------------------------------------------------ 64
REFRENCES -------------------------------------------------------------------------------------------------- 66
7|Page
6.3.1 JSP SCRIPTING ELEMENTS ------------------------------------------------------------------------ 83
6.3.2 JSP DIRECTIVE ELEMENTS ------------------------------------------------------------------------ 84
6.3.3 JSP STANDARD ACTION ELEMENTS -------------------------------------------------------------- 85
6.4 JSP STANDARD ACTIONS-------------------------------------------------------------------------- 85
PART I: SHORT QUESTIONS ---------------------------------------------------------------------------- 87
PART II: LONG QUESTIONS ------------------------------------------------------------------------------ 87
MULTIPLE CHOICE QUESTIONS ------------------------------------------------------------------------ 88
REFERENCES --------------------------------------------------------------------------------------------------- 89
8|Page
8.3 CONNECTING TO THE DATABASE ----------------------------------------------------------------- 106
8.3.1 IMPORT JDBC PACKAGES ------------------------------------------------------------------------- 107
8.3.2 REGISTER JDBC DRIVER--------------------------------------------------------------------------- 107
8.3.3 DATABASE URL FORMULATION ------------------------------------------------------------------ 108
8.3.4 CREATE CONNECTION OBJECT -------------------------------------------------------------------- 109
8.3.5 CLOSING JDBC CONNECTIONS ------------------------------------------------------------------- 109
8.4 ACCESSING DATA ---------------------------------------------------------------------------------- 110
8.4.1 SEQUENTIAL ACCESS ------------------------------------------------------------------------------ 110
8.4.2 RANDOM ACCESS --------------------------------------------------------------------------------- 110
8.5 THE EXECUTE QUERY METHOD ------------------------------------------------------------------- 110
8.5.1 THE SQL SELECT STATEMENT ------------------------------------------------------------------ 110
8.6 THE EXECUTE UPDATE METHOD ----------------------------------------------------------------- 112
8.6.1 DML: ---------------------------------------------------------------------------------------------- 112
8.6.2 DDL ------------------------------------------------------------------------------------------------ 113
PART I: SHORT QUESTIONS --------------------------------------------------------------------------- 115
PART II: LONG QUESTIONS ---------------------------------------------------------------------------- 115
MULTIPLE CHOICE QUESTIONS ---------------------------------------------------------------------- 116
REFERENCES ------------------------------------------------------------------------------------------------- 119
9|Page
10.1 INTRODUCTION ------------------------------------------------------------------------------- 128
10.1.1 BENEFITS OF JAVA SERVER FACES -------------------------------------------------------------- 128
10.2 USING JSF WITH JSP ------------------------------------------------------------------------- 129
10.3 JSF LIFE CYCLE --------------------------------------------------------------------------------- 130
10.4 EVENTS HANDLING -------------------------------------------------------------------------- 132
10.5 JSF TAG LIBRARY ----------------------------------------------------------------------------- 133
PART I: SHORT QUESTIONS --------------------------------------------------------------------------- 136
PART II: LONG QUESTIONS ---------------------------------------------------------------------------- 136
MULTIPLE CHOICE QUESTIONS ---------------------------------------------------------------------- 137
REFERENCES ------------------------------------------------------------------------------------------------- 139
10 | P a g e
Chapter # 1 Introduction to web development
Chapter No. 01
INTRODUCTION TO WEB DEVELOPMENT
At the end of this chapter students will be able to understand:
2|Page
Chapter # 1 Introduction to web development
Web Page: A web page is a document that is suitable for the World Wide
Web and web browsers. A web browser displays a web page on a monitor or
mobile device. Web page is a document commonly written in Hyper Text
Markup Language (HTML) that is accessible through the Internet or other
network using an Internet browser.
Website: A set of related web pages located under a single domain name,
and published on at least one web server.
For example www.tevta.gop.pk
HTML: HTML stands for Hyper Text Makrup Language. It is a standard
markup language for creating Web Pages. It describe the structure of web
pages using markups. HTML elements are the building blocks of HTML pages.
HTML elements are represented by tags. HTML tags label pieces of content
such as "heading", "paragraph", "table", and so on. Browsers do not display
the HTML tags, but use them to render the content of the page.
For Example:
<!DOCTYPE.html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
</body>
</html>
JAVASCRIPT: JavaScript is a programming language commonly used in web
development.
Client-Server: Client-server is a relationship in which one program (the client)
requests a service or resource from another program (the server).
3|Page
Chapter # 1 Introduction to web development
top of the TCP/IP suite of protocols (the foundation protocols for the
Internet). Latest version of HTTP is HTTP/2.
4|Page
Chapter # 1 Introduction to web development
A client (browser) submits an HTTP request to the server; then the server
returns a response to the client. The response contains status information
about the request and may also contain the requested content.
1-GET is used to request data from a specified resource. GET is one of the
most common HTTP methods. The query string (name/value pairs) is sent in
the URL of a GET request: For example,
GET /test/demo_form.php?name1=value1&name2=value2
5|Page
Chapter # 1 Introduction to web development
6|Page
Chapter # 1 Introduction to web development
characters
Information is visible to everyone in Information is not displayed in the
the URL URL thus not visible to everyone
Can be cached Can’t be cached
PHP
C++
Java and JSP
7|Page
Chapter # 1 Introduction to web development
<head>
<title>PHP Test</title>
</head>
<body>
<?php echo '<p>Hello World</p>'; ?>
</body>
</html>
C++: C++ is a general purpose language in computer programming. It is a
middle level language that can be used for several purposes in the computer
industry. C++ language may not always be the most preferred programming
language, but there are many aspects of software programming that cannot
be done without the use of C++.
Java and JSP:
Java - Java is a programming language that produces software for multiple
platforms. When a programmer writes a Java application, the compiled code
(known as bytecode) runs on most operating systems (OS), including
Windows, Linux and Mac OS.
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.
Java Servlet - Servlet technology is used to create web application (resides at
server side and generates dynamic web page).
8|Page
Chapter # 1 Introduction to web development
9|Page
Chapter # 1 Introduction to web development
The chief benefit of three-tier architecture is that because each tier runs on
its own infrastructure, each tier can be developed simultaneously by a
separate development team, and can be updated or scaled as needed
without impacting the other tiers. The three tiers in detail:
The presentation tier is the user interface and communication layer of the
application, where the end user interacts with the application. Its main
purpose is to display information to and collect information from the user.
This top-level tier can run on a web browser, as desktop application, or a
graphical user interface (GUI), for example. Web presentation tiers are
usually developed using HTML, CSS and JavaScript. Desktop applications can
be written in a variety of languages depending on the platform.
The application tier, also known as the logic tier or middle tier, is the heart of
the application. In this tier, information collected in the presentation tier is
processed - sometimes against other information in the data tier - using
business logic, a specific set of business rules. The application tier can also
add, delete or modify data in the data tier.
The application tier is typically developed using Python, Java, Perl, PHP or
Ruby, and communicates with the data tier using API calls.
10 | P a g e
Chapter # 1 Introduction to web development
The data tier, sometimes called database tier, data access tier or back-end, is
where the information processed by the application is stored and managed.
This can be a relational database management system such as PostgreSQL,
MySQL, MariaDB, Oracle, DB2, Informix or Microsoft SQL Server, or in
a NoSQL Database server such as Cassandra, CouchDB or MongoDB.
11 | P a g e
Chapter # 1 Introduction to web development
EXERCISE
PART I: SHORT QUESTIONS
1. What is a web Application?
2. What is a website and a web page?
3. What is HTML?
4. What is HTTP?
5. What is an HTTP Request?
6. What is a GET method?
7. Define POST method?
8. What is server side programming? Write names of server side
programming languages.
9. What is client side programming? Write names of some client side
programming languages.
10. Define JavaScript?
11. What is an application layer?
12. Write two benefits of three layer model of web application layers.
12 | P a g e
Chapter # 1 Introduction to web development
1 2 3 4 5 6 7 8 9 10
C B A D C A A D D A
13 | P a g e
Chapter # 1 Introduction to web development
References
client-server model (client-server architecture). (n.d.). Retrieved from
www.techtarget.com:
https://www.techtarget.com/searchnetworking/definition/client-
server#:~:text=Client%2Dserver%20is%20a%20relationship,another%20pro
gram%20(the%20server).
14 | P a g e
Chapter # 2 Setting up development environment
Chapter No. 02
SETTING UP DEVELOPMENT ENVIRONMENT
At the end of this chapter students will be able to:
15 | P a g e
Chapter # 2 Setting up development environment
16 | P a g e
Chapter # 2 Setting up development environment
17 | P a g e
Chapter # 2 Setting up development environment
Step 7. Then give path for Java jdk/ jre, and click on the "Next" button again
18 | P a g e
Chapter # 2 Setting up development environment
Step 9. Now click on the "Finish" button, here the installation of Tomcat is
completed. It may ask you to restart your system, so restart your system.
There will be no specific icon for
tomcat on your windows because
it is only services so you have to
start these servicesyou can see
this service in Bin folder in
c:\Apache Software
Foundation\Tomcat 9.0. Open
tomcat9w.exe. Apache Tomcat
9.0 Tomcat 9.0 Properties will
be open you can start or stop the
service with the help of start/
stop button. After starting
service you can open
localhost:8080 in your web
19 | P a g e
Chapter # 2 Setting up development environment
browser.
20 | P a g e
Chapter # 2 Setting up development environment
21 | P a g e
Chapter # 2 Setting up development environment
22 | P a g e
Chapter # 2 Setting up development environment
7. Wait for the while till the time the setup is properly installed into
the Computer
23 | P a g e
Chapter # 2 Setting up development environment
8. After complication of the setup you can click on the “Finish” button.
Now you can start the NetBeans for further use.
2.1.2 Installation Process of Eclipse:
1. In the first step, Open your browser and navigate to the URL
https://www.eclipse.org
2. Then, click on the “Download” button to download Eclipse IDE.
3. After downloading click on the “eclipse-inst-jre-win64.exe” file to install
Eclipse IDE.
4. Then, click on “Eclipse IDE for Java Developers”.
5. Then, click on the “Install” button.
6. Now click on “Create a new Java project”.
Now, you are ready to make new Java projects using eclipse IDE.
24 | P a g e
Chapter # 2 Setting up development environment
In order to run your java web application (servlet, JSP, etc.) we need
webserver. Before running the application you need to package the
resources inside it (servlets, SP's, xml files, etc.) in a standardized way as
shown below.
The Root Directory: The root directory of your web application can have
any name. In the above example the root directory name is mywebapp.
Under the root directory, you can put all files that should be accessible in
your web application.
This is the main or Root folder of web application. Usually name of this folder
becomes your web application context. For example, if our web application
name is mywebapp, then folder name mywebapp and web application will
be accessible via http://localhost:8080/mywebapp
The WEB-INF Directory: The WEB-INF directory is located just below the
web app root directory. This directory is a Meta information directory. Files
stored here are not supposed to be accessible from a browser (although
your web app can access them internally, in your code). Inside the WEB-INF
directory there are two important directories (classes and lib, and one
important file(web.xml). These are described below.
2. Classes Directory: The classes directory contains all compiled Java classes
that are part of your web application. The classes should be located in a
directory structure matching their package structure.
3.lib folder: The lib directory contains all JAR files used by your web
application. This directory most often contains any third party libraries that
your application is using. You could, however, also put your own classes into
a JAR file, and locate it here, rather than putting those classes in the classes
directory.
25 | P a g e
Chapter # 2 Setting up development environment
The WAR file is a standard format for web applications that has specific
directories and specific files. This includes a WEB-INF directory, a WEB-
INF/web.xml file used to describe the application, a WEB-INF/lib directory for
JAR files used by the application.
Web development makes sure the web app offers compatibility with both
Android and iOS, Identifies life cycle and optimization metrics, builds an
intelligent, iterative user interface.
26 | P a g e
Chapter # 2 Setting up development environment
27 | P a g e
Chapter # 2 Setting up development environment
After finalizing the initial mockups, they are shared with clients for review &
feedback. The design iterations and mockup changes go on until the client is
satisfied.
28 | P a g e
Chapter # 2 Setting up development environment
EXERCISE
PART I: SHORT QUESTIONS
1. What is Tomcat?
2. Write some advantages of tomcat?
3. What is NetBeans?
4. What is WEB-INF?
5. What is web.xml or Deployment Descriptor?
6. Write names of Web Application Development Stages.
29 | P a g e
Chapter # 2 Setting up development environment
MCQ’s ANSWERS:
1 2 3 4 5 6 7 8
C C A B B B A B
30 | P a g e
Chapter # 2 Setting up development environment
References
how-to-download-and-install-eclipse-on-windows. (n.d.). Retrieved from
www.geeksforgeeks.org: https://www.geeksforgeeks.org/how-to-
download-and-install-eclipse-on-windows/
31 | P a g e
Chapter # 3 HTML and CSS
Chapter No. 03
HTML and CSS
At the end of this chapter students will be able to:
HTML stands for Hypertext Markup Language, and it is the most widely used
language to write Web Pages. HTML is the standard markup language for
creating Web pages. It describes the structure of a Web page. It consists of a
series of elements. These elements tell the browser how to display the
content. Hypertext refers to the way in which Web pages (HTML documents)
are linked together. Thus, the link available on a webpage is called Hypertext.
HTML is a Markup Language which means you use HTML to simply "mark-up"
a text document with tags that tell a Web browser how to structure it to
display.
Originally, HTML was developed with the intent of defining the structure of
documents like headings, paragraphs, lists, etc.
An HTML document has two main parts: the head and the body. But firstly
every HTML document should start by declaring that it is an HTML document.
All HTML documents must start with a document type declaration:
<!DOCTYPEhtml>.
The HTML document itself begins with <html> and ends with </html>.
The visible part of the HTML document is between <body> and </body>.
Head of an HTML Document:
The head element contains Meta information about the HTML page. The
HEAD of an HTML document is where information (which might be ignored
32 | P a g e
Chapter # 3 HTML and CSS
by some Web browsers), such as the document's title, can be placed. The
HEAD of a document should be declared using the following HTML tags:
<head> Should appear after the <html> definition. </head> should appear at
the end of head.
A typical entry in the HEAD section of a document would be:
<title> Title of the document </title>. The title appears on the title bar of
your web browser.
Body of an HTML Document
The BODY of an HTML document is where all the information you wish to
view in your web browser. The text must be carefully marked-up, paragraphs
must begin with the <p> tag and the end of each paragraph must be clearly
marked using the HTML tag </p>. If the body text doesn't contain paragraph
breaks then the text will be viewed as one long paragraph! The BODY of a
document should be declared using the following HTML tags:
<body> tag should appear after the </head> tag. </body> tag should appear
after the document's text but before the </html> tag.
A Simple HTML Document (Example):
Write the following text in your html editor (notepad, NetBeans or any other
editor). You can use both lowercase and uppercase, as HTML is not case
sensitive.
<!DOCTYPE html>
<html>
<head>
<title> A Simple HTML Document </title>
</head>
<body>
<h1>Heading is added here</h1>
<p>This is a very simple HTML document</p>
<p>It only has two paragraphs</p>
</body>
</html>
Save this file as “first.html” here first is the name of your html document and
html is the extension that tells that the file you saved is an html file. The page
will look like as given in the picture below:
33 | P a g e
Chapter # 3 HTML and CSS
34 | P a g e
Chapter # 3 HTML and CSS
35 | P a g e
Chapter # 3 HTML and CSS
36 | P a g e
Chapter # 3 HTML and CSS
37 | P a g e
Chapter # 3 HTML and CSS
List Tags: To add list of values both ordered and unordered lists we use list
tags: Few tags are:-
Tag Description Example
<ul> Defines an unordered list <ul style="list-style-type:circle;
padding-
left:0px"><li>Islamabad</li><li
>Karachi</li><li>Lahore</li><li
>Peshawar</li><li>Quetta</li>
</ul>
<ol> Defines an ordered list <ol style="list-style-
type:lower-
roman"><li>Islamabad</li><li>
Karachi</li><li>Lahore</li><li>
Peshawar</li><li>Quetta</li><
/ol>
<li> Defines a list item "><li>Islamabad</li>
38 | P a g e
Chapter # 3 HTML and CSS
Meta Info:
Tag Description Example
<head> Defines information <head>
about the document. <link rel="stylesheet"
The contents inside head href="E:\CIT\Web Development with
39 | P a g e
Chapter # 3 HTML and CSS
Attributes:
An attribute indicates the characteristics of an object. For example, size and
color of a line or text are the attributes. Attributes are specified with opening
tag to provide additional information about an element or object of the
document.
Example:
<h1 align=”center”>Web Programming </h1>
<hr size=50 color=red>
Some important attributes are: background-color, Background, Text, Link,
Vlink, Alink, href, src, width, alt, style, etc.
3.2 DESCRIBE CSS STYLES
CSS stands for Cascading Style Sheets. CSS describes how HTML elements are
to be displayed on screen, paper, or in other media. CSS saves a lot of work.
It can control the layout of multiple web pages all at once.
CSS can be added to HTML elements in 3 ways:
Inline - by using the style attribute in HTML elements
Internal - by using a <style> element in the <head> section
External - by using an external CSS file
Benefits of using CSS:
A style sheet gives the user several benefits:
better control over layout
better control over text display
40 | P a g e
Chapter # 3 HTML and CSS
Example:
body {
background-color: lightblue;
}
h1 {
color: white;
text-align: center;
}
p{
font-family: verdana;
font-size: 20px;
}
3.2.1 Inline CSS
An inline CSS is used to apply a unique style to a single HTML element. An
inline CSS uses the style attribute of an HTML element. This example sets the
text color of the <h1> element to blue:
Example:
<h1 style="color:blue;">This is a Blue Heading</h1>
41 | P a g e
Chapter # 3 HTML and CSS
color: blue;
}
p{
color: red;
}
</style>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
3.2.3 External CSS
An external style sheet is used to define the style for many HTML pages. With
an external style sheet, you can change the look of an entire web site, by
changing one file. To use an external style sheet, add it as a link to in the
<head> section of the HTML page:
Example:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
</head><body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
An external style sheet can be written in any text editor. The file must not
contain any HTML code, and must be saved with a .css extension.
Here is how the "styles.css" looks:
body {
background-color: powderblue;
}
h1 {
color: blue;
}
42 | P a g e
Chapter # 3 HTML and CSS
p{
color: red;
}
CSS Fonts: The CSS color property defines the text color to be used. The
CSS font-family property defines the font to be used. The CSS font-size
property defines the text size to be used.
Example
<!DOCTYPE html>
<html>
<head>
<style>
h1 {
color: blue;
font-family: verdana;
font-size: 300%;
}
p{
color: red;
font-family: courier;
font-size: 160%;
}
</style>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
CSS Border: The CSS border property defines a border around an HTML
element:
Example
p{
border: 1px solid powderblue;
}
43 | P a g e
Chapter # 3 HTML and CSS
CSS Padding: The CSS padding property defines a padding (space) between
the text and the border:
Example
p{
border: 1px solid powderblue;
padding: 30px;
}
External References :
External style sheets can be referenced with a full URL or with a path relative
to the current web page. This example uses a full URL to link to a style sheet:
Example
<link rel="stylesheet" href="https://www.w3schools.com/html/styles. css">
Each table row is defined with the <tr> tag. A table header is defined with the
<th> tag. By default, table headings are bold and centered. A table data/cell
is defined with the <td> tag.
44 | P a g e
Chapter # 3 HTML and CSS
Colspan and Rowspan Attributes: You will use colspan attribute if you want
to merge two or more columns into a single column. Similar way you will use
rowspan if you want to merge two or more rows.
45 | P a g e
Chapter # 3 HTML and CSS
</tr>
<tr>
<td>102</td>
<td>DAE</td>
<td>990</td>
<td>PBTE Lahore</td>
</tr>
</table>
There are various form elements available like text fields, textarea fields,
dropdown menus, radio buttons, checkboxes, etc. Form Example:
First name:
Last name:
SUBMIT
The <form> Element: The HTML <form> element defines a form that is used
to collect user input:
<form> … </form>
An HTML form contains form elements.
Form elements are different types of input elements, like text fields,
checkboxes, radio buttons, submit buttons, and more.
The <input> Element:
The <input> element is the most important form element.
The <input> element can be displayed in several ways, depending on the
type attribute.
Here are some examples:
Type Description
46 | P a g e
Chapter # 3 HTML and CSS
47 | P a g e
Chapter # 3 HTML and CSS
48 | P a g e
Chapter # 3 HTML and CSS
<title>Page Layout</title>
<style>
.head1 {
font-size:40px;
color:#009900;
font-weight:bold;
}
.head2 {
font-size:17px;
margin-left:10px;
margin-bottom:15px;
}
body {
margin: 0 auto;
background-position:center;
background-size: contain;
}
.menu {
position: sticky;
top: 0;
background-color: #009900;
padding:10px 0px 10px 0px;
color:white;
margin: 0 auto;
overflow: hidden;
}
.menu a {
float: left;
color: white;
text-align: center;
padding: 14px 16px;
text-decoration: none;
font-size: 20px;
}
.menu-log {
right: auto;
49 | P a g e
Chapter # 3 HTML and CSS
float: right;
}
footer {
width: 100%;
bottom: 0px;
background-color: #000;
color: #fff;
position: absolute;
padding-top:20px;
padding-bottom:50px;
text-align:center;
font-size:30px;
font-weight:bold;
}
.body_sec {
margin-left:20px;
}
</style>
</head>
<body>
<!-- Header Section -->
<header>
<div class="head1">Computer Science</div>
<div class="head2">A computer science web Page</div>
</header>
<!-- Menu Navigation Bar -->
<nav>
<div class="menu">
<a href="#home">HOME</a>
<a href="#news">NEWS</a>
<a href="#notification">NOTIFICATIONS</a>
<div class="menu-log">
<a href="#login">LOGIN</a>
</div>
</div>
</nav>
50 | P a g e
Chapter # 3 HTML and CSS
51 | P a g e
Chapter # 3 HTML and CSS
EXERCISE
PART I: SHORT QUESTIONS
13. What is html tag and give one example?
14. Write any five html tags?
15. What is CSS?
16. What is an Internal CSS?
17. Explain external CSS
18. Why we use CSS?
19. Describe cellpadding and cellspacing attributes.
20. How can you add a header in an html page?
52 | P a g e
Chapter # 3 HTML and CSS
1 2 3 4 5 6 7 8 9 10
B D B B A B A A B C
53 | P a g e
Chapter # 3 HTML and CSS
Reference:
HTML Tutorial. (n.d.). Retrieved from https://www.w3schools.com:
https://www.w3schools.com/html/html_intro.asp
54 | P a g e
Chapter # 4 Javascript
Chapter. No. 04
JAVASCRIPT
4.1 Introduction to Javascript
4.2 Hiding and Showing Elements
4.3 Styling Elements
4.4 Using Jquery
4.5 Jquery Selectors
4.6 Validating Forms
4.1 What is JavScript?
JavaScript is a lightweight, interpreted programming language. It is designed
for creating network-centric applications. It is complimentary to and
integrated with Java. JavaScript is very easy to implement because it is
integrated with HTML. It is open and cross-platform.
<html>
<body>
<script language = "javascript" type = "text/javascript">
55 | P a g e
Chapter # 4 Javascript
<!--
document.write("Hello World!")
//-->
</script>
</body>
</html>
4.1.1 JavaScript Can Change HTML Content
This example uses the method to "find" an HTML element (with id="demo")
and changes the element content (innerHTML) to "Hello JavaScript":
Example
document.getElementById("demo").style.display="none";
or
document.getElementById('demo').style.display='none';
4.1.3 JavaScript Can Show HTML Elements
Showing hidden HTML elements can also be done by changing the display style
Example:
document.getElementById("demo").style.display="block";
or
document.getElementById('demo').style.display='block';
4.1.4 JavaScript Can Change HTML Styles (CSS)
Changing the style of an HTML element, is a variant of changing an HTML attribute:
Example:
56 | P a g e
Chapter # 4 Javascript
document.getElementById("demo").style.fontSize="35px";
or
document.getElementById('demo').style.fontSize='35px';
JavaScript Functions?
Function myFunction(p1,p2){
return p1 * p2; // The function returns the product of p1andp2
}
The HTML DOM allows JavaScript to change the style of HTML elements.
<script>
document.getElementById("p2").style.color = "blue";
</script>
</body>
</html>
Using Events
The HTML DOM allows you to execute code when an event occurs. Events
are generated by the browser when "things happen" to HTML elements:
57 | P a g e
Chapter # 4 Javascript
An element is clicked on
The page has loaded
Input fields are changed
This example changes the style of the HTML element with id="id1", when the
user clicks a button
Example:
<!DOCTYPE html>
<html>
<body>
<button type="button"
onclick="document.getElementById('id1').style.color = 'red'">
Click Me!</button>
</body>
</html>
58 | P a g e
Chapter # 4 Javascript
With jQuery, you can hide and show HTML elements with the hide() and
show() methods:
$("#hide").click(function(){
$("p").hide();
});
59 | P a g e
Chapter # 4 Javascript
$("#show").click(function(){
$("p").show();
});
$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
}):
An id should be unique within a page, so you should use the #id selector
when you want to find a single, unique element. To find an element with a
specific id, write a hash character, followed by the id of the HTML element:
60 | P a g e
Chapter # 4 Javascript
$("#test")
Example
When a user clicks on a button, the element with id="test" will be hidden:
$(document).ready(function(){
$("button").click(function(){
$("#test").hide();
});
});
Example
When a user clicks on a button, the elements with class="test" will be
hidden:
$(document).ready(function(){
$("button").click(function(){
$(".test").hide();
});
});
<html>
<body>
61 | P a g e
Chapter # 4 Javascript
<h2>JavaScript Validation</h2>
<input id="numb">
<p id="demo"></p>
<script>
functionmyFunction() {
let x = document.getElementById("numb").value;
</body>
</html>
62 | P a g e
Chapter # 4 Javascript
EXERCISE
PART I: SHORT QUESTIONS
1. What is JavaScript?
2. What can JavaScript Do?
3. Write aexample of Hide HTML Element through javaScript?
4. Explain JavaScript Functions?
5. Write the syntax of JavaScript Functions.
6. Define jQuery Selector?
7. Define the #id Selector?
8. Define the .class Selector?
9. Write any two Examples of jQuery Selectors with Description?
10. Explain jQuery Hide and Show?
11. How to create sliding effects on HTML elements with jQuery?
63 | P a g e
Chapter # 4 Javascript
64 | P a g e
Chapter # 4 Javascript
Answers
1 2 3 4 5 6 7 8 9 10
A A A B A C B B D C
11 12
A C
65 | P a g e
Chapter # 4 Javascript
REFRENCES
1. https://www.tutorialspoint.com/javascript/index.html
2. https://www.w3schools.com/jquery/jquery_syntax.asp
66 | P a g e
Chapter # 5 Java Servlet
Chepter No. 5
JAVA SERVLETS
5.1 What is a Servlet?
5.2 Advantages of Servlet
5.3 Servlet Types
5.4 Writing Basic Hello World Servlet
5.5 Servlet Life Cycle
5.6 Servlet and Forms
5.7 Servlet and Input Validation
67 | P a g e
Chapter # 5 Java Servlet
There are many advantages of Servlet over CGI. The web container
creates threads for handling the multiple requests to the Servlet. Threads
have many benefits over the processes such as they share a common
memory area, lightweight, cost of communication between the threads are
low. The advantages of Servlet are as follows:
68 | P a g e
Chapter # 5 Java Servlet
object. The request object tells the servlet about the request made by client
while the response object is used to return a response back to the client.
69 | P a g e
Chapter # 5 Java Servlet
<web-app>
<servlet>
<servlet-name>s10</servlet-name>
<servlet-class>Hello</servlet-class>
</servlet>
<!-- Servlet Mapping -->
<servlet-mapping>
<servlet-name>s10</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
WEB-INF/classes/Hello.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
out.println("<HTML>" +
"<HEAD><TITLE>WTAD.practical-10 @iAmLearningHere</TITLE></HEAD>"
+
"<body bgcolor=YellowGreen>" +
"HELLO WORLD" +
70 | P a g e
Chapter # 5 Java Servlet
"</body></HTML>");
}
}
Preview
How to Run?
> Start Apache Server
> Start localhost and open program folder
> type url '/hello'
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.
71 | P a g e
Chapter # 5 Java Servlet
}
2 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(ServletRequestrequest,ServletResponse response)
throwsServletException,IOException{
}
3 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.
publicvoiddoGet(HttpServletRequestrequest,HttpServletResponse response)
throwsServletException,IOException{
// Servlet code
}
4 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.
publicvoiddoPost(HttpServletRequestrequest,HttpServletResponse response)
throwsServletException,IOException{
// Servlet code
}
5 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
publicvoid destroy(){
// Finalization code...
}
Architecture Diagram
72 | P a g e
Chapter # 5 Java Servlet
The servlet container loads the servlet before invoking the service()
method.
Then the servlet container handles multiple requests by spawning
multiple threads, each thread executing the service() method of a
single instance of the servlet.
Flow:
1. Request will be sent from HTML form
2. It will be sent as either GET/POST method in the Java servlet side
3. Response will be provided from servlet as an HTML form
73 | P a g e
Chapter # 5 Java Servlet
you will learn that how to create simple registration form in servlet.
create a table first as given below:
13. <br/><br/>
14. <input type="submit" value="register"/>
74 | P a g e
Chapter # 5 Java Servlet
15. </form>
16. </body>
17. </html>
Register.java
This servlet class receives all the data entered by user and stores it into the
database. Here, we are performing the database logic. But you may separate
it, which will be better for the web application.
1. import java.io.*;
2. import java.sql.*;
3. import javax.servlet.ServletException;
4. import javax.servlet.http.*;
8. response.setContentType("text/html");
9. PrintWriter out = response.getWriter();
10.
11. String n=request.getParameter("userName");
12. String p=request.getParameter("userPass");
13. String e=request.getParameter("userEmail");
14. String c=request.getParameter("userCountry");
15. try{
16. Class.forName("oracle.jdbc.driver.OracleDriver");
17. Connection con=DriverManager.getConnection(
18. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
21. ps.setString(1,n);
22. ps.setString(2,p);
75 | P a g e
Chapter # 5 Java Servlet
23. ps.setString(3,e);
24. ps.setString(4,c);
29. out.close();
30. }
31. }
web.xml file
The is the configuration file, providing information about the servlet.
1. <web-app>
2. <servlet>
3. <servlet-name>Register</servlet-name>
4. <servlet-class>Register</servlet-class>
5. </servlet>
6. <servlet-mapping>
7. <servlet-name>Register</servlet-name>
8. <url-pattern>/servlet/Register</url-pattern>
9. </servlet-mapping>
10. <welcome-file-list>
11. <welcome-file>register.html</welcome-file>
12. </welcome-file-list>
13. </web-app>
76 | P a g e
Chapter # 5 Java Servlet
The given date value is in Getting sales report for given data
MM/DD/YYYY pattern or not? value.
(Pattern verification)
77 | P a g e
Chapter # 5 Java Servlet
EXERCISE
PART I: SHORT QUESTIONS
1. What is a Servlet?
2. Write any two Advantages of Servlet?
3. Define a Generic servlets?
4. What is a HTTP servlets explain with diagram?
5. Enlist steps of Writing Basic Hello World Servlet?
6. What are the processes of Servlet Life Cycle?
7. Write any two methods of servlet life cycle?
8. Explain the the service() Method of servlet life cycle
9. Draw the Architecture Diagram servlet life-cycle?
10.Explain Servlet and Forms?
11.What is a Register.java?
12.What is Form Validating?
78 | P a g e
Chapter # 5 Java Servlet
8. The method is called only once at the end of the life cycle
of a servlet.
A) destroy() C) Close()
B)both D) None
79 | P a g e
Chapter # 5 Java Servlet
A) service() C) init()
B) Destroy() D) None
1 2 3 4 5 6 7 8 9
C A A A D C A A A
References
https://www.javatpoint.com/example-of-registration-form-in-servlet
https://www.knowprogram.com/servlet/form-validation-in-java-servlet/
80 | P a g e
Chapter # 6 Java Server Pages
Chapter No. 6
JAVA SERVER PAGES
6.1 Introduction
6.2 Life Cycle of JSP
6.3 JSP Elements
6.4 JSP Standard Actions
6.1 Introduction to JSP:
Java Server Pages (JSP) is a server-side programming technology that enables
the creation of dynamic, platform-independent method for building Web-
based applications. JSP have access to the entire family of Java APIs,
including the JDBC API to access enterprise databases. 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.
Features of JSP
Coding in JSP is easy: - As it is just adding JAVA code to HTML/XML.
Reduction in the length of Code: - In JSP we use action tags, custom
tags etc.
Connection to Database is easier:-It is easier to connect website to
database and allows reading or writing data easily to the database.
Make Interactive websites: - In this we can create dynamic web pages
which helps user to interact in real time environment.
Portable, Powerful, flexible and easy to maintain: - as these are
browser and server independent.
No Redeployment and No Re-Compilation:- It is dynamic, secure and
platform independent so no need to re-compilation.
81 | P a g e
Chapter # 6 Java Server Pages
Life Cycle is defined as translation of JSP Page into servlet as a JSP Page
needs to be converted into servlet first in order to process the service
requests. The Life Cycle starts with the creation of JSP and ends with the
disintegration of that.
82 | P a g e
Chapter # 6 Java Server Pages
1. Translation of the JSP Page: This is the first step of the JSP life cycle. This
translation phase deals with the Syntactic correctness of JSP. Here
test.jsp file is translated to test.java.
2. Compilation of JSP page: Here the generated java servlet file (test.java) is
compiled to a class file (test.class).
3. Classloading: Servlet class which has been loaded from the JSP source is
now loaded into the container.
4. Instantiation: Here an instance of the class is generated. The container
manages one or more instances by providing responses to requests.
5. Initialization: jspInit() method is called only once during the life cycle
immediately after the generation of Servlet instance from JSP.
6. Request processing: _jspService() method is used to serve the raised
requests by JSP. It takes request and response objects as parameters.
This method cannot be overridden.
7. JSP Cleanup: In order to remove the JSP from use by the container or to
destroy the method for servlets jspDestroy()method is used. This method
is called once, if you need to perform any cleanup task like closing open
files, releasing database connections jspDestroy() can be overridden.
83 | P a g e
Chapter # 6 Java Server Pages
JSP Scripting Elements are used for writing the Java Code inside the JSP page.
There are different types of scripting elements these elements are used for
various purposes. Following are the scripting elements :
Directive elements in JSP provides the special information to the JSP engine.
It gives the information about the JSP page. Each JSP page goes through the
two phases i.e. translation phase and request time phase. At the translation
phase JSP page is translated into a Servlet. The JSP engine translates the JSP
page into a Servlet, directive elements are handled at the translation time.
These directives are translated to the Servlet only for once, until there is no
changes made to the directive elements in the Servlet.
JSP Directive Elements can be declared within the following special
characters '<%@ %>'. Syntax for using directive in the JSP page is as follows :
<%@ directiveName attr1="value1" attr2="value2" %>
84 | P a g e
Chapter # 6 Java Server Pages
The action tag is also implemented to streamline flow between pages and to
employ a Java Bean. As it coincides with the XML standard, the syntax for the
action element is:
Syntax:
85 | P a g e
Chapter # 6 Java Server Pages
Two basic attributes are commonly used for all action tags. These are:
1. Id: The id attribute defines unique action elements and allows actions
to be referenced within the JSP page. When the action creates an
object's instance, the id attribute is used to refer to it.
2. Scope: The scope attribute is used for identifying an action's life
cycle. It correlates with the id attribute because the scope attribute is
used to establish that particular object's lifespan associated with the
ID.
86 | P a g e
Chapter # 6 Java Server Pages
EXERCISE
PART I: SHORT QUESTIONS
1. Define JSP?
2. Enlist Features of JSP
3. Define Life Cycle of JSP?
4. Enlist the steps of JSP life cycle.
5. What is Instantiation JSP Life cycle?
6. What is JSP expression tag?
7. What is JSP Declaration Tag?
8. Difference between JSP Scriptlet tag and Declaration tag
9. What is a JSP Standard Actions?
10.Write any two JSP Action Tags with Description?
87 | P a g e
Chapter # 6 Java Server Pages
c) both d) none
88 | P a g e
Chapter # 6 Java Server Pages
1 2 3 4 5 6 7 8 9 10
A A C A A A B A A A
References
https://www.javatpoint.com/jsp-tutorial
https://www.w3schools.in/jsp/jsp-page-life-cycle
https://www.geeksforgeeks.org/life-cycle-of-jsp/
https://www.roseindia.net/jsp/jsp-elements
89 | P a g e
Chapter No. 7 Session Management
Chapter No. 07
SESSION MANAGEMENT
At the end of this chapter students will be able to understand:
7.1 Session
7.2 Cookie
7.3 URL Rewriting
7.4 Hidden Field
7.5 Working with HTTP Session
90 | P a g e
Chapter No. 7 Session Management
91 | P a g e
Chapter No. 7 Session Management
Session
Persistent
Session cookies are cookies that last for a session. A session starts
when you launch a website or web app and ends when you leave the website
or close your browser window. Session cookies contain information that
is stored in a temporary memory location which is deleted after the session
ends. Unlike other cookies, session cookies are never stored on your device.
Therefore, they are also known as transient cookies, non-persistent cookies,
or temporary cookies.
92 | P a g e
Chapter No. 7 Session Management
Persistent cookies are cookies that are stored on a user’s device for a
considerably longer time. Therefore, they are also known as permanent
cookies. Persistent cookies recognize users and remember their browser
settings or preferences on their subsequent visits and help websites provide
better user experiences.
After logging into their email accounts, users often see a prompt
asking them whether they want to save their login information to access
their email account easily in the future. Once they agree to save their
information, users can open their email account without keying in their login
information again, and they'll find their account as it was when they last
logged in.
Persistent cookies remain on the device until you erase them or they
expire. They are ideal for storing information, for instance, persistent cookies
help you stay logged in on a website even if you close your browser window.
url?name1=value1&name2=value2&??
93 | P a g e
Chapter No. 7 Session Management
94 | P a g e
Chapter No. 7 Session Management
95 | P a g e
Chapter No. 7 Session Management
EXERCISE
PART I: SHORT QUESTIONS
1. What is session
2. What is cookies
3. What is session cookies
4. What is persistent cookies
5. Explain URL rewriting
6. Explain hidden field
7. Explain working with http session
96 | P a g e
Chapter No. 7 Session Management
a) URL rewriting
b) History
c) Cookies
d) SSL sessions
a) URL rewriting
c) SSL sessions
d) Cookies
a) URL rewriting
c) SSL sessions
d) Cookies
a) 4 KB
b) 4 MB
c) 4 bytes
d) 40 KB
97 | P a g e
Chapter No. 7 Session Management
5. Which method creates unique fields in the HTML which are not shown to
the user?
a) User authentication
b) URL writing
a) ContextHolder
b) SecurityHolder
c) AnonymousHolder
d) SecurityContextHolder
a. session identifier
b. creation time
8. Which class provides stream to read binary data such as image etc. from
a. ServltInputStream
b. ServletOutputStream
c. Both A & B
98 | P a g e
Chapter No. 7 Session Management
a. RMI Communication
b. HTTP Communication
c. Socket Communication
10. Which method is used to send the same request and response objects to
a. forward()
b. sendRedirect()
c. Both A & B
MCQ’s Answes
1 2 3 4 5 6 7 8 9 10
B D A A C D D A D A
99 | P a g e
Chapter No. 7 Session Management
References
Session Retrieved from
https://www.studytonight.com/servlet/url-rewriting-for-
session-management.php
Cookie Retrieved from
https://www.cookieyes.com/blog/session-cookies
URL Rewriting Retrieved from https://www.javatpoint.com/url-
rewriting-in-session-tracking#
Hidden Field Retrieved from https://www.javatpoint.com/hidden-
form-field-in-session-tracking#session2ex
Working with HTTP Session Retrieved from
https://www.studytonight.com/servlet/httpsession.php
100 | P a g e
Chapter No # 8 JDBC Programming
Chapter No. 08
JDBC PROGRAMMING
Objectives
After completion of this chapter students will be able to:
8.1- Introduction
8.2- Configure MySQL
8.3- Connecting to the Database
8.4- Accessing Data
8.5- The execute Query Method
8.6 The execute Update Method
JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and
execute the query with the database. It is a part of JavaSE (Java Standard
Edition). JDBC API uses JDBC drivers to connect with the database. There are
four types of JDBC drivers:
We can use JDBC API to access tabular data stored in any relational database.
By the help of JDBC API, we can save, update, delete and fetch data from the
database. It is like Open Database Connectivity (ODBC) provided by
Microsoft.
101 | P a g e
Chapter No # 8 JDBC Programming
Figure 1: JDBC
The current version of JDBC is 4.3. It is the stable release since 21st
September, 2017. It is based on the X/Open SQL Call Level Interface.
The java.sql package contains classes and interfaces for JDBC API.
Before JDBC, ODBC API was the database API to connect and execute the
query with the database. But, ODBC API uses ODBC driver which is written in
C language (i.e. platform dependent and unsecured). That is why Java has
defined its own API (JDBC API) that uses JDBC drivers (written in Java
language).
We can use JDBC API to handle database using Java program and can
perform the following activities:
102 | P a g e
Chapter No # 8 JDBC Programming
MySQL runs on virtually all of the platforms, by including UNIX, Linux and
Windows. It is wholly multi-threaded by using kernel threads, and provides
application program to interfaces (APIs) for various programming languages,
including C, C++, Java, Eiffel, Perl, PHP, Python, and Tcl.
MySQL is most commonly found on Web servers. A website that uses My SQL
might include Web pages that access information through a database. These
pages are frequently referred to as "dynamic," meaning the content of each
of page is produced from a database as the page loads. Websites that utilized
dynamic Web pages are frequently referred to as database-driven websites.
103 | P a g e
Chapter No # 8 JDBC Programming
104 | P a g e
Chapter No # 8 JDBC Programming
Here we will show you step by step how to install MySQL on the Windows
platform using the MySQL Installer.
The simplest and recommended method is to download MySQL Installer for
Windows from https://dev.mysql.com/downloads/installer/ and execute it.
After downloading, unzip it, and double click the MSI installer .exe file.
Then follow the steps below:
1. "Choosing a Setup Type" screen: Choose "Full" setup type. This installs all
MySQL products and features. Then click the "Next" button to continue.
2. "Check Requirements" screen: The installer checks if your pc has the
requirements needed. If there is some failing requirements, click on each
item to try to resolve them by clicking on the Execute button that will install
all requirements automatically. Click "Next".
3. "Installation" screen: See what products that will be installed. Click
"Execute" to download and install the Products. After finishing the
installation, click "Next".
4. "Product Configuration" screen: See what products that will be configured.
Click the "MySQL Server 8.0.23" option to configure the MySQL Server. Click
the "Next" button. Choose the "Standalone MySQL Server/Classic MySQL
Replication" option and click on the "Next" button. In page "Type and
Networking" set Config Type to "Development Computer" and "Connectivity"
to "TCP/IP" and "Port" to "3006". Then, click the "Next" button.
105 | P a g e
Chapter No # 8 JDBC Programming
106 | P a g e
Chapter No # 8 JDBC Programming
Register JDBC Driver − This step causes the JVM to load the desired
driver implementation into memory so it can fulfill your JDBC
requests.
Database URL Formulation − This is to create a properly formatted
address that points to the database to which you wish to connect.
Create Connection Object − Finally, code a call to
the DriverManager object's getConnection( ) method to establish
actual database connection.
The Import statements tell the Java compiler where to find the classes you
reference in your code and are placed at the very beginning of your source
code.
To use the standard JDBC package, which allows you to select, insert, update,
and delete data in SQL tables, add the following imports to your source code
−
You must register the driver in your program before you use it. Registering
the driver is the process by which the Oracle driver's class file is loaded into
the memory, so it can be utilized as an implementation of the JDBC
interfaces.
You need to do this registration only once in your program.
Class.forName()
The most common approach to register a driver is to use
Java's Class.forName() method, to dynamically load the driver's class file into
memory, which automatically registers it. This method is preferable because
it allows you to make the driver registration configurable and portable.
The following example uses Class.forName( ) to register the Oracle driver –
107 | P a g e
Chapter No # 8 JDBC Programming
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
After you've loaded the driver, you can establish a connection using
the DriverManager.getConnection() method. For easy reference, let me list
the three overloaded DriverManager.getConnection() methods −
getConnection(String url)
getConnection(String url, Properties prop)
getConnection(String url, String user, String password)
Here each form requires a database URL. A database URL is an address that
points to your database.
Following table lists down the popular JDBC driver names and database URL.
108 | P a g e
Chapter No # 8 JDBC Programming
All the highlighted part in URL format is static and you need to change only
the remaining part as per your database setup.
If you have a host at TCP/IP address 192.0.0.1 with a host name of amrood,
and your Oracle listener is configured to listen on port 1521, and your
database name is EMP, then complete database URL would be −
jdbc:oracle:thin:@amrood:1521:EMP
At the end of your JDBC program, it is required explicitly to close all the
connections to the database to end each database session. However, if you
forget, Java's garbage collector will close the connection when it cleans up
stale objects.
109 | P a g e
Chapter No # 8 JDBC Programming
To close the above opened connection, you should call close() method as
follows −
conn.close();
Data access refers to a user’s ability to access or retrieve data stored within a
database or other repository. Users who have data access can store, retrieve,
move or manipulate stored data, which can be stored on a wide range of
hard drives and external devices.
There are two ways to access stored data: sequential access and random
access.
Oftentimes when using random access, the data is split into multiple parts or
pieces and located anywhere randomly on a disk. Sequential files are usually
faster to load and retrieve because they require fewer seek operations.
110 | P a g e
Chapter No # 8 JDBC Programming
SELECT Syntax
Here, column1, column2, ... are the field names of the table you want to
select data from. If you want to select all the fields available in the table, use
the following syntax:
The following SQL statement selects all the customers from the country
"Mexico", in the "Customers" table:
111 | P a g e
Chapter No # 8 JDBC Programming
8.6.1 DML:
It stands for Data Manipulation Language. The DML commands deal with the
manipulation of existing records of a database. It is responsible for all
changes that occur in the database. The changes made in the database using
this command can't save permanently because its commands are not auto-
committed. Therefore, changes can be rollback. The following commands
come under DML language:
INSERT: It is a SQL query that allows us to add data into a table's row.
The following SQL statement inserts a new record in the "Customers" table.
INSERT INTO Customers (CustomerName, ContactName, Address, City,
PostalCode, Country)
VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen
21', 'Stavanger', '4006', 'Norway');
o UPDATE: This command is used to alter or modify the contents of a
table.
UPDATE Customers
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;
112 | P a g e
Chapter No # 8 JDBC Programming
8.6.2 DDL
DDL stands for Data Definition Language. As the name suggests, the DDL
commands help to define the structure of the databases or schema.
When we execute DDL statements, it takes effect immediately. The
changes made in the database using this command are saved
permanently because its commands are auto-committed. The following
commands come under DDL language:
113 | P a g e
Chapter No # 8 JDBC Programming
City varchar(255)
);
114 | P a g e
Chapter No # 8 JDBC Programming
EXERCISE
115 | P a g e
Chapter No # 8 JDBC Programming
4) How many transaction isolation levels provide the JDBC through the
Connection interface?
a. 3
b. 4
c. 7
d. 2
5) Which of the following method is static and synchronized in JDBC API?
a. getConnection()
b. prepareCall()
c. executeUpdate()
d. executeQuery()
6) Which methods are required to load a database driver in JDBC?
a. getConnection()
b. registerDriver()
c. forName()
d. Both b and c
7) Parameterized queries can be executed by?
a. ParameterizedStatement
116 | P a g e
Chapter No # 8 JDBC Programming
b. PreparedStatement
c. CallableStatement and Parameterized Statement
d. All kinds of Statements
8) Which of the following is not a valid statement in JDBC?
a. Statement
b. PreparedStatement
c. QueryStatement
d. CallableStatement
9) Stored procedure can be called by using the .......
a. CallableStatement
b. Statement
c. CalledStatement
d. PreparedStatement
10) A good way to debug JDBC-related problems is to enable???..?
a. JDBC tracing
b. Exception handling
c. Both a and b
d. Only b
11) Which JDBC driver can be used in servlet and applet both?
a. Type 3
b. Type 4
c. Type 3 and Type 2
d. Type 3 and Type 4
12) JDBC-ODBC driver is also known as?
a. Type 4
b. Type 3
c. Type 1
d. Type 2
13) How many stages are used by Java programmers while using JDBC in their
programs?
a. 3
b. 2
c. 5
d. 6
14) How many ways to register a driver?
a. 2
117 | P a g e
Chapter No # 8 JDBC Programming
b. 3
c. 4
d. 5
MCQ’s Answers
1 2 3 4 5 6 7 8 9 10
D D C B A D B C B A
11 12 13 14
D C D C
118 | P a g e
Chapter No # 8 JDBC Programming
References
Introduction JDBC Programming Retrieved from
https://www.javatpoint.com/java-jdbc
https://www.w3schools.com/sql/sql_select.asp
https://www.javatpoint.com/ddl-vs-
dml#:~:text=Key%20Differences%20between%20DDL%20and%20DM
L%20Commands&text=Data%20Definition%20Language%20(DDL)%20
statements,already%20exists%20in%20the%20database.
https://www.w3schools.com/sql/sql_delete.asp
119 | P a g e
Chapter # 9 Custom Tags
Chapter No. 09
CUSTOM TAGS
Objectives
After completion of this chapter students will be able to:
9.1- Custom Tags Overview
9.2- Custom Tag Handlers
9.3- Customizing Tag behavior with attributes
9.1 Custom Tags
A custom tag is a user-defined JSP language element. When a JSP page
containing a custom tag is translated into a servlet, the tag is converted to
operations on an object called a tag handler. The Web container then
invokes those operations when the JSP page's servlet is executed.
JSP tag extensions lets you create new tags that you can insert directly into a
JavaServer Page. The JSP 2.0 specification introduced the Simple Tag
Handlers for writing these custom tags.
To write a custom tag, you can simply extend SimpleTagSupport class and
override the doTag() method, where you can place your code to generate
content for the tag.
Advantages of Custom Tags in JSP
Portable – Once declared in the Tag Library, these tags can be used
anywhere.
Simple – They are simple and convenient to use.
Expressive – It provides a wide range of functionalities, scripting elements to
the page authors.
Usable from different scripting languages – This functionality can extend to
other scripting languages.
No need for scriptlet tag – Once we create a custom tag, we don’t need
scriptlet tag. Though it is a bad approach in JSP.
Reusable – We can use the similar business logic over and over again.
Separation of business logic from JSP – For easy maintenance, Custom tags
separate business logic and JSP.
120 | P a g e
Chapter # 9 Custom Tags
packagecom.tutorials;
importjavax.servlet.jsp.tagext.*;
importjavax.servlet.jsp.*;
import java.io.*;
The above code has simple coding where the doTag() method takes the
current JspContext object using the getJspContext() method and uses it to
send "Hello Custom Tag!" to the current JspWriter object.
The object that implements a custom tag is called a tag handler. JSP
technology defines two types of tag handlers: simple and classic. Simple tag
handlers can be used only for tags that do not use scripting elements in
attribute values or the tag body. Classic tag handlers must be used if scripting
elements are required.
The classes and interfaces used to implement simple tag handlers are
contained in the javax.servlet.jsp.tagext package. Simple tag handlers
121 | P a g e
Chapter # 9 Custom Tags
The heart of a simple tag handler is a single method, doTag, which is invoked
when the end element of the tag is encountered. Note that the default
implementation of the doTag method of SimpleTagSupport does nothing.
A tag handler has access to an API that allows it to communicate with the JSP
page. The entry point to the API is the JSP context object
(javax.servlet.jsp.JspContext). The JspContext object provides access to
implicit objects. PageContext extends JspContext with servlet-specific
behavior. Through these objects, a tag handler can retrieve all the other
implicit objects (request, session, and application) that are accessible from a
JSP page. If the tag is nested, a tag handler also has access to the handler
(called the parent) that is associated with the enclosing tag.
The classes and interfaces used to implement classic tag handlers are
contained in the javax.servlet.jsp.tagext package. Classic tag handlers
implement either the Tag, the IterationTag, or the BodyTag interface.
Interfaces can be used to take an existing Java object and make it a tag
handler. For newly created classic tag handlers, you can use
the TagSupport and BodyTagSupport classes as base classes. These classes
and interfaces are contained in the javax.servlet.jsp.tagext package.
Custom tag attributes are used to provide the requested information to the
tag handler class. A custom tag can have either no attributes or many
attributes. These attributes are used after the tag name in the start tag and
they contains a name and its respective value, these tag attributes are
customizing the custom tag behavior as the parameters customized the
behavior of a method, more than one attributes can be separated by giving a
white space.
122 | P a g e
Chapter # 9 Custom Tags
Simple attributes
Fragment attributes
Dynamic attributes
Simple attributes are evaluated by the container before being passed to the
tag handler. Simple attributes are listed in the start tag
A JSP fragment is a portion of JSP code passed to a tag handler that can be
invoked as many times as needed. You can think of a fragment as a template
that is used by a tag handler to produce customized content. Thus, unlike a
simple attribute which is evaluated by the container, a fragment attribute is
evaluated by a tag handler during tag invocation.
123 | P a g e
Chapter # 9 Custom Tags
EXERCISE
124 | P a g e
Chapter # 9 Custom Tags
125 | P a g e
Chapter # 9 Custom Tags
B. compilation
C. syntax
D. Both A and B
8. JSP includes a mechanism for defining …………………………. or custom tags.
Download more sets at McqMate.com
A. static attributes
B. local attributes
C. global attributes
D. dynamic attributes
9. Which is not a directive?
A. include
B. page
C. export
D. taglib
10. Which http method send by browser that asks the server to get the page
only? A. get
B. option
C. put
D. post
MCQ’s Answers
1 2 3 4 5 6 7 8 9 10
A A B C D B C D C A
126 | P a g e
Chapter # 9 Custom T
References
127 | P a g e
Chapter # 10 Java Server Faces
Chapter No. 10
JAVA SERVER FACES
At the end of this chapter students will be able to:
10.1- Introduction
10.2- Using JSF with JSP
10.3- JSF Life Cycle
10.4- Events Handling
10.5- JSF Tag Library
10.1 INTRODUCTION
It is a server side component based user interface framework. It is used to
develop web applications. It provides a well-defined programming model and
consists of rich API and tag libraries. Java Server Faces is a standardized
display technology, which was formalized in a specification through the Java
Community Process.
The JSF API provides components (inputText, commandButtonetc) and helps
to manage their states. It also provides server-side validation, data
conversion, defining page navigation, provides extensibility, supports for
internationalization, accessibility etc.
The JSF Tag libraries are used to add components on the web pages and
connect components with objects on the server. It also contains tag handlers
that implements the component tag.
10.1.1 Benefits of Java Server Faces
It provides clean and clear separation between behavior and
presentation of web application. You can write business logic and user
interface separately.
Java Server Faces API’s are layered directly on top of the Servlet API.
Which enables using different presentation technologies, creating
your own custom components directly from the component classes.
Inclusion of Facelets technology in Java Server Faces 2.0, provides
massive advantages to it. Facelets is now the preferred presentation
technology for building Java Server Faces based web applications.
128 | P a g e
Chapter # 10 Java Server Faces
129 | P a g e
Chapter # 10 Java Server Faces
130 | P a g e
Chapter # 10 Java Server Faces
1. Restore View Phase: This phase begins each time a consumer requests a
JSF page by simply clicking on a link, button, and so on. In this page view
generation, the binding of components to the event handlers and validators
is performed as well as the view is preserved within the FacesContext object.
2. Apply request value: The objective of this phase is made for each
component to retrieve the current state
3. Process Validations Phase: In this phase, local values stored to get the
component in the tree will be in comparison to the validation rules
authorized to get the components.
4. Update Model Values Phase: Following verifying that data is valid in the
last phase local values of elements could be started related to server-based
object properties, for example, backing beans.
5. Invoke Application Phase: Ahead of this phase the component values had
been transformed, validated, as well as, put on the bean objects so that you
can utilize these to perform the application’s business logic.
6. Render Response Phase: This phase fetches a new view if needed using
values from server-side beans then we output the view using the values that
are in the tree and then for beans that are not on the request in other words
on the session scope or application scope we will then save those the current
state.
131 | P a g e
Chapter # 10 Java Server Faces
When a user clicks a JSF button or link or changes any value in the text field,
JSF UI component fires an event, which will be handled by the application
code. To handle such an event, an event handler is to be registered in the
application code or managed bean.
When a UI component checks that a user event has occured, it creates an
instance of the corresponding event class and adds it to an event list. Then,
Component fires the event, i.e., checks the list of listeners for that event and
calls the event notification method on each listener or handler.
JSF also provide system level event handlers, which can be used to perform
some tasks when the application starts or is stopping.
Following are some important Event Handler in JSF 2.0 −
Value change events get fired when the user make changes in
input components.
2 actionListener
Action events get fired when the user clicks a button or link
component.
3 Application Events
ValueChangeListener:
When user interacts with input components, such as h:inputText or
h:selectOneMenu, the JSF fires a valueChangeEvent which can be handled in
two ways.
Technique Description
Method Binding Pass the name of the managed bean method in
valueChangeListenerattribute of UI Component.
ValueChangeListener Implement ValueChangeListener interface and pass
the implementation class name to
132 | P a g e
Chapter # 10 Java Server Faces
ActionListener:
When user interacts with components, such as h:commandButton or h:link,
the JSF fires an action events which can be handled in two ways.
Technique Description
Method Binding Pass the name of the managed bean method in
actionListener attribute of UI Component.
ActionListener Implement ActionListener interface and pass the
implementation class name to actionListener
attribute of UI Component.
10.5 JSF TAG LIBRARY
To develop a JSF application in a convenient way Sun Microsystems, Inc
provided some tag libraries that fulfils the basic requirement or functionality
to the discrete JSF applications. To develop JSF applications not only its own
tag libraries core and html but, also JSTL core1.2 and JSTL functions1.1 tag
libraries are supported. Tag libraries of JSF core and html expresses the
JavaServer Faces interface on the inside view template, these can be used
with JSP or Facelets or both.
Each JSF Tag Libraries have their own namespace, or prefix these are as
follows :
Following table describes the libraries and their corresponding uri and prefix.
133 | P a g e
Chapter # 10 Java Server Faces
JSF ui http://java.sun.com/jsf/facelets ui 12
NOTE : You would be required the jsf-impl.jar, jstl.jar, standard.jar files to use
these above libraries. Some of the tag examples of each library are as
follows:
134 | P a g e
Chapter # 10 Java Server Faces
135 | P a g e
Chapter # 10 Java Server Fa
EXERCISE
PART I: SHORT QUESTIONS
21. What is JFS?
22. Write any two benefits of JFS?
23. How JSF is used with JSP?
24. What is Uri?
25. Write name of phases in JFS life cycle?
26. What is JFS tag library?
27. Give names of JFS libraries?
28. Describe attribute tag in JFS?
136 | P a g e
Chapter # 10 Java Server Fa
137 | P a g e
Chapter # 10 Java Server Fa
a. ui
b. c
c. f
d. h
8. _________tag is used to add attribute to the UIComponent.
a. <th> tag
b. <f:actionListener>
c. <f:attribute>
d. None
9. ____________tag is used for rendering the html input element.
a. <f:actionListener>
b. <h:commandButton>
c. <nav> tag
d. none
10. prefix used for JSF html library is__________
a. ui
b. c
c. f
d. h
MCQ’s Answers:
1 2 3 4 5 6 7 8 9 10
B B C B B D C C B D
138 | P a g e
Chapter # 10 Java Server Fa
References
eventhandling.php. (n.d.). Retrieved from http://javatechnologycenter.com:
http://javatechnologycenter.com/question/jsf_tutorial/eventhandling.php
139 | P a g e