UNIT 2 Shot Notes
UNIT 2 Shot Notes
2. Objects in JavaScript
What are Objects?
Objects are like containers that hold related information
Think of an object like a person - they have properties (name, age) and can do actions (walk, talk)
Example:
javascript
// Creating an object
let person = {
name: "John",
age: 25,
city: "Delhi",
greet: function() {
return "Hello, I'm " + this.name;
}
};
let x; // x is undefined
Operations:
javascript
// Arithmetic Operations
let a = 10, b = 5;
let sum = a + b; // Addition: 15
let diff = a - b; // Subtraction: 5
let product = a * b; // Multiplication: 50
let quotient = a / b; // Division: 2
// Comparison Operations
let isEqual = (a == b); // false
let isGreater = (a > b); // true
// Logical Operations
let result = (a > 5) && (b < 10); // true (both conditions are true)
4. Control Statements
If-Else Statements:
javascript
Switch Statement:
javascript
switch(day) {
case "Monday":
console.log("Start of work week");
break;
case "Friday":
console.log("TGIF!");
break;
default:
console.log("Regular day");
}
Loops:
1. For Loop - When you know how many times to repeat
javascript
let count = 1;
while (count <= 3) {
console.log("Number: " + count);
count++;
}
5. Arrays
What are Arrays?
Arrays are like lists that can store multiple values
Think of it as a box with numbered compartments
Example:
javascript
// Creating arrays
let fruits = ["apple", "banana", "orange"];
let numbers = [1, 2, 3, 4, 5];
// Array methods
fruits.push("mango"); // Add to end
fruits.pop(); // Remove from end
console.log(fruits.length); // Get array size
6. Functions
What are Functions?
Functions are reusable blocks of code
Like a recipe - you write it once and use it many times
Types of Functions:
1. Regular Function:
javascript
function greetUser(name) {
return "Hello, " + name + "!";
}
2. Function Expression:
javascript
7. Constructors
What are Constructors?
Constructors are special functions that create objects
Like a factory that produces similar objects
Example:
javascript
// Constructor function
function Student(name, age, course) {
this.name = name;
this.age = age;
this.course = course;
this.introduce = function() {
return "Hi, I'm " + this.name + ", studying " + this.course;
};
}
console.log(student1.introduce());
2. Math Object:
javascript
console.log(Math.round(4.7)); // 5
console.log(Math.max(1, 3, 2)); // 3
console.log(Math.random()); // Random number 0-1
3. String Object:
javascript
// Getting elements
let button = document.getElementById("myButton");
let paragraphs = document.getElementsByTagName("p");
let divs = document.getElementsByClassName("container");
// Changing content
document.getElementById("demo").innerHTML = "New content";
document.getElementById("demo").style.color = "red";
window.alert("Hello!");
window.open("https://google.com");
console.log(window.innerWidth); // Browser width
<form id="myForm">
<input type="text" id="name" placeholder="Enter name">
<input type="email" id="email" placeholder="Enter email">
<input type="password" id="password" placeholder="Enter password">
<button type="submit">Submit</button>
</form>
JavaScript Validation:
javascript
document.getElementById("myForm").addEventListener("submit", function(event) {
event.preventDefault(); // Stop form from submitting
// Validation checks
if (name.length < 2) {
alert("Name must be at least 2 characters");
return;
}
if (!email.includes("@")) {
alert("Please enter a valid email");
return;
}
if (password.length < 6) {
alert("Password must be at least 6 characters");
return;
}
alert("Form is valid!");
});
// Email validation
function validateEmail(email) {
let emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailPattern.test(email);
}
<%
// Java code goes here
String message = "Hello from JSP!";
int number = 42;
%>
3. JSP Processing
How JSP Works:
1. Write JSP - You write .jsp files with HTML + Java
2. Translation - Server converts JSP to Java servlet
3. Compilation - Java servlet gets compiled to bytecode
4. Execution - Compiled servlet runs and generates HTML
5. Response - HTML is sent to user's browser
JSP Lifecycle:
JSP File (.jsp)
↓
Translation (JSP → Servlet)
↓
Compilation (Servlet → Bytecode)
↓
Loading and Instantiation
↓
Initialization (jspInit())
↓
Request Processing (jspService())
↓
Destruction (jspDestroy())
4. Declarations
What are Declarations?
Used to declare variables and methods that will be available throughout the JSP page
Syntax: <%! declaration %>
Example:
jsp
<%!
// Declare variables
int counter = 0;
String siteName = "My Website";
// Declare methods
public String getCurrentTime() {
return new java.util.Date().toString();
}
<html>
<body>
<h1><%= siteName %></h1>
<p>Current time: <%= getCurrentTime() %></p>
<p>5 + 3 = <%= addNumbers(5, 3) %></p>
<p>Page visited: <%= ++counter %> times</p>
</body>
</html>
5. Directives
What are Directives?
Special instructions for the JSP container
Control page-level settings
Three types: page, include, taglib
1. Page Directive:
jsp
2. Include Directive:
jsp
<h1>Main Content</h1>
3. Taglib Directive:
jsp
6. Expressions
What are Expressions?
Used to output values directly to the HTML
Syntax: <%= expression %>
Automatically converted to string
Examples:
jsp
<%
String name = "John";
int age = 25;
double salary = 50000.50;
%>
<html>
<body>
<h1>Employee Details</h1>
<p>Name: <%= name %></p>
<p>Age: <%= age %></p>
<p>Salary: $<%= salary %></p>
<p>Current Date: <%= new java.util.Date() %></p>
<p>Random Number: <%= Math.random() %></p>
<p>Is Adult: <%= age >= 18 ? "Yes" : "No" %></p>
</body>
</html>
<html>
<body>
<h1>Loop Example</h1>
<h3>Available Fruits:</h3>
<% for(String fruit : fruits) { %>
<p>• <%= fruit %></p>
<% } %>
</body>
</html>
8. Implicit Objects
What are Implicit Objects?
Pre-defined objects available in every JSP page
No need to create them - they're automatically available
9 Implicit Objects:
1. request - HTTP request information
jsp
<%
response.setContentType("text/html");
response.addCookie(new Cookie("username", "john"));
%>
<%
session.setAttribute("user", "John Doe");
String user = (String) session.getAttribute("user");
%>
<p>Welcome back, <%= user %>!</p>
<%
application.setAttribute("appName", "My Web App");
String appName = (String) application.getAttribute("appName");
%>
<%
out.println("<h1>Hello World!</h1>");
out.print("Current time: " + new java.util.Date());
%>
// Student.java
public class Student implements java.io.Serializable {
private String name;
private int age;
private String course;
// No-argument constructor
public Student() {}
// Getter methods
public String getName() { return name; }
public int getAge() { return age; }
public String getCourse() { return course; }
// Setter methods
public void setName(String name) { this.name = name; }
public void setAge(int age) { this.age = age; }
public void setCourse(String course) { this.course = course; }
}
Bean Scopes:
page - Available only in current page
request - Available during current request
session - Available during user session
application - Available to all users
10. Cookies and Session Tracking
What are Cookies?
Small pieces of data stored in user's browser
Used to remember user information
Cookie Example:
jsp
<%
// Creating cookies
Cookie userCookie = new Cookie("username", "john_doe");
Cookie themeCookie = new Cookie("theme", "dark");
if(cookies != null) {
for(Cookie cookie : cookies) {
if("username".equals(cookie.getName())) {
username = cookie.getValue();
} else if("theme".equals(cookie.getName())) {
theme = cookie.getValue();
}
}
}
%>
<html>
<body>
<h1>Welcome <%= username.isEmpty() ? "Guest" : username %>!</h1>
<p>Current theme: <%= theme.isEmpty() ? "default" : theme %></p>
</body>
</html>
<html>
<body>
<h1>Dashboard</h1>
<p>Welcome, <%= username %>!</p>
<p>Login time: <%= loginTime %></p>
<p>Session ID: <%= session.getId() %></p>
<a href="logout.jsp">Logout</a>
</body>
</html>
<%
// Database connection details
String url = "jdbc:mysql://localhost:3306/schooldb";
String username = "root";
String password = "password";
try {
// Load MySQL driver
Class.forName("com.mysql.cj.jdbc.Driver");
// Create connection
conn = DriverManager.getConnection(url, username, password);
// Create statement
stmt = conn.createStatement();
// Execute query
String query = "SELECT * FROM students ORDER BY name";
rs = stmt.executeQuery(query);
%>
<html>
<body>
<h1>Student List</h1>
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
<th>Course</th>
</tr>
<%
} catch(Exception e) {
out.println("<p style='color:red'>Error: " + e.getMessage() + "</p>");
} finally {
// Close connections
try {
if(rs != null) rs.close();
if(stmt != null) stmt.close();
if(conn != null) conn.close();
} catch(SQLException e) {
out.println("<p>Error closing connection: " + e.getMessage() + "</p>");
}
}
%>
try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/schooldb",
"root",
"password"
);
String insertQuery = "INSERT INTO students (name, age, course) VALUES (?, ?
pstmt = conn.prepareStatement(insertQuery);
pstmt.setString(1, name);
pstmt.setInt(2, age);
pstmt.setString(3, course);
if(result > 0) {
out.println("<p style='color:green'>Student added successfully!</p>");
} else {
out.println("<p style='color:red'>Failed to add student.</p>");
}
} catch(Exception e) {
out.println("<p style='color:red'>Error: " + e.getMessage() + "</p>");
} finally {
try {
if(pstmt != null) pstmt.close();
if(conn != null) conn.close();
} catch(SQLException e) {
out.println("<p>Error closing connection: " + e.getMessage() + "</p>")
}
}
}
%>
<html>
<body>
<h1>Add New Student</h1>
<form method="post" action="add_student.jsp">
<p>Name: <input type="text" name="name" required></p>
<p>Age: <input type="number" name="age" required></p>
<p>Course: <input type="text" name="course" required></p>
<p><input type="submit" value="Add Student"></p>
</form>
Summary
JavaScript is used to make web pages interactive on the client-side (user's browser), while JSP is
used to create dynamic web pages on the server-side using Java. JavaScript handles user
interactions, form validations, and DOM manipulation, while JSP handles server-side logic, database
connections, and generating dynamic HTML content.
Both technologies work together in modern web applications - JSP generates the initial HTML with
data from the server, and JavaScript makes it interactive in the browser.