Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
50 views

(502) Java Programming and Dynamic Web page Design Notes

Uploaded by

junedalam8357
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views

(502) Java Programming and Dynamic Web page Design Notes

Uploaded by

junedalam8357
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

BCA- 502 Java Programming and Dynamic Webpage Design

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

Java Servlets: Introduction, HTTP Servlet Basics, The Servlet Lifecycle,


Retrieving Information, Sending HTML Information, Session Tracking, Database
Connectivity

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:

● Primitive Data Types:


○ byte: 8-bit signed integer.
○ short: 16-bit signed integer.
○ int: 32-bit signed integer.
○ long: 64-bit signed integer.
○ float: Single-precision 32-bit floating point.
○ double: Double-precision 64-bit floating point.
○ char: 16-bit Unicode character.
○ boolean: Represents true or false.
● Reference Data Types: These are objects and arrays in Java.
○ Example: String, Arrays, Objects.

Example:

public class DataTypesExample {

public static void main(String[] args) {


int a = 10; // Integer
float b = 20.5f; // Float
char c = 'A'; // Character
boolean isJavaFun = true; // Boolean

System.out.println("Integer value: " + a);


System.out.println("Float value: " + b);
System.out.println("Character value: " + c);
System.out.println("Boolean value: " + isJavaFun);
}}

Explanation: Here, we define and print variables of different data types.


2. Control Structures

Control structures are used to control the flow of execution of a program based on conditions.

● if-else: Executes code based on a condition.


● switch: A multi-way branch statement.
● loops: Used for repeated execution of a block of statements.
○ for loop: Used for a known number of iterations.
○ while loop: Used when the number of iterations is not known.
○ do-while loop: Ensures the code block is executed at least once.

Example:

public class ControlStructuresExample {


public static void main(String[] args) {
// if-else Example
int number = 5;
if (number > 0) {
System.out.println("Positive number");
} else {
System.out.println("Non-positive number");
}

// 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");
}

// for loop Example


for (int i = 0; i < 5; i++) {
System.out.println("i = " + i);
}}}

Explanation:

● The if-else checks whether the number is positive or not.


● The switch selects the day based on the integer value.
● The for loop prints numbers from 0 to 4.

3. Arrays

An array is a collection of similar types of data stored in a contiguous memory location.

● One-dimensional array: A simple list of elements.


● Multi-dimensional array: Arrays of arrays, like matrices.

Example:

public class ArraysExample {


public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
for (int i = 0; i < arr.length; i++) {
System.out.println("Element at index " + i + ": " +
arr[i]);
}
}
}

Explanation: This code demonstrates a simple 1D array and prints each element.

4. Strings

Strings in Java are objects that represent a sequence of characters.

● String is immutable (cannot be changed).


● Common operations: concatenation, length, substring, and comparison.
Example:

public class StringsExample {


public static void main(String[] args) {
String str1 = "Hello";
String str2 = " World!";
String str3 = str1 + str2; // Concatenation

System.out.println("Concatenated string: " + str3);


System.out.println("Length of string: " + str3.length());
System.out.println("Substring: " + str3.substring(0, 5));
}
}

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.

● Common methods: add(), remove(), get(), size().

Example:

import java.util.*;

public class VectorExample {


public static void main(String[] args) {
Vector<String> vector = new Vector<>();
vector.add("Apple");
vector.add("Banana");
vector.add("Cherry");
System.out.println("Vector elements: " + vector);
System.out.println("Element at index 1: " + vector.get(1));
}
}

Explanation: The vector dynamically grows as we add elements to it, and we access the
elements using the get() method.

6. Classes (Inheritance, Packages, Exception Handling)

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.");
}
}

class Dog extends Animal {


void bark() {
System.out.println("Dog is barking.");
}
}

public class InheritanceExample {


public static void main(String[] args) {
Dog dog = new Dog();
dog.eat(); // Inherited method
dog.bark(); // Dog's own method
}
}
Explanation: The Dog class inherits from the Animal class and has access to its methods.

b. Packages: A package is a namespace that organizes a set of related classes and interfaces.

// In file Animal.java
package animals;

public class Animal {


public void sound() {
System.out.println("Animal makes a sound");
}
}

// In file TestAnimal.java
import animals.Animal;

public class TestAnimal {


public static void main(String[] args) {
Animal animal = new Animal();
animal.sound();
}
}

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.

● Thread: Represents a single thread of execution.


● Runnable Interface: Provides a standard method for creating threads.
Example:

class MyThread extends Thread {


public void run() {
System.out.println("Thread is running.");
}
}

public class MultithreadingExample {


public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start(); // Starts the thread
}
}

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;

