books.dtd <!ELEMENT library (book+)> <!ELEMENT book (title, author, isbn, publisher, edition, price)> <!ELEMENT title (#PCDATA)> <!ELEMENT author (#PCDATA)> <!ELEMENT isbn (#PCDATA)> <!ELEMENT publisher (#PCDATA)> <!ELEMENT edition (#PCDATA)> <!ELEMENT price (#PCDATA)> books.xsd <?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="library"> <xs:complexType> <xs:sequence> <xs:element name="book" maxOccurs="unbounded"> <xs:complexType> <xs:sequence> <xs:element name="title" type="xs:string"/> <xs:element name="author" type="xs:string"/> <xs:element name="isbn" type="xs:string"/> <xs:element name="publisher" type="xs:string"/> <xs:element name="edition" type="xs:string"/> <xs:element name="price" type="xs:decimal"/> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>
use itb; create table students(name varchar(50),rollno int,branch varchar(20)); insert into students (name,rollno,branch) values ('niha',90,'it'), ('nishka',95,'it'), ('nishu',96,'it'); JAVA package jdbc; import java.sql.*; public class Simple_Connection { Connection conn = null; public static void main(String[] args) { // TODO Auto-generated method stub try { Class.forName("com.mysql.cj.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/itb","root","root"); Statement stmt = conn.createStatement(); ResultSet rs=stmt.executeQuery("Select * from students"); while(rs.next()){ System.out.println(rs.getString(1)+" "+rs.getInt(2)+" "+rs.getString(3)); } conn.close(); }catch(Exception e) { e.printStackTrace(); } } }
5.Javascript program to demostrate working of prototypal inheritance ,closure,callbacks,promises and sync/await // Prototypal Inheritance function Animal(name) { this.name = name; } Animal.prototype.speak = function() { console.log(`${this.name} makes a noise.`); }; function Dog(name) { Animal.call(this, name); // Call the parent constructor } Dog.prototype = Object.create(Animal.prototype); Dog.prototype.constructor = Dog; Dog.prototype.speak = function() { console.log(`${this.name} barks.`); }; // Closure function createCounter() { let count = 0; // Private variable return { increment: function() { count++; return count; }, decrement: function() { count--; return count; }, getCount: function() { return count; } }; } // Callback function fetchData(callback) { setTimeout(() => { const data = { message: "Data fetched!" }; callback(data); }, 1000); } // Promise function fetchDataPromise() { return new Promise((resolve, reject) => { setTimeout(() => { const data = { message: "Data fetched with Promise!" }; resolve(data); }, 1000); }); } // Async/Await async function fetchDataAsync() { const data = await fetchDataPromise(); console.log(data.message); } // Demonstration function demo() { // Prototypal Inheritance const dog = new Dog('Buddy'); dog.speak(); // Output: Buddy barks. // Closure const counter = createCounter(); console.log(counter.increment()); // Output: 1 console.log(counter.increment()); // Output: 2 console.log(counter.decrement()); // Output: 1 console.log(counter.getCount()); // Output: 1 // Callback fetchData((data) => { console.log(data.message); // Output: Data fetched! }); // Promise fetchDataPromise().then((data) => { console.log(data.message); // Output: Data fetched with Promise! }); // Async/Await fetchDataAsync(); // Output: Data fetched with Promise! } // Run the demonstration demo();
3.Validate the registration ,user login,user profile and payment pages using javascript .Make use of any needed javascrpt objects HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Registration</title> <link rel="stylesheet" href="styles.css"> </head> <body> <h1>Register</h1> <form id="registrationForm"> <input type="text" id="username" placeholder="Username" required> <input type="email" id="email" placeholder="Email" required> <input type="password" id="password" placeholder="Password" required> <button type="submit">Register</button> <div id="message" class="error-message"></div> </form> <script src="script.js"></script> </body> </html> script.js document.getElementById("registrationForm").addEventListener("submit", function(event) { event.preventDefault(); // Prevent form submission validateRegistration(); }); function validateRegistration() { const username = document.getElementById("username").value; const email = document.getElementById("email").value; const password = document.getElementById("password").value; const messageDiv = document.getElementById("message"); messageDiv.textContent = ""; // Simple validation if (username.length < 3) { messageDiv.textContent = "Username must be at least 3 characters."; return; } if (!/\S+@\S+\.\S+/.test(email)) { messageDiv.textContent = "Email is not valid."; return; } if (password.length < 6) { messageDiv.textContent = "Password must be at least 6 characters."; return; } messageDiv.textContent = "Registration successful!"; // You can proceed to send the data to the server here } User Login Page(HTML) <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Login</title> <link rel="stylesheet" href="styles.css"> </head> <body> <h1>Login</h1> <form id="loginForm"> <input type="email" id="loginEmail" placeholder="Email" required> <input type="password" id="loginPassword" placeholder="Password" required> <button type="submit">Login</button> <div id="loginMessage" class="error-message"></div> </form> <script src="script.js"></script> </body> </html> script.js document.getElementById("loginForm").addEventListener("submit", function(event) { event.preventDefault(); // Prevent form submission validateLogin(); }); function validateLogin() { const email = document.getElementById("loginEmail").value; const password = document.getElementById("loginPassword").value; const loginMessageDiv = document.getElementById("loginMessage"); loginMessageDiv.textContent = ""; // Simple validation if (!/\S+@\S+\.\S+/.test(email)) { loginMessageDiv.textContent = "Email is not valid."; return; } if (password.length < 6) { loginMessageDiv.textContent = "Password must be at least 6 characters."; return; } loginMessageDiv.textContent = "Login successful!"; // You can proceed to authenticate the user here } User Profile Page(HTML) <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>User Profile</title> <link rel="stylesheet" href="styles.css"> </head> <body> <h1>User Profile</h1> <form id="profileForm"> <input type="text" id="profileUsername" placeholder="Username" required> <input type="email" id="profileEmail" placeholder="Email" required> <button type="submit">Update Profile</button> <div id="profileMessage" class="error-message"></div> </form> <script src="script.js"></script> </body> </html> script.js document.getElementById("profileForm").addEventListener("submit", function(event) { event.preventDefault(); // Prevent form submission validateProfile(); }); function validateProfile() { const username = document.getElementById("profileUsername").value; const email = document.getElementById("profileEmail").value; const profileMessageDiv = document.getElementById("profileMessage"); profileMessageDiv.textContent = ""; // Simple validation if (username.length < 3) { profileMessageDiv.textContent = "Username must be at least 3 characters."; return; } if (!/\S+@\S+\.\S+/.test(email)) { profileMessageDiv.textContent = "Email is not valid."; return; } profileMessageDiv.textContent = "Profile updated successfully!"; // You can proceed to update the user profile on the server here } Payment page(HTML) <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Payment</title> <link rel="stylesheet" href="styles.css"> </head> <body> <h1>Payment</h1> <form id="paymentForm"> <input type="text" id="cardNumber" placeholder="Card Number" required> <input type="text" id="expiryDate" placeholder="MM/YY" required> <input type="text" id="cvv" placeholder="CVV" required> <button type="submit">Pay</button> <div id="paymentMessage" class="error-message"></div> </form> <script src="script.js"></script> </body> </html> script.js document.getElementById("paymentForm").addEventListener("submit", function(event) { event.preventDefault(); // Prevent form submission validatePayment(); }); function validatePayment() { const cardNumber = document.getElementById("cardNumber").value; const expiryDate = document.getElementById("expiryDate").value; const cvv = document.getElementById("cvv").value; const paymentMessageDiv = document.getElementById("paymentMessage"); paymentMessageDiv.textContent = ""; // Simple validation if (!/^\d{16}$/.test(cardNumber)) { paymentMessageDiv.textContent = "Card number must be 16 digits."; return; } if (!/^(0[1-9]|1[0-2])\/\d{2}$/.test(expiryDate)) { paymentMessageDiv.textContent = "Expiry date must be in MM/YY format."; return; } if (!/^\d{3}$/.test(cvv)) { paymentMessageDiv.textContent = "CVV must be 3 digits."; return; } paymentMessageDiv.textContent = "Payment successful!"; // You can proceed to process the payment here }
HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Responsive Web Page with Bootstrap</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <link rel="stylesheet" href="styles.css"> </head> <body> <header class="bg-success text-white text-center py-4"> <h1>My Awesome Web Page</h1> </header> <main class="container my-5"> <section class="row"> <div class="col-lg-4 col-md-6 mb-4"> <div class="card grid-item"> <div class="card-body"> <h5 class="card-title">Item 1</h5> </div> </div> </div> <div class="col-lg-4 col-md-6 mb-4"> <div class="card grid-item"> <div class="card-body"> <h5 class="card-title">Item 2</h5> </div> </div> </div> <div class="col-lg-4 col-md-6 mb-4"> <div class="card grid-item"> <div class="card-body"> <h5 class="card-title">Item 3</h5> </div> </div> </div> <div class="col-lg-4 col-md-6 mb-4"> <div class="card grid-item"> <div class="card-body"> <h5 class="card-title">Item 4</h5> </div> </div> </div> <div class="col-lg-4 col-md-6 mb-4"> <div class="card grid-item"> <div class="card-body"> <h5 class="card-title">Item 5</h5> </div> </div> </div> </section> </main> <footer class="bg-dark text-white text-center py-3"> <p>Footer Content</p> </footer> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script> </body> </html> CSS .grid-item { background-color: #ffcc00; transition: transform 0.3s ease, background-color 0.3s ease; } .grid-item:hover { transform: scale(1.05); background-color: #ffd700; }
<!-- index.html --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Form Submission</title> </head> <body> <form action="/submit-form" 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> <button type="submit">Submit</button> </form> </body> </html> // server.js const express = require('express'); const bodyParser = require('body-parser'); const app = express(); const port = 3000; app.use(bodyParser.urlencoded({ extended: true })); app.get('/', (req, res) => { res.sendFile(__dirname + '/index.html'); }); app.post('/submit-form', (req, res) => { const { name, email } = req.body; res.send(Hello, ${name}! We have received your email: ${email}.); }); app.listen(port, () => { console.log(Server is running on http://localhost:${port}); });
TASK 13 Servlet code import java.io.IOException; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/exampleServlet") public class ExampleServlet extends HttpServlet { // Initialize the servlet and get ServletConfig and ServletContext @Override public void init(ServletConfig config) throws ServletException { super.init(config); // Get ServletConfig parameters String param1 = config.getInitParameter("param1"); String param2 = config.getInitParameter("param2"); // Print ServletConfig parameters System.out.println("ServletConfig param1: " + param1); System.out.println("ServletConfig param2: " + param2); // Get ServletContext ServletContext context = config.getServletContext(); // Get context parameters String contextParam1 = context.getInitParameter("contextParam1"); // Print ServletContext parameters System.out.println("ServletContext contextParam1: " + contextParam1); } // Handle HTTP GET requests @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); response.getWriter().println("<h1>ServletConfig and ServletContext Parameters</h1>"); response.getWriter().println("<p>Check the server logs for printed parameters.</p>"); } } Web. Xml <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <servlet> <servlet-name>exampleServlet</servlet-name> <servlet-class>ExampleServlet</servlet-class> <init-param> <param-name>param1</param-name> <param-value>Value1</param-value> </init-param> <init-param> <param-name>param2</param-name> <param-value>Value2</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>exampleServlet</servlet-name> <url-pattern>/exampleServlet</url-pattern> </servlet-mapping> <context-param> <param-name>contextParam1</param-name> <param-value>ContextValue1</param-value> </context-param> </web-app>
TASK 07 DTD <!DOCTYPE library [ <!ELEMENT library (book+)> <!ELEMENT book (title, author, isbn, publisher, edition, price)> <!ELEMENT title (#PCDATA)> <!ELEMENT author (#PCDATA)> <!ELEMENT isbn (#PCDATA)> <!ELEMENT publisher (#PCDATA)> <!ELEMENT edition (#PCDATA)> <!ELEMENT price (#PCDATA)> ]> XML <?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="library"> <xs:complexType> <xs:sequence> <xs:element name="book" maxOccurs="unbounded"> <xs:complexType> <xs:sequence> <xs:element name="title" type="xs:string"/> <xs:element name="author" type="xs:string"/> <xs:element name="isbn" type="xs:string"/> <xs:element name="publisher" type="xs:string"/> <xs:element name="edition" type="xs:string"/> <xs:element name="price" type="xs:decimal"/> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>
TASK 06 <?xml version="1.0" encoding="UTF-8"?> <library> <book> <title>The Great Gatsby</title> <author>F. Scott Fitzgerald</author> <isbn>9780743273565</isbn> <publisher>Charles Scribner's Sons</publisher> <edition>First</edition> <price>10.99</price> </book> <book> <title>To Kill a Mockingbird</title> <author>Harper Lee</author> <isbn>9780060935467</isbn> <publisher>J.B. Lippincott & Co.</publisher> <edition>50th Anniversary</edition> <price>7.99</price> </book> <book> <title>1984</title> <author>George Orwell</author> <isbn>9780451524935</isbn> <publisher>Harcourt Brace Jovanovich</publisher> <edition>Signet Classics</edition> <price>9.99</price> </book> </library>
package task11; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; public class metadata { // Database URL, user, and password static final String JDBC_URL = "jdbc:mysql://localhost:3306/varshitha"; // Replace with your database name static final String JDBC_USER = "root"; // Replace with your username static final String JDBC_PASSWORD = "root"; // Replace with your password public static void main(String[] args) { try (Connection connection = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD)) { // Get database metadata DatabaseMetaData dbMetaData = connection.getMetaData(); // Display general database information System.out.println("Database Product Name: " + dbMetaData.getDatabaseProductName()); System.out.println("Database Product Version: " + dbMetaData.getDatabaseProductVersion()); System.out.println("Database Driver Name: " + dbMetaData.getDriverName()); System.out.println("Database Driver Version: " + dbMetaData.getDriverVersion()); // Retrieve and display table metadata System.out.println("\nTables in the database:"); ResultSet tables = dbMetaData.getTables(null, null, "%", new String[] { "TABLE" }); while (tables.next()) { String tableName = tables.getString("TABLE_NAME"); System.out.println("Table: " + tableName); // Retrieve and display column metadata for each table ResultSet columns = dbMetaData.getColumns(null, null, tableName, "%"); while (columns.next()) { String columnName = columns.getString("COLUMN_NAME"); String columnType = columns.getString("TYPE_NAME"); int columnSize = columns.getInt("COLUMN_SIZE"); System.out.println(" Column: " + columnName + " - Type: " + columnType + " - Size: " + columnSize); } columns.close(); } tables.close(); } catch (SQLException e) { System.out.println("SQL Exception: " + e.getMessage()); } } }
package task10; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class updandscroll { // Database credentials and URL static final String JDBC_URL = "jdbc:mysql://localhost:3306/varshitha"; // Replace with your database name static final String JDBC_USER = "root"; // Replace with your MySQL username static final String JDBC_PASSWORD = "root"; // Replace with your MySQL password public static void main(String[] args) { try (Connection connection = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD); Statement statement = connection.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, // Scrollable ResultSet ResultSet.CONCUR_UPDATABLE)) { // Updatable ResultSet // Query to select all records from Students String selectSQL = "SELECT id, name, age, grade FROM Students"; ResultSet resultSet = statement.executeQuery(selectSQL); // Scroll to last row and display data if (resultSet.last()) { System.out.println("Last Row - ID: " + resultSet.getInt("id") + ", Name: " + resultSet.getString("name") + ", Age: " + resultSet.getInt("age") + ", Grade: " + resultSet.getString("grade")); } // Move to the first row and update the age and grade resultSet.first(); resultSet.updateInt("age", resultSet.getInt("age") + 1); // Increase age by 1 resultSet.updateString("grade", "A"); // Set grade to 'A' resultSet.updateRow(); // Commit the update System.out.println("Updated first row age and grade."); // Insert a new row into the ResultSet resultSet.moveToInsertRow(); resultSet.updateInt("id", 101); // Example ID resultSet.updateString("name", "New Student"); resultSet.updateInt("age", 20); resultSet.updateString("grade", "B"); resultSet.insertRow(); System.out.println("Inserted new row."); // Display all rows after the updates resultSet.beforeFirst(); // Move cursor to the beginning System.out.println("Updated Students Table:"); while (resultSet.next()) { System.out.println("ID: " + resultSet.getInt("id") + ", Name: " + resultSet.getString("name") + ", Age: " + resultSet.getInt("age") + ", Grade: " + resultSet.getString("grade")); } } catch (SQLException e) { System.out.println("SQL Exception: " + e.getMessage()); } } }
package task9; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; public class preparedstmt { // Database credentials and URL static final String JDBC_URL = "jdbc:mysql://localhost:3306/varshitha"; // Replace with your database name static final String JDBC_USER = "root"; // Replace with your MySQL username static final String JDBC_PASSWORD = "root"; // Replace with your MySQL password public static void main(String[] args) { // SQL query to insert data into the Students table String insertSQL = "INSERT INTO Students (name, age, grade) VALUES (?, ?, ?)"; // Try with resources to automatically close the connection and statement try (Connection connection = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD); PreparedStatement preparedStatement = connection.prepareStatement(insertSQL)) { // Insert first student preparedStatement.setString(1, "Alice"); preparedStatement.setInt(2, 20); preparedStatement.setString(3, "A"); preparedStatement.executeUpdate(); System.out.println("Inserted first student: Alice"); // Insert second student preparedStatement.setString(1, "Bob"); preparedStatement.setInt(2, 22); preparedStatement.setString(3, "B"); preparedStatement.executeUpdate(); System.out.println("Inserted second student:s Bob"); } catch (SQLException e) { System.out.println("SQL Exception: " + e.getMessage()); } } } package task9; import java.sql.Connection; import java.sql.DriverManager; import java.sql.CallableStatement; import java.sql.ResultSet; import java.sql.SQLException; public class callableprocedures { // Database credentials and URL static final String JDBC_URL = "jdbc:mysql://localhost:3306/varshitha"; // Replace with your database name static final String JDBC_USER = "root"; // Replace with your MySQL username static final String JDBC_PASSWORD = "root"; // Replace with your MySQL password public static void main(String[] args) { // SQL query to call the stored procedure String callProcedureSQL = "{call selectGradeAStudents()}"; try (Connection connection = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD); CallableStatement callableStatement = connection.prepareCall(callProcedureSQL); ResultSet resultSet = callableStatement.executeQuery()) { System.out.println("Students with Grade A:"); while (resultSet.next()) { // Assuming the Students table has columns: id, name, age, and grade int id = resultSet.getInt("id"); String name = resultSet.getString("name"); int age = resultSet.getInt("age"); String grade = resultSet.getString("grade"); System.out.printf("ID: %d, Name: %s, Age: %d, Grade: %s%n", id, name, age, grade); } } catch (SQLException e) { System.out.println("SQL Exception: " + e.getMessage()); } } } package task9; import java.sql.Connection; import java.sql.DriverManager; import java.sql.CallableStatement; import java.sql.ResultSet; import java.sql.SQLException; public class callablefunctions { // Database credentials and URL static final String JDBC_URL = "jdbc:mysql://localhost:3306/varshitha"; // Replace with your database name static final String JDBC_USER = "root"; // Replace with your MySQL username static final String JDBC_PASSWORD = "root"; // Replace with your MySQL password public static void main(String[] args) { // SQL query to call the stored function String callFunctionSQL = "{? = call getAverageAgeByGrade(?)}"; try (Connection connection = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD); CallableStatement callableStatement = connection.prepareCall(callFunctionSQL)) { // Register the output parameter (the average age) callableStatement.registerOutParameter(1, java.sql.Types.DOUBLE); // Set the input parameter (the grade for which we want the average age) callableStatement.setString(2, "A"); // Change the grade as needed // Execute the function callableStatement.execute(); // Retrieve the output parameter double averageAge = callableStatement.getDouble(1); System.out.println("Average age of students with grade 'A': " + averageAge); } catch (SQLException e) { System.out.println("SQL Exception: " + e.getMessage()); } } }
package task8; import java.sql.*; public class jdbcex { // Database credentials and URL static final String JDBC_URL = "jdbc:mysql://localhost:3306/varshitha"; // Replace with your database name static final String JDBC_USER = "root"; // Replace with your MySQL username static final String JDBC_PASSWORD = "root"; // Replace with your MySQL password public static void main(String[] args) { try { // Load the MySQL JDBC driver Class.forName("com.mysql.cj.jdbc.Driver"); // Establish the connection Connection connection = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD); System.out.println("Connected to the database."); // Create a statement object to execute SQL commands Statement statement = connection.createStatement(); // SQL query to create a table named "Students" String createTableSQL = "CREATE TABLE IF NOT EXISTS Students (" + "id INT AUTO_INCREMENT PRIMARY KEY, " + "name VARCHAR(50) NOT NULL, " + "age INT, " + "grade VARCHAR(10)" + ");"; // Execute the SQL command to create the table statement.executeUpdate(createTableSQL); System.out.println("Table 'Students' created successfully."); // Close the statement and connection statement.close(); connection.close(); } catch (SQLException | ClassNotFoundException e) { System.out.println("Error: " + e.getMessage()); } } }
TASK 05 // Prototypal inheritance function Person(name) { this.name = name; } Person.prototype.greet = function () { console.log(Hello, my name is ${this.name}.); }; function Employee(name, jobTitle) { Person.call(this, name); // Call parent constructor this.jobTitle = jobTitle; } Employee.prototype = Object.create(Person.prototype); Employee.prototype.constructor = Employee; Employee.prototype.describeJob = function () { console.log(I am a ${this.jobTitle}.); }; // Closure example function createCounter() { let count = 0; // Private variable return () => ++count; // Increment count and return } // Callback example function fetchData(callback) { setTimeout(() => { const data = { id: 1, name: "John Doe" }; callback(data); }, 1000); // Simulate async operation } // Promise example function fetchDataPromise() { return new Promise((resolve) => { setTimeout(() => { resolve({ id: 2, name: "Jane Smith" }); }, 1000); }); } // Async/Await example async function fetchAndProcessData() { const data = await fetchDataPromise(); console.log(Fetched data: ${JSON.stringify(data)}); } // Instantiate and use const person = new Person("Alice"); const employee = new Employee("Bob", "Developer"); person.greet(); // Hello, my name is Alice. employee.greet(); // Hello, my name is Bob. employee.describeJob(); // I am a Developer. const counter = createCounter(); console.log(counter()); // 1 console.log(counter()); // 2 fetchData((data) => { console.log(Fetched data using callback: ${JSON.stringify(data)}); }); fetchAndProcessData(); // Fetched data: {"id":2,"name":"Jane Smith"}
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Scientific Calculator</title> <style> body { display: flex; justify-content: center; align-items: center; height: 100vh; background: #f4f4f4; font-family: Arial; } .calculator { background: #fff; border-radius: 10px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); padding: 20px; } #display { width: 100%; height: 40px; font-size: 24px; text-align: right; border: 1px solid #ddd; border-radius: 5px; padding: 5px; margin-bottom: 10px; } .buttons { display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px; } button { padding: 15px; font-size: 18px; background: #007bff; color: white; border: none; border-radius: 5px; cursor: pointer; } button:hover { background: #0056b3; } </style> </head> <body> <div class="calculator"> <input type="text" id="display" disabled> <div class="buttons"> <button onclick="clearDisplay()">C</button> <button onclick="appendToDisplay('(')">(</button> <button onclick="appendToDisplay(')')">)</button> <button onclick="appendToDisplay('/')">/</button> <button onclick="appendToDisplay('7')">7</button> <button onclick="appendToDisplay('8')">8</button> <button onclick="appendToDisplay('9')">9</button> <button onclick="appendToDisplay('')"></button> <button onclick="appendToDisplay('4')">4</button> <button onclick="appendToDisplay('5')">5</button> <button onclick="appendToDisplay('6')">6</button> <button onclick="appendToDisplay('-')">-</button> <button onclick="appendToDisplay('1')">1</button> <button onclick="appendToDisplay('2')">2</button> <button onclick="appendToDisplay('3')">3</button> <button onclick="appendToDisplay('+')">+</button> <button onclick="appendToDisplay('0')">0</button> <button onclick="appendToDisplay('.')">.</button> <button onclick="calculate()">=</button> <button onclick="appendToDisplay('Math.sqrt(')">√</button> <button onclick="appendToDisplay('Math.pow(')">x²</button> <button onclick="appendToDisplay('Math.sin(')">sin</button> <button onclick="appendToDisplay('Math.cos(')">cos</button> <button onclick="appendToDisplay('Math.tan(')">tan</button> </div> </div> <script> function appendToDisplay(value) { document.getElementById('display').value += value; } function clearDisplay() { document.getElementById('display').value = ''; } function calculate() { try { document.getElementById('display').value = eval(document.getElementById('display').value); } catch { document.getElementById('display').value = 'Error'; } } </script> </body> </html>
Task -3 Registration page <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Registration</title> </head> <body> <form id="registrationForm"> <input type="text" id="username" placeholder="Username" required><br> <input type="email" id="email" placeholder="Email" required><br> <input type="password" id="password" placeholder="Password" required><br> <input type="text" id="phone" placeholder="Phone" required><br> <button type="submit">Register</button> </form> <script> registrationForm.onsubmit = (e) => { e.preventDefault(); const username = username.value, email = email.value, password = password.value, phone = phone.value; const errors = [ username.length < 5 && "Username must be 5+ characters", !/@/.test(email) && "Invalid email", password.length < 6 && "Password must be 6+ characters", !/^\d{10}$/.test(phone) && "Phone must be 10 digits" ].filter(Boolean); alert(errors.length ? errors.join("\n") : "Registration successful!"); }; </script> </body> </html> Task-3 Login page <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Login</title> </head> <body> <form id="loginForm"> <input type="text" id="loginUsername" placeholder="Username" required><br> <input type="password" id="loginPassword" placeholder="Password" required><br> <button type="submit">Login</button> </form> <script> loginForm.onsubmit = (e) => { e.preventDefault(); const username = loginUsername.value, password = loginPassword.value; alert(username && password ? "Login successful!" : "Please fill out all fields."); }; </script> </body> </html> Task -3 User profile page <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>User Profile</title> </head> <body> <form id="profileForm"> <input type="text" id="name" placeholder="Name" required><br> <input type="email" id="profileEmail" placeholder="Email" required><br> <input type="text" id="address" placeholder="Address" required><br> <button type="submit">Update</button> </form> <script> profileForm.onsubmit = (e) => { e.preventDefault(); const name = name.value, email = profileEmail.value, address = address.value; const errors = [ name.length < 3 && "Name must be 3+ characters", !/@/.test(email) && "Invalid email", address.length < 5 && "Address must be 5+ characters" ].filter(Boolean); alert(errors.length ? errors.join("\n") : "Profile updated!"); }; </script> </body> </html> Task -3 Payment page <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Payment</title> </head> <body> <form id="paymentForm"> <input type="text" id="cardNumber" placeholder="Card Number" required><br> <input type="text" id="expiryDate" placeholder="MM/YY" required><br> <input type="text" id="cvv" placeholder="CVV" required><br> <button type="submit">Pay</button> </form> <script> paymentForm.onsubmit = (e) => { e.preventDefault(); const cardNumber = cardNumber.value, expiryDate = expiryDate.value, cvv = cvv.value; const errors = [ !/^\d{16}$/.test(cardNumber) && "Card must be 16 digits", !/^\d{2}\/\d{2}$/.test(expiryDate) && "Invalid date format", !/^\d{3}$/.test(cvv) && "CVV must be 3 digits" ].filter(Boolean); alert(errors.length ? errors.join("\n") : "Payment successful!"); }; </script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Responsive Bootstrap Layout</title> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <!-- Header --> <header class="bg-primary text-white text-center py-5"> <h1>Welcome to My Page</h1> <p>Explore Bootstrap Layouts!</p> </header> <!-- Main Content --> <main class="container my-5"> <div class="row"> <!-- Cards Section --> <section class="col-lg-8 col-md-7 mb-4"> <div class="row"> <div class="col-sm-6 mb-4"> <div class="card shadow-sm"> <div class="card-body text-center">Card 1</div> </div> </div> <div class="col-sm-6 mb-4"> <div class="card shadow-sm"> <div class="card-body text-center">Card 2</div> </div> </div> </div> </section> <!-- Sidebar --> <aside class="col-lg-4 col-md-5 mb-4"> <div class="card shadow-sm"> <div class="card-body"> <h2>Sidebar</h2> <p>Sidebar content here.</p> </div> </div> </aside> </div> </main> <!-- Footer --> <footer class="bg-dark text-white text-center py-3"> <p>© 2024 My Page</p> </footer> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script> </body> </html>
1.create a web page using the advanced features of css:Grid,Flexbox.And apply transition and animations on the contents of the webpage HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>CSS Grid and Flexbox Example</title> <link rel="stylesheet" href="styles.css"> </head> <body> <header class="header"> <h1>My Awesome Web Page</h1> </header> <main class="main-content"> <section class="grid-container"> <div class="grid-item">Item 1</div> <div class="grid-item">Item 2</div> <div class="grid-item">Item 3</div> <div class="grid-item">Item 4</div> <div class="grid-item">Item 5</div> </section> </main> <footer class="footer"> <p>Footer Content</p> </footer> </body> </html> CSS * { box-sizing: border-box; margin: 0; padding: 0; } body { font-family: Arial, sans-serif; display: flex; flex-direction: column; height: 100vh; } .header { background-color: #4CAF50; color: white; text-align: center; padding: 20px; } .main-content { flex: 1; display: flex; justify-content: center; align-items: center; background-color: #f4f4f4; } .grid-container { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 15px; padding: 20px; } .grid-item { background-color: #ffcc00; padding: 20px; border-radius: 5px; text-align: center; transition: transform 0.3s ease, background-color 0.3s ease; } .grid-item:hover { transform: scale(1.1); background-color: #ffd700; } .footer { background-color: #333; color: white; text-align: center; padding: 10px; } @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } } .header, .footer { animation: fadeIn 1s ease-in; } 2.make the webpages created in the above experiment as responsive web page with Bootstrap Framework HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Responsive Web Page with Bootstrap</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <link rel="stylesheet" href="styles.css"> </head> <body> <header class="bg-success text-white text-center py-4"> <h1>My Awesome Web Page</h1> </header> <main class="container my-5"> <section class="row"> <div class="col-lg-4 col-md-6 mb-4"> <div class="card grid-item"> <div class="card-body"> <h5 class="card-title">Item 1</h5> </div> </div> </div> <div class="col-lg-4 col-md-6 mb-4"> <div class="card grid-item"> <div class="card-body"> <h5 class="card-title">Item 2</h5> </div> </div> </div> <div class="col-lg-4 col-md-6 mb-4"> <div class="card grid-item"> <div class="card-body"> <h5 class="card-title">Item 3</h5> </div> </div> </div> <div class="col-lg-4 col-md-6 mb-4"> <div class="card grid-item"> <div class="card-body"> <h5 class="card-title">Item 4</h5> </div> </div> </div> <div class="col-lg-4 col-md-6 mb-4"> <div class="card grid-item"> <div class="card-body"> <h5 class="card-title">Item 5</h5> </div> </div> </div> </section> </main> <footer class="bg-dark text-white text-center py-3"> <p>Footer Content</p> </footer> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script> </body> </html> CSS .grid-item { background-color: #ffcc00; transition: transform 0.3s ease, background-color 0.3s ease; } .grid-item:hover { transform: scale(1.05); background-color: #ffd700; } 3.Validate the registration ,user login,user profile and payment pages using javascript .Make use of any needed javascrpt objects HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Registration</title> <link rel="stylesheet" href="styles.css"> </head> <body> <h1>Register</h1> <form id="registrationForm"> <input type="text" id="username" placeholder="Username" required> <input type="email" id="email" placeholder="Email" required> <input type="password" id="password" placeholder="Password" required> <button type="submit">Register</button> <div id="message" class="error-message"></div> </form> <script src="script.js"></script> </body> </html> script.js document.getElementById("registrationForm").addEventListener("submit", function(event) { event.preventDefault(); // Prevent form submission validateRegistration(); }); function validateRegistration() { const username = document.getElementById("username").value; const email = document.getElementById("email").value; const password = document.getElementById("password").value; const messageDiv = document.getElementById("message"); messageDiv.textContent = ""; // Simple validation if (username.length < 3) { messageDiv.textContent = "Username must be at least 3 characters."; return; } if (!/\S+@\S+\.\S+/.test(email)) { messageDiv.textContent = "Email is not valid."; return; } if (password.length < 6) { messageDiv.textContent = "Password must be at least 6 characters."; return; } messageDiv.textContent = "Registration successful!"; // You can proceed to send the data to the server here } User Login Page(HTML) <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Login</title> <link rel="stylesheet" href="styles.css"> </head> <body> <h1>Login</h1> <form id="loginForm"> <input type="email" id="loginEmail" placeholder="Email" required> <input type="password" id="loginPassword" placeholder="Password" required> <button type="submit">Login</button> <div id="loginMessage" class="error-message"></div> </form> <script src="script.js"></script> </body> </html> script.js document.getElementById("loginForm").addEventListener("submit", function(event) { event.preventDefault(); // Prevent form submission validateLogin(); }); function validateLogin() { const email = document.getElementById("loginEmail").value; const password = document.getElementById("loginPassword").value; const loginMessageDiv = document.getElementById("loginMessage"); loginMessageDiv.textContent = ""; // Simple validation if (!/\S+@\S+\.\S+/.test(email)) { loginMessageDiv.textContent = "Email is not valid."; return; } if (password.length < 6) { loginMessageDiv.textContent = "Password must be at least 6 characters."; return; } loginMessageDiv.textContent = "Login successful!"; // You can proceed to authenticate the user here } User Profile Page(HTML) <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>User Profile</title> <link rel="stylesheet" href="styles.css"> </head> <body> <h1>User Profile</h1> <form id="profileForm"> <input type="text" id="profileUsername" placeholder="Username" required> <input type="email" id="profileEmail" placeholder="Email" required> <button type="submit">Update Profile</button> <div id="profileMessage" class="error-message"></div> </form> <script src="script.js"></script> </body> </html> script.js document.getElementById("profileForm").addEventListener("submit", function(event) { event.preventDefault(); // Prevent form submission validateProfile(); }); function validateProfile() { const username = document.getElementById("profileUsername").value; const email = document.getElementById("profileEmail").value; const profileMessageDiv = document.getElementById("profileMessage"); profileMessageDiv.textContent = ""; // Simple validation if (username.length < 3) { profileMessageDiv.textContent = "Username must be at least 3 characters."; return; } if (!/\S+@\S+\.\S+/.test(email)) { profileMessageDiv.textContent = "Email is not valid."; return; } profileMessageDiv.textContent = "Profile updated successfully!"; // You can proceed to update the user profile on the server here } Payment page(HTML) <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Payment</title> <link rel="stylesheet" href="styles.css"> </head> <body> <h1>Payment</h1> <form id="paymentForm"> <input type="text" id="cardNumber" placeholder="Card Number" required> <input type="text" id="expiryDate" placeholder="MM/YY" required> <input type="text" id="cvv" placeholder="CVV" required> <button type="submit">Pay</button> <div id="paymentMessage" class="error-message"></div> </form> <script src="script.js"></script> </body> </html> script.js document.getElementById("paymentForm").addEventListener("submit", function(event) { event.preventDefault(); // Prevent form submission validatePayment(); }); function validatePayment() { const cardNumber = document.getElementById("cardNumber").value; const expiryDate = document.getElementById("expiryDate").value; const cvv = document.getElementById("cvv").value; const paymentMessageDiv = document.getElementById("paymentMessage"); paymentMessageDiv.textContent = ""; // Simple validation if (!/^\d{16}$/.test(cardNumber)) { paymentMessageDiv.textContent = "Card number must be 16 digits."; return; } if (!/^(0[1-9]|1[0-2])\/\d{2}$/.test(expiryDate)) { paymentMessageDiv.textContent = "Expiry date must be in MM/YY format."; return; } if (!/^\d{3}$/.test(cvv)) { paymentMessageDiv.textContent = "CVV must be 3 digits."; return; } paymentMessageDiv.textContent = "Payment successful!"; // You can proceed to process the payment here } 4.Build a scientific calculator HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Scientific Calculator</title> <link rel="stylesheet" href="styles.css"> </head> <body> <div class="calculator"> <input type="text" id="display" disabled> <div class="buttons"> <button onclick="clearDisplay()">C</button> <button onclick="appendToDisplay('7')">7</button> <button onclick="appendToDisplay('8')">8</button> <button onclick="appendToDisplay('9')">9</button> <button onclick="appendToDisplay('/')">/</button> <button onclick="appendToDisplay('4')">4</button> <button onclick="appendToDisplay('5')">5</button> <button onclick="appendToDisplay('6')">6</button> <button onclick="appendToDisplay('*')">*</button> <button onclick="appendToDisplay('1')">1</button> <button onclick="appendToDisplay('2')">2</button> <button onclick="appendToDisplay('3')">3</button> <button onclick="appendToDisplay('-')">-</button> <button onclick="appendToDisplay('0')">0</button> <button onclick="appendToDisplay('.')">.</button> <button onclick="calculate()">=</button> <button onclick="appendToDisplay('+')">+</button> <button onclick="calculate('sqrt')">√</button> <button onclick="calculate('pow')">x²</button> <button onclick="calculate('sin')">sin</button> <button onclick="calculate('cos')">cos</button> <button onclick="calculate('tan')">tan</button> </div> </div> <script src="script.js"></script> </body> </html> CSS body { display: flex; justify-content: center; align-items: center; height: 100vh; background-color: #f4f4f4; font-family: Arial, sans-serif; } .calculator { background-color: white; border-radius: 10px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); padding: 20px; width: 300px; } #display { width: 100%; height: 40px; text-align: right; font-size: 24px; border: 1px solid #ccc; border-radius: 5px; margin-bottom: 10px; padding: 5px; } .buttons { display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px; } button { height: 40px; font-size: 18px; border: none; border-radius: 5px; background-color: #007bff; color: white; cursor: pointer; transition: background-color 0.3s; } button:hover { background-color: #0056b3; } script.js function appendToDisplay(value) { document.getElementById("display").value += value; } function clearDisplay() { document.getElementById("display").value = ""; } function calculate(operation) { const display = document.getElementById("display"); let result; try { if (operation === 'sqrt') { result = Math.sqrt(eval(display.value)); } else if (operation === 'pow') { result = Math.pow(eval(display.value), 2); } else if (['sin', 'cos', 'tan'].includes(operation)) { const angle = eval(display.value) * (Math.PI / 180); // Convert to radians result = Math[operation](angle); } else { result = eval(display.value); } display.value = result; } catch (error) { display.value = "Error!"; } } 5.Javascript program to demostrate working of prototypal inheritance ,closure,callbacks,promises and sync/await // Prototypal Inheritance function Animal(name) { this.name = name; } Animal.prototype.speak = function() { console.log(`${this.name} makes a noise.`); }; function Dog(name) { Animal.call(this, name); // Call the parent constructor } Dog.prototype = Object.create(Animal.prototype); Dog.prototype.constructor = Dog; Dog.prototype.speak = function() { console.log(`${this.name} barks.`); }; // Closure function createCounter() { let count = 0; // Private variable return { increment: function() { count++; return count; }, decrement: function() { count--; return count; }, getCount: function() { return count; } }; } // Callback function fetchData(callback) { setTimeout(() => { const data = { message: "Data fetched!" }; callback(data); }, 1000); } // Promise function fetchDataPromise() { return new Promise((resolve, reject) => { setTimeout(() => { const data = { message: "Data fetched with Promise!" }; resolve(data); }, 1000); }); } // Async/Await async function fetchDataAsync() { const data = await fetchDataPromise(); console.log(data.message); } // Demonstration function demo() { // Prototypal Inheritance const dog = new Dog('Buddy'); dog.speak(); // Output: Buddy barks. // Closure const counter = createCounter(); console.log(counter.increment()); // Output: 1 console.log(counter.increment()); // Output: 2 console.log(counter.decrement()); // Output: 1 console.log(counter.getCount()); // Output: 1 // Callback fetchData((data) => { console.log(data.message); // Output: Data fetched! }); // Promise fetchDataPromise().then((data) => { console.log(data.message); // Output: Data fetched with Promise! }); // Async/Await fetchDataAsync(); // Output: Data fetched with Promise! } // Run the demonstration demo(); 6.Write an xml file which will display the Book information with the following fields : Title of the book,Author name,ISBN number ,Publisher name,Edition,Price. <?xml version="1.0" encoding="UTF-8"?> <library> <book> <title>The Great Gatsby</title> <author>F. Scott Fitzgerald</author> <isbn>978-0743273565</isbn> <publisher>Scribner</publisher> <edition>1st</edition> <price>10.99</price> </book> <book> <title>To Kill a Mockingbird</title> <author>Harper Lee</author> <isbn>978-0061120084</isbn> <publisher>Harper Perennial Modern Classics</publisher> <edition>50th Anniversary Edition</edition> <price>7.19</price> </book> <book> <title>1984</title> <author>George Orwell</author> <isbn>978-0451524935</isbn> <publisher>Signet Classics</publisher> <edition>Anniversary Edition</edition> <price>9.99</price> </book> <book> <title>Moby Dick</title> <author>Herman Melville</author> <isbn>978-1503280786</isbn> <publisher>CreateSpace Independent Publishing Platform</publisher> <edition>1st</edition> <price>11.95</price> </book> <book> <title>Brave New World</title> <author>Aldous Huxley</author> <isbn>978-0060850524</isbn> <publisher>Harper Perennial Modern Classics</publisher> <edition>Reissue</edition> <price>14.99</price> </book> </library> 7.Define a Document Type Definition(DTD) and xml schema to validate the above created xml Documents books.dtd <!ELEMENT library (book+)> <!ELEMENT book (title, author, isbn, publisher, edition, price)> <!ELEMENT title (#PCDATA)> <!ELEMENT author (#PCDATA)> <!ELEMENT isbn (#PCDATA)> <!ELEMENT publisher (#PCDATA)> <!ELEMENT edition (#PCDATA)> <!ELEMENT price (#PCDATA)> books.xsd <?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="library"> <xs:complexType> <xs:sequence> <xs:element name="book" maxOccurs="unbounded"> <xs:complexType> <xs:sequence> <xs:element name="title" type="xs:string"/> <xs:element name="author" type="xs:string"/> <xs:element name="isbn" type="xs:string"/> <xs:element name="publisher" type="xs:string"/> <xs:element name="edition" type="xs:string"/> <xs:element name="price" type="xs:decimal"/> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> 8.8.write a java program to establish a connection to a database and execute simple SQL queries SQL use itb; create table students(name varchar(50),rollno int,branch varchar(20)); insert into students (name,rollno,branch) values ('niha',90,'it'), ('nishka',95,'it'), ('nishu',96,'it'); JAVA package jdbc; import java.sql.*; public class Simple_Connection { Connection conn = null; public static void main(String[] args) { // TODO Auto-generated method stub try { Class.forName("com.mysql.cj.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/itb","root","root"); Statement stmt = conn.createStatement(); ResultSet rs=stmt.executeQuery("Select * from students"); while(rs.next()){ System.out.println(rs.getString(1)+" "+rs.getInt(2)+" "+rs.getString(3)); } conn.close(); }catch(Exception e) { e.printStackTrace(); } } } 9.write a java program to demonstrate the usage of JDBC in performing various DML statements .Use prepared statements and callable statements SQL CREATE DATABASE sampledb; USE sampledb; CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100), email VARCHAR(100) ); JAVA import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.CallableStatement; import java.sql.ResultSet; public class JdbcDmlExample { private static final String URL = "jdbc:mysql://localhost:3306/sampledb"; private static final String USERNAME = "your_username"; // Replace with your DB username private static final String PASSWORD = "your_password"; // Replace with your DB password public static void main(String[] args) { Connection connection = null; try { // Establishing the connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD); System.out.println("Connected to the database successfully."); // Inserting data using PreparedStatement insertUser(connection, "Alice Johnson", "alice@example.com"); insertUser(connection, "Bob Smith", "bob@example.com"); // Updating data using PreparedStatement updateUserEmail(connection, 1, "alice.new@example.com"); // Calling stored procedure using CallableStatement callUserCountProcedure(connection); } catch (SQLException e) { System.err.println("SQL Exception: " + e.getMessage()); } finally { // Closing the connection try { if (connection != null && !connection.isClosed()) { connection.close(); System.out.println("Database connection closed."); } } catch (SQLException e) { System.err.println("Failed to close the connection: " + e.getMessage()); } } } // Method to insert user using PreparedStatement private static void insertUser(Connection connection, String name, String email) throws SQLException { String insertSQL = "INSERT INTO users (name, email) VALUES (?, ?)"; try (PreparedStatement pstmt = connection.prepareStatement(insertSQL)) { pstmt.setString(1, name); pstmt.setString(2, email); int rowsAffected = pstmt.executeUpdate(); System.out.println(rowsAffected + " user(s) inserted."); } } // Method to update user email using PreparedStatement private static void updateUserEmail(Connection connection, int userId, String newEmail) throws SQLException { String updateSQL = "UPDATE users SET email = ? WHERE id = ?"; try (PreparedStatement pstmt = connection.prepareStatement(updateSQL)) { pstmt.setString(1, newEmail); pstmt.setInt(2, userId); int rowsAffected = pstmt.executeUpdate(); System.out.println(rowsAffected + " user(s) updated."); } } // Method to call a stored procedure using CallableStatement private static void callUserCountProcedure(Connection connection) throws SQLException { // Assuming there is a stored procedure named `GetUserCount` that returns the count of users String procedureCall = "{ CALL GetUserCount() }"; try (CallableStatement cstmt = connection.prepareCall(procedureCall)) { try (ResultSet rs = cstmt.executeQuery()) { if (rs.next()) { int userCount = rs.getInt(1); System.out.println("Total users: " + userCount); } } } } } 10.write a java based application to demonstrate the Updatable and Scrollable resultsets SQL CREATE DATABASE sampledb; USE sampledb; CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100), email VARCHAR(100) ); JAVA import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.PreparedStatement; public class UpdatableScrollableResultSetExample { private static final String URL = "jdbc:mysql://localhost:3306/sampledb"; private static final String USERNAME = "your_username"; // Replace with your DB username private static final String PASSWORD = "your_password"; // Replace with your DB password public static void main(String[] args) { Connection connection = null; try { // Establishing the connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD); System.out.println("Connected to the database successfully."); // Inserting some sample data insertSampleData(connection); // Using Updatable and Scrollable ResultSet try (Statement stmt = connection.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE)) { String query = "SELECT * FROM users"; ResultSet rs = stmt.executeQuery(query); // Moving to the last record if (rs.last()) { System.out.println("Last Record: ID: " + rs.getInt("id") + ", Name: " + rs.getString("name") + ", Email: " + rs.getString("email")); } // Moving to the first record if (rs.first()) { System.out.println("First Record: ID: " + rs.getInt("id") + ", Name: " + rs.getString("name") + ", Email: " + rs.getString("email")); } // Updating the first record if (rs.first()) { System.out.println("Updating record..."); rs.updateString("name", "Updated Name"); rs.updateRow(); System.out.println("Record updated."); } // Displaying updated records System.out.println("Updated Records:"); rs.beforeFirst(); // Move cursor to before the first record while (rs.next()) { System.out.println("ID: " + rs.getInt("id") + ", Name: " + rs.getString("name") + ", Email: " + rs.getString("email")); } } } catch (SQLException e) { System.err.println("SQL Exception: " + e.getMessage()); } finally { // Closing the connection try { if (connection != null && !connection.isClosed()) { connection.close(); System.out.println("Database connection closed."); } } catch (SQLException e) { System.err.println("Failed to close the connection: " + e.getMessage()); } } } // Method to insert sample data into the users table private static void insertSampleData(Connection connection) throws SQLException { String insertSQL = "INSERT INTO users (name, email) VALUES (?, ?)"; try (PreparedStatement pstmt = connection.prepareStatement(insertSQL)) { pstmt.setString(1, "John Doe"); pstmt.setString(2, "john@example.com"); pstmt.executeUpdate(); pstmt.setString(1, "Jane Smith"); pstmt.setString(2, "jane@example.com"); pstmt.executeUpdate(); System.out.println("Sample data inserted into users table."); } } } 11.write a java program to access metadata of the SQL database import java.sql.Connection; import java.sql.DriverManager; import java.sql.DatabaseMetaData; import java.sql.ResultSet; import java.sql.SQLException; public class DatabaseMetadataExample { private static final String URL = "jdbc:mysql://localhost:3306/sampledb"; // Replace with your DB URL private static final String USERNAME = "your_username"; // Replace with your DB username private static final String PASSWORD = "your_password"; // Replace with your DB password public static void main(String[] args) { Connection connection = null; try { // Establishing the connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD); System.out.println("Connected to the database successfully."); // Accessing database metadata DatabaseMetaData metaData = connection.getMetaData(); // Retrieve and display basic information System.out.println("Database Product Name: " + metaData.getDatabaseProductName()); System.out.println("Database Product Version: " + metaData.getDatabaseProductVersion()); System.out.println("Driver Name: " + metaData.getDriverName()); System.out.println("Driver Version: " + metaData.getDriverVersion()); System.out.println("SQL Syntax: " + metaData.getSQLKeywords()); // Get and display the tables System.out.println("\nTables in the database:"); ResultSet tables = metaData.getTables(null, null, "%", new String[]{"TABLE"}); while (tables.next()) { String tableName = tables.getString("TABLE_NAME"); System.out.println("Table: " + tableName); // Get and display columns for each table ResultSet columns = metaData.getColumns(null, null, tableName, null); System.out.println(" Columns in " + tableName + ":"); while (columns.next()) { String columnName = columns.getString("COLUMN_NAME"); String columnType = columns.getString("TYPE_NAME"); int columnSize = columns.getInt("COLUMN_SIZE"); System.out.printf(" %s (%s, Size: %d)%n", columnName, columnType, columnSize); } } } catch (SQLException e) { System.err.println("SQL Exception: " + e.getMessage()); } finally { // Closing the connection try { if (connection != null && !connection.isClosed()) { connection.close(); System.out.println("Database connection closed."); } } catch (SQLException e) { System.err.println("Failed to close the connection: " + e.getMessage()); } } } } 12. write a java program to accept request parameters a form and generate the response HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>User Form</title> </head> <body> <h1>User Information Form</h1> <form action="ResponseServlet" method="POST"> <label for="name">Name:</label><br> <input type="text" id="name" name="name" required><br> <label for="email">Email:</label><br> <input type="email" id="email" name="email" required><br> <input type="submit" value="Submit"> </form> </body> </html> ResponseServlet.java import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/ResponseServlet") public class ResponseServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set the response content type response.setContentType("text/html"); // Get the parameters from the request String name = request.getParameter("name"); String email = request.getParameter("email"); // Generate the response PrintWriter out = response.getWriter(); out.println("<html><body>"); out.println("<h2>User Information</h2>"); out.println("<p>Name: " + name + "</p>"); out.println("<p>Email: " + email + "</p>"); out.println("</body></html>"); } } 13.write a program to accept ServletConfig and ServletContext parameters import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/ConfigServlet") public class ConfigServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set the response content type response.setContentType("text/html"); // Get ServletConfig and ServletContext ServletConfig config = getServletConfig(); ServletContext context = getServletContext(); // Get parameters from ServletConfig String servletParam = config.getInitParameter("servletParam"); // Get parameters from ServletContext String contextParam = context.getInitParameter("contextParam"); // Generate the response PrintWriter out = response.getWriter(); out.println("<html><body>"); out.println("<h2>Servlet Config and Context Parameters</h2>"); out.println("<p>Servlet Parameter: " + servletParam + "</p>"); out.println("<p>Context Parameter: " + contextParam + "</p>"); out.println("</body></html>"); } }
1.create a web page using the advanced features of css:Grid,Flexbox.And apply transition and animations on the contents of the webpage HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>CSS Grid and Flexbox Example</title> <link rel="stylesheet" href="styles.css"> </head> <body> <header class="header"> <h1>My Awesome Web Page</h1> </header> <main class="main-content"> <section class="grid-container"> <div class="grid-item">Item 1</div> <div class="grid-item">Item 2</div> <div class="grid-item">Item 3</div> <div class="grid-item">Item 4</div> <div class="grid-item">Item 5</div> </section> </main> <footer class="footer"> <p>Footer Content</p> </footer> </body> </html> CSS * { box-sizing: border-box; margin: 0; padding: 0; } body { font-family: Arial, sans-serif; display: flex; flex-direction: column; height: 100vh; } .header { background-color: #4CAF50; color: white; text-align: center; padding: 20px; } .main-content { flex: 1; display: flex; justify-content: center; align-items: center; background-color: #f4f4f4; } .grid-container { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 15px; padding: 20px; } .grid-item { background-color: #ffcc00; padding: 20px; border-radius: 5px; text-align: center; transition: transform 0.3s ease, background-color 0.3s ease; } .grid-item:hover { transform: scale(1.1); background-color: #ffd700; } .footer { background-color: #333; color: white; text-align: center; padding: 10px; } @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } } .header, .footer { animation: fadeIn 1s ease-in; } 2.make the webpages created in the above experiment as responsive web page with Bootstrap Framework HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Responsive Web Page with Bootstrap</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <link rel="stylesheet" href="styles.css"> </head> <body> <header class="bg-success text-white text-center py-4"> <h1>My Awesome Web Page</h1> </header> <main class="container my-5"> <section class="row"> <div class="col-lg-4 col-md-6 mb-4"> <div class="card grid-item"> <div class="card-body"> <h5 class="card-title">Item 1</h5> </div> </div> </div> <div class="col-lg-4 col-md-6 mb-4"> <div class="card grid-item"> <div class="card-body"> <h5 class="card-title">Item 2</h5> </div> </div> </div> <div class="col-lg-4 col-md-6 mb-4"> <div class="card grid-item"> <div class="card-body"> <h5 class="card-title">Item 3</h5> </div> </div> </div> <div class="col-lg-4 col-md-6 mb-4"> <div class="card grid-item"> <div class="card-body"> <h5 class="card-title">Item 4</h5> </div> </div> </div> <div class="col-lg-4 col-md-6 mb-4"> <div class="card grid-item"> <div class="card-body"> <h5 class="card-title">Item 5</h5> </div> </div> </div> </section> </main> <footer class="bg-dark text-white text-center py-3"> <p>Footer Content</p> </footer> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script> </body> </html> CSS .grid-item { background-color: #ffcc00; transition: transform 0.3s ease, background-color 0.3s ease; } .grid-item:hover { transform: scale(1.05); background-color: #ffd700; } 3.Validate the registration ,user login,user profile and payment pages using javascript .Make use of any needed javascrpt objects HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Registration</title> <link rel="stylesheet" href="styles.css"> </head> <body> <h1>Register</h1> <form id="registrationForm"> <input type="text" id="username" placeholder="Username" required> <input type="email" id="email" placeholder="Email" required> <input type="password" id="password" placeholder="Password" required> <button type="submit">Register</button> <div id="message" class="error-message"></div> </form> <script src="script.js"></script> </body> </html> script.js document.getElementById("registrationForm").addEventListener("submit", function(event) { event.preventDefault(); // Prevent form submission validateRegistration(); }); function validateRegistration() { const username = document.getElementById("username").value; const email = document.getElementById("email").value; const password = document.getElementById("password").value; const messageDiv = document.getElementById("message"); messageDiv.textContent = ""; // Simple validation if (username.length < 3) { messageDiv.textContent = "Username must be at least 3 characters."; return; } if (!/\S+@\S+\.\S+/.test(email)) { messageDiv.textContent = "Email is not valid."; return; } if (password.length < 6) { messageDiv.textContent = "Password must be at least 6 characters."; return; } messageDiv.textContent = "Registration successful!"; // You can proceed to send the data to the server here } User Login Page(HTML) <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Login</title> <link rel="stylesheet" href="styles.css"> </head> <body> <h1>Login</h1> <form id="loginForm"> <input type="email" id="loginEmail" placeholder="Email" required> <input type="password" id="loginPassword" placeholder="Password" required> <button type="submit">Login</button> <div id="loginMessage" class="error-message"></div> </form> <script src="script.js"></script> </body> </html> script.js document.getElementById("loginForm").addEventListener("submit", function(event) { event.preventDefault(); // Prevent form submission validateLogin(); }); function validateLogin() { const email = document.getElementById("loginEmail").value; const password = document.getElementById("loginPassword").value; const loginMessageDiv = document.getElementById("loginMessage"); loginMessageDiv.textContent = ""; // Simple validation if (!/\S+@\S+\.\S+/.test(email)) { loginMessageDiv.textContent = "Email is not valid."; return; } if (password.length < 6) { loginMessageDiv.textContent = "Password must be at least 6 characters."; return; } loginMessageDiv.textContent = "Login successful!"; // You can proceed to authenticate the user here } User Profile Page(HTML) <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>User Profile</title> <link rel="stylesheet" href="styles.css"> </head> <body> <h1>User Profile</h1> <form id="profileForm"> <input type="text" id="profileUsername" placeholder="Username" required> <input type="email" id="profileEmail" placeholder="Email" required> <button type="submit">Update Profile</button> <div id="profileMessage" class="error-message"></div> </form> <script src="script.js"></script> </body> </html> script.js document.getElementById("profileForm").addEventListener("submit", function(event) { event.preventDefault(); // Prevent form submission validateProfile(); }); function validateProfile() { const username = document.getElementById("profileUsername").value; const email = document.getElementById("profileEmail").value; const profileMessageDiv = document.getElementById("profileMessage"); profileMessageDiv.textContent = ""; // Simple validation if (username.length < 3) { profileMessageDiv.textContent = "Username must be at least 3 characters."; return; } if (!/\S+@\S+\.\S+/.test(email)) { profileMessageDiv.textContent = "Email is not valid."; return; } profileMessageDiv.textContent = "Profile updated successfully!"; // You can proceed to update the user profile on the server here } Payment page(HTML) <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Payment</title> <link rel="stylesheet" href="styles.css"> </head> <body> <h1>Payment</h1> <form id="paymentForm"> <input type="text" id="cardNumber" placeholder="Card Number" required> <input type="text" id="expiryDate" placeholder="MM/YY" required> <input type="text" id="cvv" placeholder="CVV" required> <button type="submit">Pay</button> <div id="paymentMessage" class="error-message"></div> </form> <script src="script.js"></script> </body> </html> script.js document.getElementById("paymentForm").addEventListener("submit", function(event) { event.preventDefault(); // Prevent form submission validatePayment(); }); function validatePayment() { const cardNumber = document.getElementById("cardNumber").value; const expiryDate = document.getElementById("expiryDate").value; const cvv = document.getElementById("cvv").value; const paymentMessageDiv = document.getElementById("paymentMessage"); paymentMessageDiv.textContent = ""; // Simple validation if (!/^\d{16}$/.test(cardNumber)) { paymentMessageDiv.textContent = "Card number must be 16 digits."; return; } if (!/^(0[1-9]|1[0-2])\/\d{2}$/.test(expiryDate)) { paymentMessageDiv.textContent = "Expiry date must be in MM/YY format."; return; } if (!/^\d{3}$/.test(cvv)) { paymentMessageDiv.textContent = "CVV must be 3 digits."; return; } paymentMessageDiv.textContent = "Payment successful!"; // You can proceed to process the payment here } 4.Build a scientific calculator HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Scientific Calculator</title> <link rel="stylesheet" href="styles.css"> </head> <body> <div class="calculator"> <input type="text" id="display" disabled> <div class="buttons"> <button onclick="clearDisplay()">C</button> <button onclick="appendToDisplay('7')">7</button> <button onclick="appendToDisplay('8')">8</button> <button onclick="appendToDisplay('9')">9</button> <button onclick="appendToDisplay('/')">/</button> <button onclick="appendToDisplay('4')">4</button> <button onclick="appendToDisplay('5')">5</button> <button onclick="appendToDisplay('6')">6</button> <button onclick="appendToDisplay('*')">*</button> <button onclick="appendToDisplay('1')">1</button> <button onclick="appendToDisplay('2')">2</button> <button onclick="appendToDisplay('3')">3</button> <button onclick="appendToDisplay('-')">-</button> <button onclick="appendToDisplay('0')">0</button> <button onclick="appendToDisplay('.')">.</button> <button onclick="calculate()">=</button> <button onclick="appendToDisplay('+')">+</button> <button onclick="calculate('sqrt')">√</button> <button onclick="calculate('pow')">x²</button> <button onclick="calculate('sin')">sin</button> <button onclick="calculate('cos')">cos</button> <button onclick="calculate('tan')">tan</button> </div> </div> <script src="script.js"></script> </body> </html> CSS body { display: flex; justify-content: center; align-items: center; height: 100vh; background-color: #f4f4f4; font-family: Arial, sans-serif; } .calculator { background-color: white; border-radius: 10px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); padding: 20px; width: 300px; } #display { width: 100%; height: 40px; text-align: right; font-size: 24px; border: 1px solid #ccc; border-radius: 5px; margin-bottom: 10px; padding: 5px; } .buttons { display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px; } button { height: 40px; font-size: 18px; border: none; border-radius: 5px; background-color: #007bff; color: white; cursor: pointer; transition: background-color 0.3s; } button:hover { background-color: #0056b3; } script.js function appendToDisplay(value) { document.getElementById("display").value += value; } function clearDisplay() { document.getElementById("display").value = ""; } function calculate(operation) { const display = document.getElementById("display"); let result; try { if (operation === 'sqrt') { result = Math.sqrt(eval(display.value)); } else if (operation === 'pow') { result = Math.pow(eval(display.value), 2); } else if (['sin', 'cos', 'tan'].includes(operation)) { const angle = eval(display.value) * (Math.PI / 180); // Convert to radians result = Math[operation](angle); } else { result = eval(display.value); } display.value = result; } catch (error) { display.value = "Error!"; } } 5.Javascript program to demostrate working of prototypal inheritance ,closure,callbacks,promises and sync/await // Prototypal Inheritance function Animal(name) { this.name = name; } Animal.prototype.speak = function() { console.log(`${this.name} makes a noise.`); }; function Dog(name) { Animal.call(this, name); // Call the parent constructor } Dog.prototype = Object.create(Animal.prototype); Dog.prototype.constructor = Dog; Dog.prototype.speak = function() { console.log(`${this.name} barks.`); }; // Closure function createCounter() { let count = 0; // Private variable return { increment: function() { count++; return count; }, decrement: function() { count--; return count; }, getCount: function() { return count; } }; } // Callback function fetchData(callback) { setTimeout(() => { const data = { message: "Data fetched!" }; callback(data); }, 1000); } // Promise function fetchDataPromise() { return new Promise((resolve, reject) => { setTimeout(() => { const data = { message: "Data fetched with Promise!" }; resolve(data); }, 1000); }); } // Async/Await async function fetchDataAsync() { const data = await fetchDataPromise(); console.log(data.message); } // Demonstration function demo() { // Prototypal Inheritance const dog = new Dog('Buddy'); dog.speak(); // Output: Buddy barks. // Closure const counter = createCounter(); console.log(counter.increment()); // Output: 1 console.log(counter.increment()); // Output: 2 console.log(counter.decrement()); // Output: 1 console.log(counter.getCount()); // Output: 1 // Callback fetchData((data) => { console.log(data.message); // Output: Data fetched! }); // Promise fetchDataPromise().then((data) => { console.log(data.message); // Output: Data fetched with Promise! }); // Async/Await fetchDataAsync(); // Output: Data fetched with Promise! } // Run the demonstration demo(); 6.Write an xml file which will display the Book information with the following fields : Title of the book,Author name,ISBN number ,Publisher name,Edition,Price. <?xml version="1.0" encoding="UTF-8"?> <library> <book> <title>The Great Gatsby</title> <author>F. Scott Fitzgerald</author> <isbn>978-0743273565</isbn> <publisher>Scribner</publisher> <edition>1st</edition> <price>10.99</price> </book> <book> <title>To Kill a Mockingbird</title> <author>Harper Lee</author> <isbn>978-0061120084</isbn> <publisher>Harper Perennial Modern Classics</publisher> <edition>50th Anniversary Edition</edition> <price>7.19</price> </book> <book> <title>1984</title> <author>George Orwell</author> <isbn>978-0451524935</isbn> <publisher>Signet Classics</publisher> <edition>Anniversary Edition</edition> <price>9.99</price> </book> <book> <title>Moby Dick</title> <author>Herman Melville</author> <isbn>978-1503280786</isbn> <publisher>CreateSpace Independent Publishing Platform</publisher> <edition>1st</edition> <price>11.95</price> </book> <book> <title>Brave New World</title> <author>Aldous Huxley</author> <isbn>978-0060850524</isbn> <publisher>Harper Perennial Modern Classics</publisher> <edition>Reissue</edition> <price>14.99</price> </book> </library> 7.Define a Document Type Definition(DTD) and xml schema to validate the above created xml Documents books.dtd <!ELEMENT library (book+)> <!ELEMENT book (title, author, isbn, publisher, edition, price)> <!ELEMENT title (#PCDATA)> <!ELEMENT author (#PCDATA)> <!ELEMENT isbn (#PCDATA)> <!ELEMENT publisher (#PCDATA)> <!ELEMENT edition (#PCDATA)> <!ELEMENT price (#PCDATA)> books.xsd <?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="library"> <xs:complexType> <xs:sequence> <xs:element name="book" maxOccurs="unbounded"> <xs:complexType> <xs:sequence> <xs:element name="title" type="xs:string"/> <xs:element name="author" type="xs:string"/> <xs:element name="isbn" type="xs:string"/> <xs:element name="publisher" type="xs:string"/> <xs:element name="edition" type="xs:string"/> <xs:element name="price" type="xs:decimal"/> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> 8.8.write a java program to establish a connection to a database and execute simple SQL queries SQL use itb; create table students(name varchar(50),rollno int,branch varchar(20)); insert into students (name,rollno,branch) values ('niha',90,'it'), ('nishka',95,'it'), ('nishu',96,'it'); JAVA package jdbc; import java.sql.*; public class Simple_Connection { Connection conn = null; public static void main(String[] args) { // TODO Auto-generated method stub try { Class.forName("com.mysql.cj.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/itb","root","root"); Statement stmt = conn.createStatement(); ResultSet rs=stmt.executeQuery("Select * from students"); while(rs.next()){ System.out.println(rs.getString(1)+" "+rs.getInt(2)+" "+rs.getString(3)); } conn.close(); }catch(Exception e) { e.printStackTrace(); } } } 9.write a java program to demonstrate the usage of JDBC in performing various DML statements .Use prepared statements and callable statements SQL CREATE DATABASE sampledb; USE sampledb; CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100), email VARCHAR(100) ); JAVA import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.CallableStatement; import java.sql.ResultSet; public class JdbcDmlExample { private static final String URL = "jdbc:mysql://localhost:3306/sampledb"; private static final String USERNAME = "your_username"; // Replace with your DB username private static final String PASSWORD = "your_password"; // Replace with your DB password public static void main(String[] args) { Connection connection = null; try { // Establishing the connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD); System.out.println("Connected to the database successfully."); // Inserting data using PreparedStatement insertUser(connection, "Alice Johnson", "alice@example.com"); insertUser(connection, "Bob Smith", "bob@example.com"); // Updating data using PreparedStatement updateUserEmail(connection, 1, "alice.new@example.com"); // Calling stored procedure using CallableStatement callUserCountProcedure(connection); } catch (SQLException e) { System.err.println("SQL Exception: " + e.getMessage()); } finally { // Closing the connection try { if (connection != null && !connection.isClosed()) { connection.close(); System.out.println("Database connection closed."); } } catch (SQLException e) { System.err.println("Failed to close the connection: " + e.getMessage()); } } } // Method to insert user using PreparedStatement private static void insertUser(Connection connection, String name, String email) throws SQLException { String insertSQL = "INSERT INTO users (name, email) VALUES (?, ?)"; try (PreparedStatement pstmt = connection.prepareStatement(insertSQL)) { pstmt.setString(1, name); pstmt.setString(2, email); int rowsAffected = pstmt.executeUpdate(); System.out.println(rowsAffected + " user(s) inserted."); } } // Method to update user email using PreparedStatement private static void updateUserEmail(Connection connection, int userId, String newEmail) throws SQLException { String updateSQL = "UPDATE users SET email = ? WHERE id = ?"; try (PreparedStatement pstmt = connection.prepareStatement(updateSQL)) { pstmt.setString(1, newEmail); pstmt.setInt(2, userId); int rowsAffected = pstmt.executeUpdate(); System.out.println(rowsAffected + " user(s) updated."); } } // Method to call a stored procedure using CallableStatement private static void callUserCountProcedure(Connection connection) throws SQLException { // Assuming there is a stored procedure named `GetUserCount` that returns the count of users String procedureCall = "{ CALL GetUserCount() }"; try (CallableStatement cstmt = connection.prepareCall(procedureCall)) { try (ResultSet rs = cstmt.executeQuery()) { if (rs.next()) { int userCount = rs.getInt(1); System.out.println("Total users: " + userCount); } } } } } 10.write a java based application to demonstrate the Updatable and Scrollable resultsets SQL CREATE DATABASE sampledb; USE sampledb; CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100), email VARCHAR(100) ); JAVA import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.PreparedStatement; public class UpdatableScrollableResultSetExample { private static final String URL = "jdbc:mysql://localhost:3306/sampledb"; private static final String USERNAME = "your_username"; // Replace with your DB username private static final String PASSWORD = "your_password"; // Replace with your DB password public static void main(String[] args) { Connection connection = null; try { // Establishing the connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD); System.out.println("Connected to the database successfully."); // Inserting some sample data insertSampleData(connection); // Using Updatable and Scrollable ResultSet try (Statement stmt = connection.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE)) { String query = "SELECT * FROM users"; ResultSet rs = stmt.executeQuery(query); // Moving to the last record if (rs.last()) { System.out.println("Last Record: ID: " + rs.getInt("id") + ", Name: " + rs.getString("name") + ", Email: " + rs.getString("email")); } // Moving to the first record if (rs.first()) { System.out.println("First Record: ID: " + rs.getInt("id") + ", Name: " + rs.getString("name") + ", Email: " + rs.getString("email")); } // Updating the first record if (rs.first()) { System.out.println("Updating record..."); rs.updateString("name", "Updated Name"); rs.updateRow(); System.out.println("Record updated."); } // Displaying updated records System.out.println("Updated Records:"); rs.beforeFirst(); // Move cursor to before the first record while (rs.next()) { System.out.println("ID: " + rs.getInt("id") + ", Name: " + rs.getString("name") + ", Email: " + rs.getString("email")); } } } catch (SQLException e) { System.err.println("SQL Exception: " + e.getMessage()); } finally { // Closing the connection try { if (connection != null && !connection.isClosed()) { connection.close(); System.out.println("Database connection closed."); } } catch (SQLException e) { System.err.println("Failed to close the connection: " + e.getMessage()); } } } // Method to insert sample data into the users table private static void insertSampleData(Connection connection) throws SQLException { String insertSQL = "INSERT INTO users (name, email) VALUES (?, ?)"; try (PreparedStatement pstmt = connection.prepareStatement(insertSQL)) { pstmt.setString(1, "John Doe"); pstmt.setString(2, "john@example.com"); pstmt.executeUpdate(); pstmt.setString(1, "Jane Smith"); pstmt.setString(2, "jane@example.com"); pstmt.executeUpdate(); System.out.println("Sample data inserted into users table."); } } } 11.write a java program to access metadata of the SQL database import java.sql.Connection; import java.sql.DriverManager; import java.sql.DatabaseMetaData; import java.sql.ResultSet; import java.sql.SQLException; public class DatabaseMetadataExample { private static final String URL = "jdbc:mysql://localhost:3306/sampledb"; // Replace with your DB URL private static final String USERNAME = "your_username"; // Replace with your DB username private static final String PASSWORD = "your_password"; // Replace with your DB password public static void main(String[] args) { Connection connection = null; try { // Establishing the connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD); System.out.println("Connected to the database successfully."); // Accessing database metadata DatabaseMetaData metaData = connection.getMetaData(); // Retrieve and display basic information System.out.println("Database Product Name: " + metaData.getDatabaseProductName()); System.out.println("Database Product Version: " + metaData.getDatabaseProductVersion()); System.out.println("Driver Name: " + metaData.getDriverName()); System.out.println("Driver Version: " + metaData.getDriverVersion()); System.out.println("SQL Syntax: " + metaData.getSQLKeywords()); // Get and display the tables System.out.println("\nTables in the database:"); ResultSet tables = metaData.getTables(null, null, "%", new String[]{"TABLE"}); while (tables.next()) { String tableName = tables.getString("TABLE_NAME"); System.out.println("Table: " + tableName); // Get and display columns for each table ResultSet columns = metaData.getColumns(null, null, tableName, null); System.out.println(" Columns in " + tableName + ":"); while (columns.next()) { String columnName = columns.getString("COLUMN_NAME"); String columnType = columns.getString("TYPE_NAME"); int columnSize = columns.getInt("COLUMN_SIZE"); System.out.printf(" %s (%s, Size: %d)%n", columnName, columnType, columnSize); } } } catch (SQLException e) { System.err.println("SQL Exception: " + e.getMessage()); } finally { // Closing the connection try { if (connection != null && !connection.isClosed()) { connection.close(); System.out.println("Database connection closed."); } } catch (SQLException e) { System.err.println("Failed to close the connection: " + e.getMessage()); } } } } 12. write a java program to accept request parameters a form and generate the response HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>User Form</title> </head> <body> <h1>User Information Form</h1> <form action="ResponseServlet" method="POST"> <label for="name">Name:</label><br> <input type="text" id="name" name="name" required><br> <label for="email">Email:</label><br> <input type="email" id="email" name="email" required><br> <input type="submit" value="Submit"> </form> </body> </html> ResponseServlet.java import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/ResponseServlet") public class ResponseServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set the response content type response.setContentType("text/html"); // Get the parameters from the request String name = request.getParameter("name"); String email = request.getParameter("email"); // Generate the response PrintWriter out = response.getWriter(); out.println("<html><body>"); out.println("<h2>User Information</h2>"); out.println("<p>Name: " + name + "</p>"); out.println("<p>Email: " + email + "</p>"); out.println("</body></html>"); } } 13.write a program to accept ServletConfig and ServletContext parameters import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/ConfigServlet") public class ConfigServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set the response content type response.setContentType("text/html"); // Get ServletConfig and ServletContext ServletConfig config = getServletConfig(); ServletContext context = getServletContext(); // Get parameters from ServletConfig String servletParam = config.getInitParameter("servletParam"); // Get parameters from ServletContext String contextParam = context.getInitParameter("contextParam"); // Generate the response PrintWriter out = response.getWriter(); out.println("<html><body>"); out.println("<h2>Servlet Config and Context Parameters</h2>"); out.println("<p>Servlet Parameter: " + servletParam + "</p>"); out.println("<p>Context Parameter: " + contextParam + "</p>"); out.println("</body></html>"); } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Stylish Page</title> <link rel="stylesheet" href="styles.css"> </head> <body> <header class="header"> <h1>Welcome to My Stylish Page</h1> <p>Experience CSS Grid, Flexbox, and Animations!</p> </header> <main class="container"> <section class="content"> <div class="card">Card 1</div> <div class="card">Card 2</div> <div class="card">Card 3</div> <div class="card">Card 4</div> </section> <aside class="sidebar"> <h2>Sidebar</h2> <p>This is the sidebar content.</p> </aside> </main> <footer class="footer"> <p>© 2024 My Stylish Page</p> </footer> </body> </html> * { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: Arial, sans-serif; color: #333; } .container { display: grid; grid-template-columns: 3fr 1fr; gap: 20px; padding: 20px; } .header, .footer { text-align: center; background-color: #333; color: #fff; padding: 20px; } .content { display: flex; gap: 20px; flex-wrap: wrap; } .card { flex: 1 1 calc(50% - 20px); background: #4CAF50; color: #fff; padding: 20px; border-radius: 10px; text-align: center; transition: transform 0.3s, background 0.3s; cursor: pointer; } .card:hover { transform: scale(1.05); background: #45a049; } .sidebar { background: #f4f4f4; padding: 20px; border-radius: 10px; } @keyframes fadeIn { from { opacity: 0; transform: translateY(-10px); } to { opacity: 1; transform: translateY(0); } } .header h1, .content .card { animation: fadeIn 1s ease-in-out; } .content .card { animation-delay: 0.5s; animation-fill-mode: backwards; }
import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.Button import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.navigation.NavController import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import com.example.prog2.ui.theme.Prog2Theme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() setContent { val nav_Controller = rememberNavController() NavHost(navController = nav_Controller, startDestination = "fragment1") { composable("fragment1") { Fragment1(nav_Controller) } composable("fragment2") { Fragment2(nav_Controller) } } } } } @Composable fun Fragment1(navController: NavController){ Column { Button(onClick={ navController.navigate("fragment2")}) { Text(text = "Navigate to fragment2 ") } } } @Composable fun Fragment2(navController: NavController) { Row(horizontalArrangement = Arrangement.SpaceEvenly){ Button(onClick = { navController.navigateUp() }) { Text(text = "Back to Fragment 1") } } }
/////////*********** LOOPS FOR ARRAYS IN JS //////////////// // for of const arr = [1,3,3,4,5] for(const n of arr){ // n is just a variable in which array elements is stored console.log(n); // OUTPUT = 1 3 3 4 5 } const greet = "hello world" for(const greetings of greet){ // greetings is just a variable in which array elements is stored console.log(`the value of greet ${greetings}`); } /// Maps (always take different values means no repetation and always print in the order they re saved ) maps are not itterable too const map = new Map(); map.set('IN', "INDIA"); map.set('FR', "FRANCE"); map.set('US', "UNITED STATES OF AMERICA"); console.log(map); for(const[key,value] of map){ console.log(key,":->",value) }// OUTPUT = IN :-> INDIA FR :-> FRANCE US :-> UNITED STATES OF AMERICA
// MainActivity.kt package com.example.dbtest import android.os.Bundle import android.widget.Toast import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.* import androidx.compose.material3.Button import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Text import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.room.* import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext // Room Database-related code (User entity, DAO, and Database class) // User data class representing the database table @Entity(tableName = "users") data class User( @PrimaryKey(autoGenerate = true) val uid: Int = 0, val username: String, val phone: String ) // DAO interface for database operations @Dao interface UserDAO { @Insert suspend fun insert(user: User) } // Room Database class @Database(entities = [User::class], version = 1) abstract class UserDatabase : RoomDatabase() { abstract fun userDao(): UserDAO companion object { @Volatile private var INSTANCE: UserDatabase? = null fun getInstance(context: android.content.Context): UserDatabase { return INSTANCE ?: synchronized(this) { val instance = Room.databaseBuilder( context.applicationContext, UserDatabase::class.java, "user_database" ).build() INSTANCE = instance instance } } } } // Main Activity to set up the content and provide the database instance class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val database = UserDatabase.getInstance(this) setContent { InsertRecord(database) } } } // Composable function for inserting user data @Composable fun InsertRecord(database: UserDatabase) { val context = LocalContext.current val userDao = database.userDao() var name by remember { mutableStateOf("") } var phone by remember { mutableStateOf("") } val scope = rememberCoroutineScope() Column( modifier = Modifier .fillMaxSize() .padding(16.dp) ) { Text(text = "Enter your details here") Spacer(modifier = Modifier.height(25.dp)) OutlinedTextField( value = name, onValueChange = { name = it }, label = { Text(text = "Enter your name") }, modifier = Modifier.fillMaxWidth() ) Spacer(modifier = Modifier.height(25.dp)) OutlinedTextField( value = phone, onValueChange = { phone = it }, label = { Text(text = "Enter your phone number") }, modifier = Modifier.fillMaxWidth() ) Spacer(modifier = Modifier.height(25.dp)) Button(onClick = { scope.launch(Dispatchers.IO) { // Insert user data in the database userDao.insert(User(username = name, phone = phone)) // Display Toast on the main thread withContext(Dispatchers.Main) { Toast.makeText(context, "Record Inserted Successfully", Toast.LENGTH_LONG).show() } } }) { Text(text = "Insert Now") } } } //Plugins //kotlin("kapt") //Dependencies //val room_version = "2.6.1" // implementation("androidx.room:room-runtime:$room_version") // kapt("androidx.room:room-compiler:$room_version") // implementation("androidx.room:room-ktx:$room_version")
show databases; +--------------------+ | Database | +--------------------+ | information_schema | | mysql | | performance_schema | | test | +--------------------+ 4 rows in set (0.01 sec) mysql> create database varshitha; Query OK, 1 row affected (0.02 sec) mysql> show databases; +--------------------+ | Database | +--------------------+ | information_schema | | mysql | | performance_schema | | test | | varshitha | +--------------------+ 5 rows in set (0.00 sec) mysql> use varshitha; Database changed mysql> show tables; +---------------------+ | Tables_in_varshitha | +---------------------+ | students | +---------------------+ 1 row in set (0.02 sec) mysql> desc students; +-------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------+-------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | name | varchar(50) | NO | | NULL | | | age | int(11) | YES | | NULL | | | grade | varchar(10) | YES | | NULL | | +-------+-------------+------+-----+---------+----------------+ 4 rows in set (0.01 sec) mysql> select * from students; +----+-------+------+-------+ | id | name | age | grade | +----+-------+------+-------+ | 1 | Alice | 20 | A | | 2 | Bob | 22 | B | +----+-------+------+-------+ 2 rows in set (0.00 sec) mysql> DELIMITER // mysql> CREATE PROCEDURE selectGradeAStudents() -> BEGIN -> SELECT * FROM Students WHERE grade = 'A'; -> END // Query OK, 0 rows affected (0.00 sec) mysql> DELIMITER ; mysql> mysql> DELIMITER // mysql> CREATE FUNCTION getAverageAgeByGrade(gradeInput VARCHAR(10)) -> RETURNS DOUBLE -> BEGIN -> DECLARE avgAge DOUBLE; -> SELECT AVG(age) INTO avgAge FROM Students WHERE grade = gradeInput; -> RETURN avgAge; -> END // Query OK, 0 rows affected (0.00 sec) mysql> DELIMITER ;
package task11; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; public class metadata { // Database URL, user, and password static final String JDBC_URL = "jdbc:mysql://localhost:3306/varshitha"; // Replace with your database name static final String JDBC_USER = "root"; // Replace with your username static final String JDBC_PASSWORD = "root"; // Replace with your password public static void main(String[] args) { try (Connection connection = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD)) { // Get database metadata DatabaseMetaData dbMetaData = connection.getMetaData(); // Display general database information System.out.println("Database Product Name: " + dbMetaData.getDatabaseProductName()); System.out.println("Database Product Version: " + dbMetaData.getDatabaseProductVersion()); System.out.println("Database Driver Name: " + dbMetaData.getDriverName()); System.out.println("Database Driver Version: " + dbMetaData.getDriverVersion()); // Retrieve and display table metadata System.out.println("\nTables in the database:"); ResultSet tables = dbMetaData.getTables(null, null, "%", new String[] { "TABLE" }); while (tables.next()) { String tableName = tables.getString("TABLE_NAME"); System.out.println("Table: " + tableName); // Retrieve and display column metadata for each table ResultSet columns = dbMetaData.getColumns(null, null, tableName, "%"); while (columns.next()) { String columnName = columns.getString("COLUMN_NAME"); String columnType = columns.getString("TYPE_NAME"); int columnSize = columns.getInt("COLUMN_SIZE"); System.out.println(" Column: " + columnName + " - Type: " + columnType + " - Size: " + columnSize); } columns.close(); } tables.close(); } catch (SQLException e) { System.out.println("SQL Exception: " + e.getMessage()); } } }
package task10; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class updandscroll { // Database credentials and URL static final String JDBC_URL = "jdbc:mysql://localhost:3306/varshitha"; // Replace with your database name static final String JDBC_USER = "root"; // Replace with your MySQL username static final String JDBC_PASSWORD = "root"; // Replace with your MySQL password public static void main(String[] args) { try (Connection connection = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD); Statement statement = connection.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, // Scrollable ResultSet ResultSet.CONCUR_UPDATABLE)) { // Updatable ResultSet // Query to select all records from Students String selectSQL = "SELECT id, name, age, grade FROM Students"; ResultSet resultSet = statement.executeQuery(selectSQL); // Scroll to last row and display data if (resultSet.last()) { System.out.println("Last Row - ID: " + resultSet.getInt("id") + ", Name: " + resultSet.getString("name") + ", Age: " + resultSet.getInt("age") + ", Grade: " + resultSet.getString("grade")); } // Move to the first row and update the age and grade resultSet.first(); resultSet.updateInt("age", resultSet.getInt("age") + 1); // Increase age by 1 resultSet.updateString("grade", "A"); // Set grade to 'A' resultSet.updateRow(); // Commit the update System.out.println("Updated first row age and grade."); // Insert a new row into the ResultSet resultSet.moveToInsertRow(); resultSet.updateInt("id", 101); // Example ID resultSet.updateString("name", "New Student"); resultSet.updateInt("age", 20); resultSet.updateString("grade", "B"); resultSet.insertRow(); System.out.println("Inserted new row."); // Display all rows after the updates resultSet.beforeFirst(); // Move cursor to the beginning System.out.println("Updated Students Table:"); while (resultSet.next()) { System.out.println("ID: " + resultSet.getInt("id") + ", Name: " + resultSet.getString("name") + ", Age: " + resultSet.getInt("age") + ", Grade: " + resultSet.getString("grade")); } } catch (SQLException e) { System.out.println("SQL Exception: " + e.getMessage()); } } }
package task9; import java.sql.Connection; import java.sql.DriverManager; import java.sql.CallableStatement; import java.sql.ResultSet; import java.sql.SQLException; public class callablefunctions { // Database credentials and URL static final String JDBC_URL = "jdbc:mysql://localhost:3306/varshitha"; // Replace with your database name static final String JDBC_USER = "root"; // Replace with your MySQL username static final String JDBC_PASSWORD = "root"; // Replace with your MySQL password public static void main(String[] args) { // SQL query to call the stored function String callFunctionSQL = "{? = call getAverageAgeByGrade(?)}"; try (Connection connection = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD); CallableStatement callableStatement = connection.prepareCall(callFunctionSQL)) { // Register the output parameter (the average age) callableStatement.registerOutParameter(1, java.sql.Types.DOUBLE); // Set the input parameter (the grade for which we want the average age) callableStatement.setString(2, "A"); // Change the grade as needed // Execute the function callableStatement.execute(); // Retrieve the output parameter double averageAge = callableStatement.getDouble(1); System.out.println("Average age of students with grade 'A': " + averageAge); } catch (SQLException e) { System.out.println("SQL Exception: " + e.getMessage()); } } }
package task9; import java.sql.Connection; import java.sql.DriverManager; import java.sql.CallableStatement; import java.sql.ResultSet; import java.sql.SQLException; public class callableprocedures { // Database credentials and URL static final String JDBC_URL = "jdbc:mysql://localhost:3306/varshitha"; // Replace with your database name static final String JDBC_USER = "root"; // Replace with your MySQL username static final String JDBC_PASSWORD = "root"; // Replace with your MySQL password public static void main(String[] args) { // SQL query to call the stored procedure String callProcedureSQL = "{call selectGradeAStudents()}"; try (Connection connection = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD); CallableStatement callableStatement = connection.prepareCall(callProcedureSQL); ResultSet resultSet = callableStatement.executeQuery()) { System.out.println("Students with Grade A:"); while (resultSet.next()) { // Assuming the Students table has columns: id, name, age, and grade int id = resultSet.getInt("id"); String name = resultSet.getString("name"); int age = resultSet.getInt("age"); String grade = resultSet.getString("grade"); System.out.printf("ID: %d, Name: %s, Age: %d, Grade: %s%n", id, name, age, grade); } } catch (SQLException e) { System.out.println("SQL Exception: " + e.getMessage()); } }
package task9; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; public class preparedstmt { // Database credentials and URL static final String JDBC_URL = "jdbc:mysql://localhost:3306/varshitha"; // Replace with your database name static final String JDBC_USER = "root"; // Replace with your MySQL username static final String JDBC_PASSWORD = "root"; // Replace with your MySQL password public static void main(String[] args) { // SQL query to insert data into the Students table String insertSQL = "INSERT INTO Students (name, age, grade) VALUES (?, ?, ?)"; // Try with resources to automatically close the connection and statement try (Connection connection = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD); PreparedStatement preparedStatement = connection.prepareStatement(insertSQL)) { // Insert first student preparedStatement.setString(1, "Alice"); preparedStatement.setInt(2, 20); preparedStatement.setString(3, "A"); preparedStatement.executeUpdate(); System.out.println("Inserted first student: Alice"); // Insert second student preparedStatement.setString(1, "Bob"); preparedStatement.setInt(2, 22); preparedStatement.setString(3, "B"); preparedStatement.executeUpdate(); System.out.println("Inserted second student:s Bob"); } catch (SQLException e) { System.out.println("SQL Exception: " + e.getMessage()); } } }
package task8; import java.sql.*; public class jdbcex { // Database credentials and URL static final String JDBC_URL = "jdbc:mysql://localhost:3306/varshitha"; // Replace with your database name static final String JDBC_USER = "root"; // Replace with your MySQL username static final String JDBC_PASSWORD = "root"; // Replace with your MySQL password public static void main(String[] args) { try { // Load the MySQL JDBC driver Class.forName("com.mysql.cj.jdbc.Driver"); // Establish the connection Connection connection = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD); System.out.println("Connected to the database."); // Create a statement object to execute SQL commands Statement statement = connection.createStatement(); // SQL query to create a table named "Students" String createTableSQL = "CREATE TABLE IF NOT EXISTS Students (" + "id INT AUTO_INCREMENT PRIMARY KEY, " + "name VARCHAR(50) NOT NULL, " + "age INT, " + "grade VARCHAR(10)" + ");"; // Execute the SQL command to create the table statement.executeUpdate(createTableSQL); System.out.println("Table 'Students' created successfully."); // Close the statement and connection statement.close(); connection.close(); } catch (SQLException | ClassNotFoundException e) { System.out.println("Error: " + e.getMessage()); } } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Dynamic Pricing Table</title> <style> body { font-family: Arial, sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; background-color: #f4f4f4; margin: 0; } .pricing-table { display: flex; justify-content: space-around; width: 80%; } .card { background-color: #fff; border: 1px solid #ccc; border-radius: 10px; padding: 20px; text-align: center; transition: transform 0.3s, box-shadow 0.3s; width: 30%; box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1); } .card:hover { transform: scale(1.05); box-shadow: 0 8px 20px rgba(0, 0, 0, 0.2); } .card.selected { background-color: #007bff; color: white; border: none; } .card.selected:hover { box-shadow: 0 8px 20px rgba(0, 0, 0, 0.3); } .price { font-size: 2rem; margin: 10px 0; } button { padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer; background-color: #007bff; color: white; transition: background-color 0.3s; } button:hover { background-color: #0056b3; } </style> </head> <body> <div class="pricing-table"> <div class="card" onclick="selectCard(this)"> <h3>Basic Plan</h3> <div class="price">$10/month</div> <p>Basic features included.</p> <button>Choose</button> </div> <div class="card" onclick="selectCard(this)"> <h3>Standard Plan</h3> <div class="price">$20/month</div> <p>Standard features included.</p> <button>Choose</button> </div> <div class="card" onclick="selectCard(this)"> <h3>Premium Plan</h3> <div class="price">$30/month</div> <p>All features included.</p> <button>Choose</button> </div> </div> <script> function selectCard(card) { // Remove 'selected' class from all cards const cards = document.querySelectorAll('.card'); cards.forEach(c => c.classList.remove('selected')); // Add 'selected' class to the clicked card card.classList.add('selected'); } </script> </body> </html>
import java.sql.*; public class JdbcDmlExample { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/your_database_name"; // Replace with your database name String user = "your_username"; // Replace with your database username String password = "your_password"; // Replace with your database password try (Connection conn = DriverManager.getConnection(url, user, password)) { // Prepared Statement for Insert String insertSQL = "INSERT INTO users (name, email) VALUES (?, ?)"; try (PreparedStatement pstmt = conn.prepareStatement(insertSQL)) { pstmt.setString(1, "John Doe"); pstmt.setString(2, "john@example.com"); pstmt.executeUpdate(); System.out.println("User inserted successfully."); } // Prepared Statement for Update String updateSQL = "UPDATE users SET email = ? WHERE name = ?"; try (PreparedStatement pstmt = conn.prepareStatement(updateSQL)) { pstmt.setString(1, "john.doe@example.com"); pstmt.setString(2, "John Doe"); pstmt.executeUpdate(); System.out.println("User updated successfully."); } // Prepared Statement for Delete String deleteSQL = "DELETE FROM users WHERE name = ?"; try (PreparedStatement pstmt = conn.prepareStatement(deleteSQL)) { pstmt.setString(1, "John Doe"); pstmt.executeUpdate(); System.out.println("User deleted successfully."); } // Callable Statement for retrieving users String callableSQL = "{CALL getAllUsers()}"; // Assume this stored procedure exists try (CallableStatement cstmt = conn.prepareCall(callableSQL)) { ResultSet rs = cstmt.executeQuery(); System.out.println("Users in the database:"); while (rs.next()) { System.out.println("ID: " + rs.getInt("id") + ", Name: " + rs.getString("name")); } } } catch (SQLException e) { e.printStackTrace(); } } } How to Run the Java Program Setup JDBC: Ensure you have the MySQL JDBC Driver in your classpath. Create a Java File: Save the code above in a file named JdbcDmlExample.java. Create the Database and Table: Ensure you have a database with a users table that has at least id, name, and email columns. Also, create a stored procedure getAllUsers to fetch users. Compile and Run: Compile and run the Java program. Update the placeholders with your actual database connection details.
////////******* LOOPS IN JS ********/// // while loop let index = 0 while(index <= 10){ console.log(`the value of index is ${index}`); index = index+2; } let myarray = ["srk" , "salman khan" , "amir khan"] let arr = 0 while(arr < myarray.length){ console.log(`value is ${myarray[arr]}`); arr = arr +1 } // do while loop let score = 0 do{ console.log(`Score is ${score}`) score++ } while(score <= 10);
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Responsive Design with CSS Units</title> <style> body { font-family: Arial, sans-serif; margin: 0; padding: 20px; } .container { max-width: 1200px; /* Maximum width using px */ margin: 0 auto; /* Center the container */ } h1 { font-size: 2rem; /* Font size using rem */ color: #333; } p { font-size: 1em; /* Font size using em (relative to the parent) */ line-height: 1.5; /* Line height using unitless value */ } .responsive-box { width: 100%; /* Full width using % */ max-width: 600px; /* Max width using px */ padding: 20px; /* Padding using px */ margin: 20px auto; /* Margin using px */ background-color: #f0f0f0; border: 1px solid #ccc; box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.1); } @media (max-width: 600px) { h1 { font-size: 1.5rem; /* Adjust font size for smaller screens */ } } </style> </head> <body> <div class="container"> <h1>Responsive Design Using Different CSS Units</h1> <p>This paragraph demonstrates the use of <strong>em</strong> and <strong>rem</strong> for font sizes. It will scale based on the user's default font size settings.</p> <div class="responsive-box"> <p>This box adjusts its size and padding using a combination of CSS units. Resize the window to see how it responds!</p> </div> </div> </body> </html>
This Java application uses JDBC to connect to a MySQL database and demonstrate how to use updatable and scrollable result sets. java Copy code import java.sql.*; public class ScrollableUpdatableResultSet { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/your_database_name"; // Replace with your database name String user = "your_username"; // Replace with your database username String password = "your_password"; // Replace with your database password try (Connection conn = DriverManager.getConnection(url, user, password)) { // Create a statement for updatable and scrollable result set Statement stmt = conn.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE ); // Execute query ResultSet rs = stmt.executeQuery("SELECT * FROM users"); // Replace 'users' with your table name // Move to the last row and display the last record if (rs.last()) { System.out.println("Last User ID: " + rs.getInt("id") + ", Name: " + rs.getString("name")); } // Move to the first row if (rs.first()) { System.out.println("First User ID: " + rs.getInt("id") + ", Name: " + rs.getString("name")); // Update the first record rs.updateString("name", "Updated Name"); rs.updateRow(); System.out.println("Updated User Name to 'Updated Name'."); } // Close the result set and statement rs.close(); stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } } How to Run the Java Application Setup JDBC: Make sure you have the MySQL JDBC Driver in your classpath. Create a Java File: Name it ScrollableUpdatableResultSet.java and copy the code above. Compile and Run: Compile the Java program and run it. Ensure to replace the placeholders with your actual database connection details.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Responsive Bootstrap Grid</title> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <div class="container"> <h1 class="text-center my-4">Responsive Bootstrap Grid Example</h1> <div class="row"> <div class="col-md-4 col-sm-6 mb-4"> <div class="card"> <div class="card-body"> <h5 class="card-title">Column 1</h5> <p class="card-text">Content for column 1. This column is responsive.</p> </div> </div> </div> <div class="col-md-4 col-sm-6 mb-4"> <div class="card"> <div class="card-body"> <h5 class="card-title">Column 2</h5> <p class="card-text">Content for column 2. This column is responsive.</p> </div> </div> </div> <div class="col-md-4 col-sm-12 mb-4"> <div class="card"> <div class="card-body"> <h5 class="card-title">Column 3</h5> <p class="card-text">Content for column 3. This column is responsive.</p> </div> </div> </div> </div> </div> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.3/dist/umd/popper.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script> </body> </html>
import java.sql.*; public class DatabaseMetadataExample { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/your_database_name"; // Replace with your database URL String user = "your_username"; // Replace with your database username String password = "your_password"; // Replace with your database password try (Connection conn = DriverManager.getConnection(url, user, password)) { // Get Database Metadata DatabaseMetaData metaData = conn.getMetaData(); // Print database information System.out.println("Database Product Name: " + metaData.getDatabaseProductName()); System.out.println("Database Product Version: " + metaData.getDatabaseProductVersion()); System.out.println("Driver Name: " + metaData.getDriverName()); System.out.println("Driver Version: " + metaData.getDriverVersion()); // Get and print tables ResultSet tables = metaData.getTables(null, null, null, new String[]{"TABLE"}); System.out.println("\nTables in the database:"); while (tables.next()) { System.out.println("Table Name: " + tables.getString("TABLE_NAME")); } tables.close(); } catch (SQLException e) { e.printStackTrace(); } } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>User Input Form</title> </head> <body> <h1>User Input Form</h1> <form action="processForm" 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> <input type="submit" value="Submit"> </form> </body> </html> import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/processForm") public class FormProcessorServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Retrieve request parameters String name = request.getParameter("name"); String email = request.getParameter("email"); // Set response type response.setContentType("text/html"); // Generate response response.getWriter().println("<html><body>"); response.getWriter().println("<h1>Form Submission Successful</h1>"); response.getWriter().println("<p>Name: " + name + "</p>"); response.getWriter().println("<p>Email: " + email + "</p>"); response.getWriter().println("</body></html>"); } } <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <servlet> <servlet-name>FormProcessorServlet</servlet-name> <servlet-class>FormProcessorServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>FormProcessorServlet</servlet-name> <url-pattern>/processForm</url-pattern> </servlet-mapping> </web-app> How to Run the Example Create a Dynamic Web Project: Use an IDE like Eclipse or IntelliJ to create a new Dynamic Web Project. Add the HTML Form: Create an HTML file (e.g., form.html) and paste the form code into it. Place this file in the WebContent or root folder. Add the Servlet: Create a new servlet class (FormProcessorServlet) and paste the servlet code into it. Configure web.xml: If you are not using annotations, add the servlet configuration in the web.xml file located in the WEB-INF directory. Run the Server: Deploy the project on a servlet container (like Apache Tomcat). Access the Form: Open a web browser and navigate to http://localhost:8080/YourProjectName/form.html to access the form. Submit the Form: Fill in the form and submit it. The servlet will process the input and display the name and email back to the user.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Landing Page</title> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"> <style> body { background-color: #f8f9fa; } .hero-section { background-color: #4CAF50; /* Green */ color: white; padding: 100px 0; } </style> </head> <body> <!-- Hero Section --> <section class="hero-section text-center"> <div class="container"> <h1 class="display-4 mb-4">Welcome to Our Service</h1> <p class="lead mb-5">Innovative solutions for your business.</p> <a href="#" class="btn btn-light btn-lg">Get Started</a> </div> </section> <!-- Features Section --> <section class="py-5"> <div class="container text-center"> <h2 class="mb-4">Features</h2> <div class="row"> <div class="col-md-4 mb-4"><h3>Feature One</h3><p>Description here.</p></div> <div class="col-md-4 mb-4"><h3>Feature Two</h3><p>Description here.</p></div> <div class="col-md-4 mb-4"><h3>Feature Three</h3><p>Description here.</p></div> </div> </div> </section> <!-- Call to Action --> <section class="py-5 bg-light text-center"> <h2 class="mb-4">Ready to Get Started?</h2> <a href="#" class="btn btn-primary btn-lg">Sign Up Now</a> </section> <!-- Footer --> <footer class="py-4 bg-dark text-white text-center"> <p>© 2024 Your Company Name. All Rights Reserved.</p> </footer> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.3/dist/umd/popper.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script> </body> </html>
import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; @WebServlet("/configDemo") public class ConfigDemoServlet extends HttpServlet { private static final long serialVersionUID = 1L; public void init(ServletConfig config) throws ServletException { super.init(config); // You can retrieve ServletConfig parameters here String initParam = config.getInitParameter("exampleParam"); System.out.println("ServletConfig exampleParam: " + initParam); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); String contextParam = getServletContext().getInitParameter("contextParam"); ServletContext context = getServletContext(); response.getWriter().println("<html><body>"); response.getWriter().println("<h1>ServletConfig and ServletContext Demo</h1>"); response.getWriter().println("<p>ServletConfig Parameter: " + request.getServletContext().getInitParameter("contextParam") + "</p>"); response.getWriter().println("<p>ServletContext Parameter: " + contextParam + "</p>"); response.getWriter().println("</body></html>"); } } web.xml <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <servlet> <servlet-name>ConfigDemoServlet</servlet-name> <servlet-class>ConfigDemoServlet</servlet-class> <init-param> <param-name>exampleParam</param-name> <param-value>This is a ServletConfig parameter</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>ConfigDemoServlet</servlet-name> <url-pattern>/configDemo</url-pattern> </servlet-mapping> <context-param> <param-name>contextParam</param-name> <param-value>This is a ServletContext parameter</param-value> </context-param> </web-app>
////////******* LOOPS IN JS ********/// // for loop for (let i = 1; i <= 10; i++) { //console.log(`outer loop: ${i}`); for (let j = 1; j <= 10; j++) { // console.log(`${i} * ${j} = ${i * j}`); } } // loops in array for printing elements let myarray = ["srk" , "salman khan" , "amir khan"] console.log(myarray.length); for(let i = 0 ; i < myarray.length; i++){ const element = myarray[i]; console.log(element); } //// key words // break keyword for(let i = 0 ; i <= 10 ; i++){ if(i == 5){ console.log("number 5 is detected"); break } console.log(`the number is ${i}`); } // continue keyword for(let i = 0 ; i <= 10 ; i++){ if(i == 5){ console.log("number 5 is detected"); continue } console.log(`the number is ${i}`); }
Here's an example validation for registration, user login, user profile, and payment pages using JavaScript: Registration Page Validation // Registration form validation const registerForm = document.getElementById('register-form'); registerForm.addEventListener('submit', (e) => { e.preventDefault(); const username = document.getElementById('username').value.trim(); const email = document.getElementById('email').value.trim(); const password = document.getElementById('password').value.trim(); const confirmPassword = document.getElementById('confirm-password').value.trim(); if (username === '') { alert('Username is required'); return; } if (email === '') { alert('Email is required'); return; } if (!validateEmail(email)) { alert('Invalid email format'); return; } if (password === '') { alert('Password is required'); return; } if (password.length < 8) { alert('Password must be at least 8 characters'); return; } if (password !== confirmPassword) { alert('Passwords do not match'); return; } // Register user logic here }); // Email validation function function validateEmail(email) { const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/; return emailRegex.test(email); } Login Page Validation // Login form validation const loginForm = document.getElementById('login-form'); loginForm.addEventListener('submit', (e) => { e.preventDefault(); const email = document.getElementById('email').value.trim(); const password = document.getElementById('password').value.trim(); if (email === '') { alert('Email is required'); return; } if (!validateEmail(email)) { alert('Invalid email format'); return; } if (password === '') { alert('Password is required'); return; } // Login user logic here }); // Email validation function function validateEmail(email) { const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/; return emailRegex.test(email); } User Profile Validation // Profile form validation const profileForm = document.getElementById('profile-form'); profileForm.addEventListener('submit', (e) => { e.preventDefault(); const name = document.getElementById('name').value.trim(); const email = document.getElementById('email').value.trim(); const phone = document.getElementById('phone').value.trim(); if (name === '') { alert('Name is required'); return; } if (email === '') { alert('Email is required'); return; } if (!validateEmail(email)) { alert('Invalid email format'); return; } if (phone === '') { alert('Phone number is required'); return; } if (!validatePhone(phone)) { alert('Invalid phone number format'); return; } // Update profile logic here }); // Email validation function function validateEmail(email) { const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/; return emailRegex.test(email); } // Phone number validation function function validatePhone(phone) { const phoneRegex = /^\d{3}-\d{3}-\d{4}$/; return phoneRegex.test(phone); } Payment Page Validation // Payment form validation const paymentForm = document.getElementById('payment-form'); paymentForm.addEventListener('submit', (e) => { e.preventDefault(); const cardNumber = document.getElementById('card-number').value.trim(); const expirationDate = document.getElementById('expiration-date').value.trim(); const cvv = document.getElementById('cvv').value.trim(); if (cardNumber === '') { alert('Card number is required'); return; } if (!validateCardNumber(cardNumber)) { alert('Invalid card number format'); return; } if (expirationDate === '') { alert('Expiration date is required'); return; } if (!validateExpirationDate(expirationDate)) { alert('Invalid expiration date format'); return; } if (cvv === '') { alert('CVV is required'); return; } if (!validateCVV(cvv)) { alert('Invalid CVV format'); return; } // Process payment logic here }); // Card number validation function function validateCardNumber(cardNumber) { const cardNumberRegex = /^(\d{4}[- ]?){4}$/; return cardNumberRegex.test(cardNumber); } // Expiration date validation
<!DOCTYPE html> <html lang="en"> <head> <title>Online Book Store</title> <style> body { font-family: Arial, sans-serif; margin: 0; background-color: #f4f4f4; } header { background-color: #333; color: white; padding: 15px; text-align: center; } nav a { color: white; margin: 10px; text-decoration: none; } .container { display: none; /* Hide all sections initially */ padding: 20px; } .active { display: block; /* Show the active section */ } table { width: 100%; border-collapse: collapse; margin-top: 20px; } th, td { border: 1px solid #ddd; padding: 8px; text-align: left; } th { background-color: #f2f2f2; } input[type="text"], input[type="email"], input[type="password"] { width: 100%; padding: 10px; margin: 5px 0 10px; border: 1px solid #ccc; } input[type="submit"] { background-color: #4CAF50; color: white; padding: 10px; border: none; cursor: pointer; width: 100%; } input[type="submit"]:hover { background-color: #45a049; } </style> </head> <body> <header> <h1>Online Book Store</h1> <nav> <a href="#" onclick="showSection('home')">Home</a> <a href="#" onclick="showSection('login')">Login</a> <a href="#" onclick="showSection('catalogue')">Catalogue</a> <a href="#" onclick="showSection('registration')">Register</a> </nav> </header> <div id="home" class="container active"> <h2>Welcome to the Online Book Store!</h2> <p>Find your favorite books here.</p> </div> <div id="login" class="container"> <h2>Login</h2> <form action="#"> <label for="username">Username:</label> <input type="text" id="username" name="username" required> <label for="password">Password:</label> <input type="password" id="password" name="password" required> <input type="submit" value="Login"> </form> </div> <div id="catalogue" class="container"> <h2>Book Catalogue</h2> <table> <thead> <tr> <th>Book Title</th> <th>Author</th> <th>Price</th> <th>Availability</th> </tr> </thead> <tbody> <tr> <td>The Great Gatsby</td> <td>F. Scott Fitzgerald</td> <td>$10.99</td> <td>In Stock</td> </tr> <tr> <td>1984</td> <td>George Orwell</td> <td>$8.99</td> <td>In Stock</td> </tr> <tr> <td>To Kill a Mockingbird</td> <td>Harper Lee</td> <td>$12.99</td> <td>Out of Stock</td> </tr> <tr> <td>Pride and Prejudice</td> <td>Jane Austen</td> <td>$7.99</td> <td>In Stock</td> </tr> </tbody> </table> </div> <div id="registration" class="container"> <h2>Registration</h2> <form action="#"> <label for="new-username">Username:</label> <input type="text" id="new-username" name="username" required> <label for="email">Email:</label> <input type="email" id="email" name="email" required> <label for="new-password">Password:</label> <input type="password" id="new-password" name="password" required> <input type="submit" value="Register"> </form> </div> <script> function showSection(sectionId) { const sections = document.querySelectorAll('.container'); sections.forEach(section => { section.classList.remove('active'); // Hide all sections }); document.getElementById(sectionId).classList.add('active'); // Show the selected section } </script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <title>Minimal Responsive Website</title> <style> body { margin: 0; font-family: Arial, sans-serif; } header, footer { background: #4CAF50; color: white; text-align: center; padding: 10px 0; } nav { background: #333; text-align: center; } nav a { color: white; padding: 10px; text-decoration: none; display: inline-block; } .container { padding: 10px; } .box { border: 1px solid #ccc; margin: 10px 0; padding: 10px; text-align: center; } /* Media Queries */ @media (min-width: 600px) { .box { display: inline-block; width: calc(33% - 20px); margin: 10px; } } </style> </head> <body> <header> <h1>Responsive Website</h1> </header> <nav> <a href="#home">Home</a> <a href="#about">About</a> <a href="#services">Services</a> <a href="#contact">Contact</a> </nav> <div class="container"> <div class="box">Box 1</div> <div class="box">Box 2</div> <div class="box">Box 3</div> </div> <footer> <p>Footer © 2024</p> </footer> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>JavaScript Pop-Up Examples</title> <style> body { font-family: Arial, sans-serif; margin: 20px; } button { margin: 10px 0; padding: 10px 15px; font-size: 16px; } input[type="text"] { margin-top: 10px; width: 200px; padding: 10px; } </style> </head> <body> <h1>JavaScript Pop-Up Examples</h1> <h2>Display Current Date</h2> <button onclick="displayDate()">Display Date</button> <input type="text" id="dateOutput" placeholder="Date will be displayed here" readonly> <!-- b) Factorial --> <h2>Calculate Factorial</h2> <button onclick="calculateFactorial()">Calculate Factorial</button> <!-- c) Multiplication Table --> <h2>Multiplication Table</h2> <button onclick="multiplicationTable()">Show Multiplication Table</button> <script> // Function a: Display current date in the textbox function displayDate() { const date = new Date(); document.getElementById('dateOutput').value = date.toLocaleString(); } // Function b: Calculate factorial of a number function calculateFactorial() { const n = prompt("Enter a number to calculate its factorial:"); if (n === null || n === "" || isNaN(n) || n < 0) { alert("Please enter a valid non-negative number."); return; } let factorial = 1; for (let i = 1; i <= n; i++) { factorial *= i; } alert(`Factorial of ${n} is ${factorial}`); } // Function c: Show multiplication table of a number function multiplicationTable() { const n = prompt("Enter a number to see its multiplication table:"); if (n === null || n === "" || isNaN(n)) { alert("Please enter a valid number."); return; } let table = `Multiplication Table of ${n}:\n`; for (let i = 1; i <= 10; i++) { table += `${n} x ${i} = ${n * i}\n`; } alert(table); } </script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <title>CSS Grid and Flexbox</title> <style> body { font-family: Arial, sans-serif; } .header, .footer { display: flex; justify-content: center; align-items: center; background: #4CAF50; color: #fff; height: 60px; } .content { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; padding: 20px; } .box { padding: 20px; background: #2196F3; color: #fff; text-align: center; transition: transform 0.3s; } .box:hover { transform: scale(1.05); background: #1E88E5; } </style> </head> <body> <div class="header">Header</div> <div class="content"> <div class="box">Box 1</div> <div class="box">Box 2</div> <div class="box">Box 3</div> </div> <div class="footer">Footer</div> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <title>Data Attribute Example</title> <style> .item { cursor: pointer; margin: 10px 0; } </style> </head> <body> <h2>Product List</h2> <div class="item" data-description="A fresh apple from the orchard" onclick="showDetails(this)">Apple</div> <div class="item" data-description="A ripe, sweet banana" onclick="showDetails(this)">Banana</div> <div class="item" data-description="A juicy bunch of grapes" onclick="showDetails(this)">Grapes</div> <h3>Details:</h3> <p id="details"></p> <script> function showDetails(element) { const description = element.getAttribute("data-description"); document.getElementById("details").textContent = description; } </script> </body> </html>
star
Fri Nov 01 2024 20:46:24 GMT+0000 (Coordinated Universal Time) https://myairdropinfocenterDaily-t.com