(502) Java Programming and Dynamic Web page Design Notes
(502) Java Programming and Dynamic Web page Design Notes
UNIT-I
Java Programming: Data types, control structured, arrays, strings, and vector,
classes (inheritance, package, exception handling) multithreaded programming.
UNIT-II
Java appletsAWT controls (Button, Labels, Combo box, list and other Listeners,
menu bar) layout manager, string handling (only main functions)
UNIT-III
Networking (datagram socket and TCP/IP based server socket) event handling,
JDBC: Introduction, Drivers, Establishing Connection, Connection Pooling.
UNIT-IV
HTML: use of commenting, headers, text styling, images, formatting text with ,
special characters, horizontal rules, line breaks, table, forms, image maps, tags,
tags, file formats including image formats.
UNIT-V
UNIT-VI
Java Server Pages: Introducing Java Server Pages, JSP Overview, Setting Up
the JSP Environment, Generating Dynamic Content, Using Custom Tag Libraries
and the JSP Standard Tag Library, Processing Input and Output
UNIT-I: Java Programming
1. Data Types
Java supports various data types that define the type of data a variable can hold. These can be
classified into:
Example:
Control structures are used to control the flow of execution of a program based on conditions.
Example:
// switch Example
int day = 2;
switch(day) {
case 1: System.out.println("Monday"); break;
case 2: System.out.println("Tuesday"); break;
default: System.out.println("Invalid day");
}
Explanation:
3. Arrays
Example:
Explanation: This code demonstrates a simple 1D array and prints each element.
4. Strings
Explanation: We concatenate two strings and perform common string operations like
length() and substring().
5. Vectors
A Vector in Java is a dynamic array that grows as elements are added. It is part of the
java.util package and is thread-safe.
Example:
import java.util.*;
Explanation: The vector dynamically grows as we add elements to it, and we access the
elements using the get() method.
a. Inheritance: The mechanism in Java by which one class acquires the properties and
behaviors (methods) of another class.
class Animal {
void eat() {
System.out.println("Animal is eating.");
}
}
b. Packages: A package is a namespace that organizes a set of related classes and interfaces.
// In file Animal.java
package animals;
// In file TestAnimal.java
import animals.Animal;
Explanation: Animal class is defined in a package animals and imported in the TestAnimal
class to use its method.
7. Multithreaded Programming
Multithreading allows multiple threads to run concurrently, improving performance for tasks that
can be executed simultaneously.
Explanation: The run() method is executed when the thread is started using the start()
method.
UNIT-II: Java Applets, AWT Controls, and String Handling
1. Java Applets
Java Applets are small programs written in Java that are designed to be embedded in web
pages and run inside a web browser. However, applets are now largely deprecated, and modern
web applications use other technologies like HTML5, JavaScript, and CSS for dynamic content.
● Applet Basics:
1. An applet is a class that extends java.applet.Applet or
javax.swing.JApplet.
2. It can run in a web browser or applet viewer.
3. Applets have methods like init(), start(), stop(), and destroy() to
handle lifecycle events.
● Applet Lifecycle:
1. init(): Called once when the applet is loaded.
2. start(): Called after init() and when the applet is made visible.
3. stop(): Called when the applet is no longer visible.
4. destroy(): Called when the applet is unloaded.
Example:
import java.applet.Applet;
import java.awt.Graphics;
Note: Modern browsers no longer support Java applets due to security issues, so Java applets
are not used in modern web development.
AWT (Abstract Window Toolkit) is a set of APIs used for building graphical user interfaces
(GUIs) in Java. It includes a variety of controls such as buttons, labels, combo boxes, and more.
AWT Components:
Example:
import java.awt.*;
import java.awt.event.*;
Explanation:
● Button: When clicked, it changes the text of the label to "Button Clicked!".
● ActionListener: Used to listen for the button click event and trigger actions in response.
● FlowLayout: A layout manager that arranges components in a left-to-right flow.
AWT provides several layout managers to control the positioning of components within a
container:
Example (BorderLayout):
import java.awt.*;
// Frame settings
setTitle("BorderLayout Example");
setSize(300, 200);
setVisible(true);
}
Explanation:
● This example uses BorderLayout to place buttons in all five regions of the window.
4. String Handling in Java
Java provides a powerful set of methods for handling strings. Some important operations
include:
Example:
// Concatenation
String result = str1 + " " + str2;
System.out.println("Concatenated String: " + result);
// Length
System.out.println("Length of str1: " + str1.length());
// Substring
System.out.println("Substring of str2 (0 to 3): " +
str2.substring(0, 3));
// Comparison
System.out.println("Comparison of str1 and str2: " +
str1.equals(str2));
}
}
Explanation:
Java provides an extensive API for networking, enabling developers to create applications that
communicate over a network. Java supports both TCP (Transmission Control Protocol) and
UDP (User Datagram Protocol) for communication.
● DatagramSocket (UDP):
○ A DatagramSocket is used for connectionless communication (UDP).
○ It sends and receives packets of data, called datagrams.
○ UDP does not guarantee delivery or order of messages, making it faster but less
reliable than TCP.
● ServerSocket (TCP):
○ A ServerSocket is used for server-side communication over TCP.
○ It listens for incoming connections and establishes a reliable stream of
communication once a connection is made.
○ TCP provides guaranteed delivery, error correction, and ensures data order.
import java.net.*;
while (true) {
DatagramPacket receivePacket = new
DatagramPacket(receiveData, receiveData.length);
socket.receive(receivePacket); // Receive data
String message = new String(receivePacket.getData(), 0,
receivePacket.getLength());
System.out.println("Received: " + message);
}
}
}
Explanation:
import java.net.*;
import java.io.*;
socket.close();
serverSocket.close();
}
}
Explanation:
Event handling is an essential part of GUI programming in Java. It allows you to manage user
actions such as clicks, key presses, and mouse movements.
● Event Sources: Components that generate events, such as buttons, text fields, and
windows.
● Event Listeners: Interfaces that handle the events. For example, ActionListener
handles button clicks, MouseListener handles mouse events, and KeyListener
handles keyboard events.
import java.awt.*;
import java.awt.event.*;
// Frame settings
add(b);
setSize(300, 200);
setVisible(true);
}
Explanation:
JDBC is an API that allows Java applications to interact with databases. It provides a set of
interfaces and classes for querying and updating databases.
● JDBC Components:
1. Driver: A set of classes that handle communication with the database.
2. Connection: Used to establish a connection to the database.
3. Statement: Executes SQL queries.
4. ResultSet: Holds the results of SQL queries.
5. Exception Handling: Manages errors that occur during database interaction.
● JDBC Workflow:
1. Load the database driver.
2. Establish a connection to the database.
3. Create a Statement object.
4. Execute SQL queries (SELECT, INSERT, UPDATE).
5. Process the results (if any).
6. Close the connection.
Example (JDBC with MySQL):
import java.sql.*;
public class JDBCExample {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// Step 1: Load the driver
Class.forName("com.mysql.cj.jdbc.Driver");
Explanation:
HTML (HyperText Markup Language) is the standard language for creating web pages and web
applications. It structures content on the web and uses various tags to define elements such as
text, images, links, tables, and forms.
Comments in HTML are used to add notes or explanations to the code. These comments are
ignored by the browser and do not appear in the rendered page. They are mainly used for
documentation or to temporarily disable parts of code during development.
Example:
<!DOCTYPE html>
<html>
<head>
<title>HTML Comments Example</title>
</head>
<body>
<!-- This is the main heading of the page -->
<h1>Welcome to My Website</h1>
Explanation:
● The comments here are used to explain the purpose of the h1 and p tags. These
comments do not appear on the webpage but help developers understand the code's
functionality.
2. Headers in HTML
Headers in HTML are used to define the headings for content. They range from <h1> (largest)
to <h6> (smallest). These tags help structure the document and also provide SEO benefits, as
search engines pay attention to header tags.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Header Example</title>
</head>
<body>
<h1>Main Heading</h1>
<h2>Sub Heading 1</h2>
<h3>Sub Heading 2</h3>
<p>This is a paragraph under heading 3.</p>
</body>
</html>
Explanation:
● The <h1> tag defines the primary heading of the page, and subsequent headings <h2>
and <h3> are used for sub-headings. These headings help organize the content.
HTML provides a variety of tags to style and format text, such as making it bold, italic,
underlined, or struck-through.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Text Styling Example</title>
</head>
<body>
<p>This is <b>bold</b> text, <i>italic</i> text, <u>underlined</u>
text, and <s>strikethrough</s> text.</p>
<p><strong>Important:</strong> Please read the instructions
carefully.</p>
<p><em>Note:</em> Make sure to follow the guidelines.</p>
</body>
</html>
Explanation:
● The <b> and <i> tags are used for bold and italic text respectively.
● The <strong> tag is used to highlight important text, and the <em> tag is used for
emphasis, typically rendering text in italic.
4. Images in HTML
Images are an essential part of web design, and the <img> tag is used to embed images in an
HTML document. The src attribute specifies the image's URL, and the alt attribute provides
alternative text if the image cannot be displayed.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Image Example</title>
</head>
<body>
<h1>HTML Image Example</h1>
<img src="logo.png" alt="Website Logo" width="200" height="100">
</body>
</html>
Explanation:
● The src attribute points to the location of the image file (logo.png).
● The alt attribute provides text for screen readers or when the image is missing.
● The width and height attributes define the image size.
The <font> tag was historically used to style text with fonts, sizes, and colors. However, it has
been deprecated in HTML5, and CSS is now the preferred method for styling text. Nevertheless,
understanding the <font> tag is essential for legacy code.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Font Styling Example</title>
</head>
<body>
<font color="blue" size="6" face="Verdana">This text is styled
with the FONT tag.</font>
</body>
</html>
Explanation:
However, it is recommended to use CSS for styling fonts instead of the <font> tag.
6. Special Characters in HTML
Some characters have special meanings in HTML and need to be represented with character
entities. For example, the less-than sign < is used for tags, so it must be represented as <
when displayed as text.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Special Characters Example</title>
</head>
<body>
<p><div>This is a div tag.</div></p>
<p>He said, "Hello!"</p>
</body>
</html>
Explanation:
● The < and > symbols are replaced with < and > to display them on the web
page.
● The quotation marks are replaced with " to avoid confusion with HTML tag
delimiters.
7. Horizontal Rules in HTML
The <hr> tag is used to create a horizontal line or a thematic break in the content. It is typically
used to separate sections or content within a page.
<hr>
Example:
<!DOCTYPE html>
<html>
<head>
<title>Horizontal Rule Example</title>
</head>
<body>
<h1>Welcome to My Website</h1>
<p>This is an introductory section.</p>
<hr>
<h2>New Section</h2>
<p>Details about the new section go here.</p>
</body>
</html>
Explanation:
● The <hr> tag is used to create a horizontal line that visually separates the two sections
on the page.
The <br> tag is used to insert a line break, creating a new line without creating a new
paragraph. It is a self-closing tag, meaning it does not require a closing tag.
<!DOCTYPE html>
<html>
<head>
<title>Line Break Example</title>
</head>
<body>
<p>This is a paragraph. <br> This is the second line after a line
break.</p>
</body>
</html>
Explanation:
● The <br> tag forces a line break between the two pieces of text within the paragraph
(<p>). It's useful for formatting content like addresses, poems, or lists when you don’t
want to use paragraphs.
9. Tables in HTML
Tables are used to organize data into rows and columns. The <table> tag is used to create the
table, and other tags like <tr>, <td>, and <th> define the rows, data cells, and header cells,
respectively.
<table>
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
<tr>
<td>Data 1</td>
<td>Data 2</td>
</tr>
</table>
Example:
<!DOCTYPE html>
<html>
<head>
<title>HTML Table Example</title>
</head>
<body>
<table border="1">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
<td>30</td>
</tr>
<tr>
<td>Jane</td>
<td>Smith</td>
<td>25</td>
</tr>
</table>
</body>
</html>
Explanation:
Forms are used to collect user input. The <form> element encapsulates all the input elements,
and the action and method attributes specify where and how to send the form data. The input
elements, such as text fields, radio buttons, checkboxes, and submit buttons, are included
inside the form.
<label for="email">Email:</label>
<input type="email" id="email" name="email">
<button type="submit">Submit</button>
</form>
Example:
<!DOCTYPE html>
<html>
<head>
<title>HTML Form Example</title>
</head>
<body>
<h1>Contact Form</h1>
<form action="/submit" method="POST">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<br><br>
<label for="message">Message:</label>
<textarea id="message" name="message" rows="4" cols="50"
required></textarea>
<br><br>
● The <form> tag defines the form and specifies the action (where to send the form
data) and method (the HTTP method for submitting the form).
● The <input> tags define various types of inputs, such as text and email fields.
● The <textarea> tag creates a multi-line text input for messages.
● The <button> tag submits the form.
An image map is an image with clickable areas that link to different destinations. It is achieved
using the <map> and <area> tags. The <map> tag defines the image map, and the <area> tag
defines the clickable areas.
<map name="mapname">
<area shape="rect" coords="34,44,270,350" href="link1.html"
alt="Area 1">
<area shape="circle" coords="50,50,50" href="link2.html" alt="Area
2">
</map>
Example:
<!DOCTYPE html>
<html>
<head>
<title>Image Map Example</title>
</head>
<body>
<h1>Clickable Image Map</h1>
<img src="worldmap.jpg" usemap="#worldmap" alt="World Map">
<map name="worldmap">
<area shape="rect" coords="34,44,270,350" href="usa.html"
alt="USA">
<area shape="circle" coords="400,250,50" href="europe.html"
alt="Europe">
</map>
</body>
</html>
Explanation:
● The <img> tag includes the usemap attribute to associate the image with a map
(#worldmap).
● The <area> tags define clickable regions in the image. The coords attribute defines
the coordinates for the clickable areas.
○ For the rectangle (shape="rect"), it takes 4 values: the top-left and
bottom-right corner coordinates.
○ For the circle (shape="circle"), it takes the center and radius coordinates.
The <meta> tag provides metadata about the HTML document, such as character encoding,
author, description, keywords, and more. It is placed inside the <head> section.
<!DOCTYPE html>
<html>
<head>
<title>Meta Tags Example</title>
<meta charset="UTF-8">
<meta name="description" content="A tutorial on HTML meta tags">
<meta name="author" content="John Doe">
<meta name="keywords" content="HTML, Web Development, Meta Tags">
</head>
<body>
<h1>Welcome to the Meta Tags Tutorial</h1>
</body>
</html>
Explanation:
● The <meta charset="UTF-8"> specifies the character encoding for the document.
● The name="description" and name="keywords" provide metadata for search
engines.
● The name="author" tag provides the author of the document.
The <frameset> tag was used in older versions of HTML to create a page layout with multiple
frames. However, it is now considered outdated and replaced by CSS for layout purposes. It
allows dividing the browser window into multiple sections, where each section can display a
different HTML document.
<frameset cols="50%,50%">
<frame src="page1.html">
<frame src="page2.html">
</frameset>
Example:
<!DOCTYPE html>
<html>
<head>
<title>Frameset Example</title>
</head>
<body>
<frameset cols="50%,50%">
<frame src="page1.html">
<frame src="page2.html">
</frameset>
</body>
</html>
Explanation:
● The <frameset> tag divides the browser window into two columns, each containing a
different HTML document. The cols="50%,50%" attribute specifies the width of each
frame.
Unit V: Java Servlets
A Servlet is a Java program that runs on a server, handling client requests and generating
dynamic responses. Servlets are commonly used in web applications to extend the functionality
of web servers. They are a fundamental part of the Java EE (Enterprise Edition) and are part of
the server-side component in a client-server architecture.
Java Servlets are server-side Java programs that handle requests from clients, typically web
browsers, and generate responses. They are used to create dynamic web content, like handling
form submissions, querying databases, and providing content based on user input.
● Platform-independent: Written in Java, so they can run on any platform that supports
Java.
● Dynamic content: Servlets can generate dynamic HTML content based on client input.
● Extendable: Servlets are part of the Java Servlet API, which is an extendable framework
for web applications.
Servlet Container (Web Container): The servlet container (like Apache Tomcat) manages the
servlets. It provides an environment for servlets to run, handling their lifecycle, requests, and
responses.
The most common type of servlet is an HTTP Servlet, which processes HTTP requests from
clients (web browsers). An HTTP servlet extends the HttpServlet class and overrides
methods like doGet() and doPost() to handle GET and POST requests.
Basic Structure of an HTTP Servlet:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
Explanation:
A servlet follows a well-defined lifecycle, controlled by the servlet container. The key stages in
the lifecycle are:
1. Loading and Instantiation: When a servlet is requested for the first time, the servlet
container loads the servlet class and creates an instance of it.
2. Initialization: The init() method is called once during the servlet's lifecycle, allowing
it to perform any setup tasks (like reading configuration data).
3. Request Handling: For each request, the servlet container invokes methods like
doGet(), doPost(), or others depending on the HTTP method.
4. Destruction: When the servlet is no longer needed (for example, when the container is
shut down), the destroy() method is called to clean up resources.
Example:
Servlets can retrieve data from various sources such as query parameters, form data, headers,
and cookies. The HttpServletRequest object is used to retrieve this information.
Servlets generate dynamic content, including HTML pages. Using the HttpServletResponse
object, servlets can send data (such as HTML) back to the client.
Explanation:
● The setContentType() method sets the type of content that the servlet will return
(e.g., HTML, JSON, XML).
● The getWriter() method is used to send the response content to the client.
Session tracking allows servlets to maintain user-specific data across multiple requests. There
are several ways to track sessions:
Explanation:
Java Servlets can connect to databases using JDBC (Java Database Connectivity) to interact
with databases like MySQL, Oracle, etc.
import java.sql.*;
while (rs.next()) {
response.getWriter().println("User: " +
rs.getString("username"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Explanation:
● The servlet loads the MySQL JDBC driver, connects to the database, and queries for
user data.
● It then sends the results back to the client as an HTML response.
Unit VI: Java Server Pages (JSP)
Java Server Pages (JSP) is a technology used for developing dynamic, web-based applications.
JSP allows developers to embed Java code into HTML pages, which is executed on the server
to generate dynamic content. It is a powerful mechanism for building web applications in the
Java ecosystem, combining the best of HTML and Java in a single file.
JSP provides a convenient way to create dynamic content. It is a part of the Java EE (Enterprise
Edition) and helps in separating the business logic from the presentation logic.
JSP vs Servlets:
● Servlets: Server-side Java programs that handle requests and responses. They require
Java code to be written for each client interaction.
● JSP: Allows embedding Java directly into HTML, making it easier for developers to mix
static content with dynamic content. It is compiled into a servlet by the JSP container
before execution.
2. JSP Overview
JSPs are essentially HTML pages with embedded Java code that gets executed on the server.
The Java code is written inside special JSP tags, which the container converts into a Java
servlet behind the scenes.
● Directives: These provide information about the page (like page attributes or imports).
● Scriptlets: Java code embedded directly into the page.
● Expressions: Used to output dynamic data to the client’s browser.
● Declarations: Used to declare variables or methods that can be used throughout the
JSP.
Example JSP Page:
Explanation:
● <%@ page %>: A directive that defines the page attributes, such as content type.
● <% %>: A scriptlet where Java code is written, which will be executed on the server and
output as part of the HTML content.
To develop JSP applications, you need a servlet container (like Apache Tomcat) that supports
JSP. The steps to set up a basic JSP environment include:
The main feature of JSP is the ability to generate dynamic content. When a client requests a
JSP page, the server processes the Java code inside the JSP and sends the result as an HTML
page to the client.
Example:
Explanation:
● <%= %>: This is an expression tag. It evaluates the Java code and outputs the result
directly into the HTML response. In this case, it prints the current date and time.
5. Using Custom Tag Libraries and the JSP Standard Tag Library (JSTL)
JSP allows for the creation of custom tags, which can encapsulate functionality and simplify the
page design. One of the most widely used tag libraries is the JSP Standard Tag Library
(JSTL). JSTL provides a set of standard tags for common tasks such as iteration, conditionals,
and database access.
<html>
<body>
<h1>Looping with JSTL</h1>
<c:forEach var="i" begin="1" end="5">
<p>Number: ${i}</p>
</c:forEach>
</body>
</html>
Explanation:
● <%@ taglib %>: Declares the JSTL tag library and associates it with a prefix (e.g., c).
● <c:forEach>: This is a JSTL tag for looping. It iterates over a set of values (in this
case, from 1 to 5) and outputs each value inside the loop.
JSP can be used to process input from HTML forms and generate output accordingly. It can
retrieve data sent via GET or POST methods, perform operations on the data, and then generate
a response.
● JSP Tags: Use scriptlets (<% %>), expressions (<%= %>), and declarations to embed
Java code within HTML.
● JSP Life Cycle: Similar to servlets, JSP pages are first compiled into servlets by the
container.
● Dynamic Content: JSP generates dynamic content based on server-side logic, like
displaying the current time, greeting users, etc.
● Custom Tags & JSTL: Allows the creation of reusable tags and provides common tasks
like loops and conditionals via standard libraries.
● Form Handling: You can handle form submissions and user inputs directly in the JSP
using the request object.