public class HelloWorldApplet extends Applet {


// Called once when the applet is loaded
public void init() {
System.out.println("Applet Initialized");
}

// Called to display content


public void paint(Graphics g) {
g.drawString("Hello, World!", 20, 30);
}}
Explanation:

● The init() method is executed when the applet is loaded.


● The paint() method is used to render the string "Hello, World!" on the applet window.

Note: Modern browsers no longer support Java applets due to security issues, so Java applets
are not used in modern web development.

2. AWT Controls (Button, Labels, ComboBox, List, and Other Listeners)

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.

● Button: A GUI component that can trigger an action when clicked.


● Label: A GUI component that displays text or an image.
● ComboBox: A dropdown menu for selecting items.
● List: A list of items for the user to select from.

AWT Components:

1. Button: Triggered by user interaction, often using event listeners.


2. Label: Displays static text or an image.
3. ComboBox: Allows the user to choose one item from a list.
4. List: Displays a list of items, often used for selection.

Example:

import java.awt.*;
import java.awt.event.*;

public class AWTExample extends Frame {


AWTExample() {
// Create button and label
Button b = new Button("Click Me");
Label l = new Label("Welcome to AWT!");

// Set Layout Manager


setLayout(new FlowLayout());
// Add components to the frame
add(b);
add(l);
// Button click event handling
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
l.setText("Button Clicked!");
}
});
// Frame settings
setTitle("AWT Example");
setSize(300, 200);
setVisible(true);
}

public static void main(String[] args) {


new AWTExample();
}
}

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.

3. Layout Managers in AWT

AWT provides several layout managers to control the positioning of components within a
container:

● FlowLayout: Places components from left to right in the container.


● BorderLayout: Divides the container into five regions: North, South, East, West, and
Center.
● GridLayout: Places components in a grid of rows and columns.

Example (BorderLayout):

import java.awt.*;

public class LayoutExample extends Frame {


LayoutExample() {
// Set BorderLayout
setLayout(new BorderLayout());

// Add components to the frame


add(new Button("North"), BorderLayout.NORTH);
add(new Button("South"), BorderLayout.SOUTH);
add(new Button("East"), BorderLayout.EAST);
add(new Button("West"), BorderLayout.WEST);
add(new Button("Center"), BorderLayout.CENTER);

// Frame settings
setTitle("BorderLayout Example");
setSize(300, 200);
setVisible(true);
}

public static void main(String[] args) {


new LayoutExample();
}
}

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:

● Concatenation: Combining two strings.


● Length: Getting the length of a string.
● Substring: Extracting part of a string.
● Comparison: Comparing two strings.

Example:

public class StringHandlingExample {


public static void main(String[] args) {
String str1 = "Hello";
String str2 = "World";

// 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:

● The + operator is used to concatenate str1 and str2.


● The length() method returns the number of characters in the string.
● The substring() method extracts a part of the string.
● The equals() method compares two strings for equality.
UNIT-III: Networking, Event Handling, and JDBC

1. Networking in Java (Datagram Socket and TCP/IP based Server Socket)

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.

Example (UDP - DatagramSocket):

import java.net.*;

public class UDPServer {


public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket(9876);
byte[] receiveData = new byte[1024];

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:

● A DatagramSocket listens on port 9876.


● It receives packets from clients and prints the received message to the console.

Example (TCP - ServerSocket):

import java.net.*;
import java.io.*;

public class TCPServer {


public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(6666);
System.out.println("Server is listening on port 6666...");

Socket socket = serverSocket.accept(); // Accept connection


BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
String clientMessage = in.readLine();
System.out.println("Client says: " + clientMessage);

socket.close();
serverSocket.close();
}
}

Explanation:

● ServerSocket listens on port 6666.


● When a client connects, the server accepts the connection and reads the client's
message.
2. Event Handling in Java

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.

Common Event Listeners:

● ActionListener: For button click actions.


● MouseListener: For mouse events like click, press, release.
● KeyListener: For key events like key press, key release.

Example (Button click event using ActionListener):

import java.awt.*;
import java.awt.event.*;

public class EventHandlingExample extends Frame {


EventHandlingExample() {
Button b = new Button("Click Me");

// Add ActionListener to handle button click


b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button was clicked!");
}
});

// Frame settings
add(b);
setSize(300, 200);
setVisible(true);
}

public static void main(String[] args) {


new EventHandlingExample();
}
}

Explanation:

● The addActionListener() method is used to attach an event listener to the button.


● When the button is clicked, the actionPerformed() method is triggered, and the
message "Button was clicked!" is printed.

3. JDBC (Java Database Connectivity)

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");

// Step 2: Establish a connection


conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase",
"username", "password");

// Step 3: Create a Statement object


stmt = conn.createStatement();

// Step 4: Execute SQL query


String sql = "SELECT * FROM employees";
rs = stmt.executeQuery(sql);

// Step 5: Process the results


while (rs.next()) {
System.out.println("Employee ID: " + rs.getInt("id"));
System.out.println("Employee Name: " +
rs.getString("name"));
System.out.println("Employee Salary: " +
rs.getDouble("salary"));
}
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
// Step 6: Close the resources
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
}
}

Explanation:

● The DriverManager.getConnection() method establishes a connection to the


MySQL database.
● The executeQuery() method runs a SELECT query, and the ResultSet is used to
retrieve the data.
● After processing the result, the database connection is closed.

Important JDBC Methods:

● executeQuery(String sql): Executes a query and returns a ResultSet.


● executeUpdate(String sql): Executes an update query (e.g., INSERT, UPDATE,
DELETE).
● getConnection(String url, String user, String password): Establishes
a connection to the database.
● close(): Closes database resources like Connection, Statement, and ResultSet.
UNIT-IV: HTML

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.

1. Use of Commenting in HTML

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.

Syntax for HTML Comments:

<!-- This is a single-line comment -->


<!--
This is a
multi-line comment
-->

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>

<!-- The following paragraph is an introduction -->


<p>This is a brief introduction to the website.</p>
</body>
</html>

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.

Syntax for Header Tags:

<h1>This is a Heading Level 1</h1>


<h2>This is a Heading Level 2</h2>
<h3>This is a Heading Level 3</h3>
<!-- and so on up to h6 -->

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.

3. Text Styling in HTML

HTML provides a variety of tags to style and format text, such as making it bold, italic,
underlined, or struck-through.

Common Text Styling Tags:

● <b>: Bold text.


● <i>: Italic text.
● <u>: Underlined text.
● <s>: Strikethrough text.
● <mark>: Highlights text.
● <strong>: Defines important text (bold).
● <em>: Defines emphasized text (italic).

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.

Syntax for Image Tag:

<img src="image.jpg" alt="Description of image">

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.

5. Formatting Text with <FONT> Tag

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.

Syntax for <FONT> Tag:

<font color="red" size="5" face="Arial">This is styled text.</font>

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:

● color: Sets the font color.


● size: Sets the size of the text.
● face: Specifies the font type.

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 &lt;
when displayed as text.

Common Special Characters:

● &lt;: Less-than sign (<)


● &gt;: Greater-than sign (>)
● &amp;: Ampersand (&)
● &quot;: Double quotation mark (")
● &apos;: Single quotation mark (')

Example:

<!DOCTYPE html>
<html>
<head>
<title>Special Characters Example</title>
</head>
<body>
<p>&lt;div&gt;This is a div tag.&lt;/div&gt;</p>
<p>He said, &quot;Hello!&quot;</p>
</body>
</html>

Explanation:

● The < and > symbols are replaced with &lt; and &gt; to display them on the web
page.
● The quotation marks are replaced with &quot; 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.

Syntax for Horizontal Rule:

<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.

8. Line Breaks in HTML (<br> Tag)

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.

Syntax for Line Break: <br>


Example:

<!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.

Common Table Tags:

● <table>: Defines the table.


● <tr>: Defines a row within the table.
● <td>: Defines a data cell in the table.
● <th>: Defines a header cell in the table.
Syntax for Table Tags:

<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:

● The <table> tag is used to create the table.


● The <tr> tag creates rows, while <th> is used for header cells and <td> for data cells.
● The border="1" attribute adds a simple border to the table for visual clarity.

10. Forms in HTML

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.

Common Form Tags:

● <form>: Defines the form.


● <input>: Defines an input field (e.g., text, radio button, checkbox).
● <label>: Defines a label for an input element.
● <textarea>: Defines a multi-line text input.
● <button>: Defines a clickable button.

Syntax for Form Tags:

<form action="submit_form.php" method="POST">


<label for="name">Name:</label>
<input type="text" id="name" name="name">

<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>

<button type="submit">Send Message</button>


</form>
</body>
</html>
Explanation:

● 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.

11. Image Maps in HTML

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.

Syntax for Image Maps:

<img src="image.jpg" usemap="#mapname">

<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.

12. META Tags in HTML

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.

Syntax for META Tags:

<meta name="description" content="This is a description of the


webpage">
<meta name="keywords" content="HTML, CSS, JavaScript, Web
Development">
<meta charset="UTF-8">
Example:

<!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.

13. FRAMESET Tags in HTML

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.

Syntax for Frameset Tags:

<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.

1. Introduction to Java Servlets

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.

Key Characteristics of Servlets:

● 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.

2. HTTP Servlet Basics

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.*;

public class HelloServlet extends HttpServlet {


protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body><h1>Hello,
World!</h1></body></html>");
}
}

Explanation:

● HttpServlet: This is the base class for HTTP servlets.


● doGet(): This method is called when the server receives an HTTP GET request. It
generates the HTML response.
● PrintWriter: It writes the response content (in this case, simple HTML) to the client.

3. The Servlet Lifecycle

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.

Servlet Lifecycle Methods:

● init(): Initializes the servlet. This method is called once.


● service(): Handles incoming requests.
● destroy(): Destroys the servlet and releases resources.

Example:

public class ExampleServlet extends HttpServlet {


public void init() {
System.out.println("Servlet initialized");
}

protected void doGet(HttpServletRequest request,


HttpServletResponse response) throws ServletException, IOException {
response.getWriter().println("Handling GET request");
}

public void destroy() {


System.out.println("Servlet destroyed");
}
}

4. Retrieving Information in Servlets

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.

● Form data: Submitted via GET or POST methods.


● Query parameters: Data passed in the URL (e.g., ?name=John).
● Headers: Information like content type, user-agent, etc.
● Cookies: Stored on the client side, retrieved using the getCookies() method.
Example:

protected void doGet(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException {
String name = request.getParameter("name"); // Retrieves 'name'
from query parameters
response.getWriter().println("Hello, " + name);
}

5. Sending HTML Information

Servlets generate dynamic content, including HTML pages. Using the HttpServletResponse
object, servlets can send data (such as HTML) back to the client.

Setting the content type:

response.setContentType("text/html"); // Tells the browser to expect


HTML content
PrintWriter out = response.getWriter();
out.println("<html><body><h1>Dynamic Content</h1></body></html>");

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.

6. Session Tracking in Servlets

Session tracking allows servlets to maintain user-specific data across multiple requests. There
are several ways to track sessions:

1. Cookies: Small pieces of data stored on the client’s browser.


2. URL Rewriting: The session ID is passed in the URL (used when cookies are disabled).
3. HttpSession: The most common way to manage sessions using the HttpSession
interface.

Example of Using HttpSession:

protected void doGet(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException {
HttpSession session = request.getSession();
session.setAttribute("user", "John Doe");
response.getWriter().println("Session created for user: " +
session.getAttribute("user"));
}

Explanation:

● getSession(): Retrieves or creates a session for the client.


● setAttribute(): Sets an attribute (in this case, the user) in the session.
● getAttribute(): Retrieves the attribute from the session.

7. Database Connectivity in Servlets (JDBC)

Java Servlets can connect to databases using JDBC (Java Database Connectivity) to interact
with databases like MySQL, Oracle, etc.

1. Loading the JDBC Driver: Using Class.forName() to load the driver.


2. Establishing a Connection: Using DriverManager.getConnection().
3. Executing Queries: Using Statement or PreparedStatement to execute SQL
queries.
4. Handling Results: Using ResultSet to handle query results.

Example of Database Connection in a Servlet:

import java.sql.*;

public class DatabaseServlet extends HttpServlet {


protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb",
"user", "password");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users");

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.

1. Introduction to Java Server Pages (JSP)

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.

Basic Syntax of JSP:

● 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:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"%>


<html>
<body>
<h1>Welcome to JSP!</h1>
<%
String message = "This is dynamic content from Java!";
out.println(message);
%>
</body>
</html>

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.

3. Setting Up the JSP Environment

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:

1. Install a Web Server (e.g., Tomcat, Jetty).


2. Create a Web Application Project: Organize your project into folders like /WEB-INF
and /pages/.
3. Write JSP Files: Use .jsp files for your web pages, which will contain HTML and Java
code.
4. Deploy: Place your JSP files into the web server’s directory, and the server will process
them.
4. Generating Dynamic Content Using JSP

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:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"%>


<html>
<body>
<h1>Welcome!</h1>
Current Date and Time: <%= new java.util.Date() %>
</body>
</html>

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.

JSTL Tag Example:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<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.

6. Processing Input and Output in JSP

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.

Example of Processing Form Input:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"%>


<html>
<body>
<form method="POST">
Name: <input type="text" name="name"><br>
<input type="submit" value="Submit">
</form>
<%
String name = request.getParameter("name");
if (name != null) {
out.println("<h2>Hello, " + name + "!</h2>");
}
%>
</body>
</html>
Explanation:

● The form submits data using the POST method.


● request.getParameter("name"): Retrieves the value entered by the user in the
form.
● If the user submits the form, the JSP generates a greeting message with the user's
name.

Summary of JSP Concepts:

● 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.

You might also like