BCS-053 Solved Free Assignment 2024-25 Sem 5






Question 1: (Covers Block 1)

a) Explain the features of the following technologies – Blogging, Mashups and Rich Internet Applications. How are these technologies useful for you?

Ans:-  (a) Features of Blogging, Mashups, and Rich Internet Applications


1. **Blogging**


   **Features**:

   - **Content Creation and Sharing**: Allows individuals or organizations to publish content, such as articles, opinions, news, tutorials, and updates on a specific topic or field.

   - **Comments and Interactivity**: Most blogging platforms allow readers to interact with content by commenting, creating a two-way communication channel between bloggers and readers.

   - **Tags and Categories**: Helps organize content, making it easier for readers to find topics of interest.

   - **Personalization and Customization**: Blogs can be personalized with unique themes, designs, and media content like images and videos.

   - **Subscription and Feed Options**: Readers can subscribe to blogs through RSS feeds or email notifications, ensuring they don’t miss updates.


   **Usefulness**:

   - Blogging is valuable for sharing knowledge, building a personal or professional brand, and improving writing skills. It also enables connecting with like-minded individuals and creating a portfolio of work or expertise.


2. **Mashups**


   **Features**:

   - **Data Integration from Multiple Sources**: Combines data from different platforms, such as maps, social media, and news APIs, to provide a comprehensive view or unique functionality.

   - **APIs and Web Services**: Uses Application Programming Interfaces (APIs) to access data from external sources.

   - **Dynamic Content Presentation**: Updates information in real-time or at regular intervals, providing users with the latest data without needing to refresh the entire application.

   - **Interactive and Visual Representation**: Often includes interactive maps, charts, and other visualizations that help users understand complex information.


   **Usefulness**:

   - Mashups allow users to access integrated data from various sources, which can be valuable for research, analysis, and decision-making. For example, a weather-travel mashup could show potential impacts on travel plans, helping users make informed decisions.


3. **Rich Internet Applications (RIAs)**


   **Features**:

   - **Enhanced User Experience**: RIAs offer highly interactive, desktop-like experiences within a web browser, improving usability and engagement.

   - **Real-Time Data Updates**: Uses technologies like AJAX, WebSockets, and APIs to provide real-time data updates without reloading the entire page.

   - **Multimedia Support**: RIAs can handle images, videos, and animations seamlessly, making them suitable for multimedia-rich applications.

   - **Cross-Platform Compatibility**: Typically accessible across different devices and browsers, offering consistent functionality and experience.

   - **Offline Access**: Some RIAs can cache data locally, allowing limited functionality even without an active internet connection.


   **Usefulness**:

   - RIAs are helpful for applications that require user engagement and interactivity, such as e-commerce platforms, social media, and online collaboration tools. They enable a seamless, desktop-like experience within a browser, supporting productivity and enhancing user satisfaction.


How These Technologies Are Useful


- **Blogging** helps with sharing insights, creating a personal brand, and building a portfolio of content that can establish credibility and attract an audience.

- **Mashups** provide valuable, combined data views that support decision-making, research, and personalized information services. They are especially helpful in scenarios that require data from different sources, such as travel planning or financial analysis.

- **Rich Internet Applications** enable engaging, interactive experiences in various online services. They are beneficial for tasks that require frequent interaction, such as online shopping, content creation, and using productivity tools, all of which save time and enhance user experience.


b) (i) Create an online membership form for an Online Library using HTML. The form should ask for the following information:  

 The Name of the member 

 Aadhar Number 

 Type of Membership (Student/Faculty/Staff/Other to be chosen from a drop down list)

 Year of membership 

 Were you a member earlier? Yes/No 

 Description of services expected from the Library 

(ii) Create an external CSS file for this form. This CSS file should select the font size of 14 point italics for all the labels; font colour should be red for the headings and dark blue for the normal text. The background colour of the form should be light green. 

(iii) Write JavaScript code to validate if any of the field of the form is not filled. (3 Marks) Submit the HTML code, JavaScript code and screenshot of the form opened in a browser window. You must demonstrate the form and validations at the time of viva.

Ans:- Here's a breakdown of the requested HTML, CSS, and JavaScript code for the Online Library Membership Form, followed by explanations.


---


 (i) HTML Code for Online Library Membership Form


```html

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Online Library Membership Form</title>

    <link rel="stylesheet" href="style.css">

</head>

<body>

    <h1 class="heading">Library Membership Form</h1>

    <form id="membershipForm" onsubmit="return validateForm()">

        <label for="name">Name of the Member:</label>

        <input type="text" id="name" name="name"><br>


        <label for="aadhar">Aadhar Number:</label>

        <input type="text" id="aadhar" name="aadhar"><br>


        <label for="membershipType">Type of Membership:</label>

        <select id="membershipType" name="membershipType">

            <option value="">--Select--</option>

            <option value="Student">Student</option>

            <option value="Faculty">Faculty</option>

            <option value="Staff">Staff</option>

            <option value="Other">Other</option>

        </select><br>


        <label for="year">Year of Membership:</label>

        <input type="number" id="year" name="year" min="1900" max="2100"><br>


        <label>Were you a member earlier?</label>

        <input type="radio" id="yes" name="earlierMember" value="Yes">

        <label for="yes">Yes</label>

        <input type="radio" id="no" name="earlierMember" value="No">

        <label for="no">No</label><br>


        <label for="services">Description of Services Expected:</label>

        <textarea id="services" name="services" rows="4" cols="30"></textarea><br>


        <input type="submit" value="Submit">

    </form>


    <script src="validate.js"></script>

</body>

</html>

```


---


(ii) CSS Code (`style.css`)


```css

/* style.css */


body {

    background-color: lightgreen;

    font-family: Arial, sans-serif;

}


.heading {

    color: red;

    font-size: 18px;

    font-weight: bold;

}


label {

    font-size: 14px;

    font-style: italic;

    color: darkblue;

    display: inline-block;

    width: 200px;

}


input, select, textarea {

    margin-bottom: 10px;

    padding: 5px;

    font-size: 14px;

}


form {

    max-width: 400px;

    margin: 20px auto;

    padding: 20px;

    border: 1px solid #000;

    background-color: white;

    border-radius: 8px;

}

```


---


(iii) JavaScript Code for Form Validation (`validate.js`)


```javascript

// validate.js


function validateForm() {

    // Get form fields

    let name = document.getElementById("name").value;

    let aadhar = document.getElementById("aadhar").value;

    let membershipType = document.getElementById("membershipType").value;

    let year = document.getElementById("year").value;

    let earlierMemberYes = document.getElementById("yes").checked;

    let earlierMemberNo = document.getElementById("no").checked;

    let services = document.getElementById("services").value;


    // Check if any required field is empty

    if (name === "" || aadhar === "" || membershipType === "" || year === "" || 

       (!earlierMemberYes && !earlierMemberNo) || services === "") {

        alert("Please fill all the fields.");

        return false; // Prevent form submission

    }

    return true; // Allow form submission

}

```


---


 Explanation of Each Part


1. **HTML Form**: This form captures the required information fields, including name, Aadhar number, membership type, membership year, a prior membership question, and a description of expected services. Each field has an associated `id` to enable JavaScript validation and CSS styling.


2. **CSS Styling**: 

   - Sets the background color to light green and the font size of labels to 14-point italics.

   - The heading has a red font color and a bold style.

   - Regular text (labels) is styled in dark blue.

   - The form is centered, with additional padding and a white background for readability.


3. **JavaScript Validation**:

   - The `validateForm()` function checks if all fields are filled out before submission.

   - If any field is empty, an alert appears to notify the user, and the form submission is prevented.

   - This validation runs when the user submits the form.


---

This setup provides a complete and user-friendly form for an online library membership application, with visual enhancements and input validation.


c) Using tables, create a webpage displaying the course list of the BCA programme. This webpage should display the semester wise list of courses with the headings - serial number, course code, course title, course credits, and course type (Theory, Practical or Project). Create a second page containing separate ordered lists of course titles of theory courses and practical courses. You should use tags, wherever needed; and create an internal CSS file, which formats the web pages as given below: 

(i) The headings of the table must be in 12-point Bold and all other content should be in 11-point Arial font. 

(ii) The table heading should be in different shade. The data rows of the table should have alternatively light pink and light blue colour. The background of the table should be light green. 

(iii) The font of the ordered list should be "Times New Roman" with font size of 11 points. The background colour of list should be light yellow. 6 

(iv) At the time of viva, you should demonstrate how changes in CSS can change the display. (You must submit the HTML and CSS code and the screenshot of pages in a browser window.)

Ans:- Here's the HTML and CSS code for the requested BCA course list webpage with a second page containing ordered lists for theory and practical courses.


---


 First Page (Course List - `courses.html`)


```html

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>BCA Course List</title>

    <style>

        /* Internal CSS */


        body {

            font-family: Arial, sans-serif;

            background-color: #f0f8ff;

        }


        h1 {

            text-align: center;

            font-size: 18px;

            color: #333;

        }


        table {

            width: 80%;

            margin: 20px auto;

            border-collapse: collapse;

            background-color: lightgreen;

        }


        th {

            font-size: 12pt;

            font-weight: bold;

            color: white;

            background-color: #4CAF50;

            padding: 8px;

        }


        td {

            font-size: 11pt;

            padding: 8px;

            text-align: center;

        }


        tr:nth-child(even) {

            background-color: lightpink;

        }


        tr:nth-child(odd) {

            background-color: lightblue;

        }


        /* Link to second page */

        .link {

            text-align: center;

            margin-top: 20px;

            font-size: 14px;

        }

    </style>

</head>

<body>

    <h1>BCA Programme - Semester-wise Course List</h1>

    <table border="1">

        <tr>

            <th>Serial No.</th>

            <th>Course Code</th>

            <th>Course Title</th>

            <th>Credits</th>

            <th>Course Type</th>

        </tr>

        <tr>

            <td>1</td>

            <td>BCA101</td>

            <td>Introduction to Computer Science</td>

            <td>4</td>

            <td>Theory</td>

        </tr>

        <tr>

            <td>2</td>

            <td>BCA102</td>

            <td>Programming Fundamentals</td>

            <td>4</td>

            <td>Theory</td>

        </tr>

        <tr>

            <td>3</td>

            <td>BCA103</td>

            <td>Computer Lab I</td>

            <td>2</td>

            <td>Practical</td>

        </tr>

        <!-- More rows can be added similarly -->

    </table>


    <div class="link">

        <a href="course_lists.html">View Theory and Practical Courses</a>

    </div>

</body>

</html>

```


---


 Second Page (Theory and Practical Course Lists - `course_lists.html`)


```html

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>BCA Theory and Practical Courses</title>

    <style>

        /* Internal CSS for ordered lists */


        body {

            font-family: Arial, sans-serif;

            background-color: #f0f8ff;

        }


        h1 {

            text-align: center;

            font-size: 18px;

            color: #333;

        }


        .course-list {

            width: 60%;

            margin: 20px auto;

            padding: 15px;

            background-color: lightyellow;

            font-family: "Times New Roman", Times, serif;

            font-size: 11pt;

        }


        .course-list h2 {

            font-size: 14pt;

            color: #333;

            margin-top: 0;

        }

    </style>

</head>

<body>

    <h1>Theory and Practical Courses in BCA Programme</h1>

    

    <div class="course-list">

        <h2>Theory Courses</h2>

        <ol>

            <li>Introduction to Computer Science</li>

            <li>Programming Fundamentals</li>

            <!-- Add more theory courses as needed -->

        </ol>

    </div>


    <div class="course-list">

        <h2>Practical Courses</h2>

        <ol>

            <li>Computer Lab I</li>

            <!-- Add more practical courses as needed -->

        </ol>

    </div>

</body>

</html>

```


---


 Explanation of CSS and HTML Features


1. **Tables (First Page)**

   - The **table headings** are styled with bold, 12-point font, and a background color to differentiate the headers.

   - **Data rows** alternate between light pink and light blue colors for easy readability.

   - **Table background** is set to light green.

   - The **font style for all text** in the table is Arial, with 11-point size for general content.


2. **Ordered Lists (Second Page)**

   - Each list (`<ol>`) is wrapped in a `div` with class `course-list` for styling.

   - The font for the list items is **Times New Roman, size 11-point**.

   - The background color for the list section is **light yellow** to distinguish it from the rest of the page.


3. **Navigational Link**:

   - The first page has a link to the second page to view separate lists of theory and practical courses.


---


This setup covers both the presentation requirements and the functional structure. You can test changes in the CSS file to observe how they affect the display, such as altering font size, color, and background for demonstration.


d) A University maintains the list of its students using XML. Every student is allotted a unique enrolment Number, which can be used as an attribute in the XML document. In addition, the following information is stored about the students – Name, Programme, Duration of Programme, List of courses enrolled (assume that student takes at least one and maximum of five courses in a programme). Create an XML document containing information of five Students of BCA programme. Also create the DTD to verify the XML document created by you.

Ans:- Here's an example of the XML document and the Document Type Definition (DTD) for storing student information at a university. The XML document will contain information for five students enrolled in the BCA program, each with a unique enrollment number and a list of enrolled courses.


---


 XML Document (`students.xml`)


```xml

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE University SYSTEM "students.dtd">

<University>

    <Student enrollmentNumber="BCA2023001">

        <Name>John Doe</Name>

        <Programme>BCA</Programme>

        <Duration>3 years</Duration>

        <Courses>

            <Course>Introduction to Computer Science</Course>

            <Course>Programming Fundamentals</Course>

            <Course>Mathematics I</Course>

        </Courses>

    </Student>


    <Student enrollmentNumber="BCA2023002">

        <Name>Jane Smith</Name>

        <Programme>BCA</Programme>

        <Duration>3 years</Duration>

        <Courses>

            <Course>Introduction to Computer Science</Course>

            <Course>Database Management</Course>

            <Course>Web Development</Course>

        </Courses>

    </Student>


    <Student enrollmentNumber="BCA2023003">

        <Name>Michael Brown</Name>

        <Programme>BCA</Programme>

        <Duration>3 years</Duration>

        <Courses>

            <Course>Programming Fundamentals</Course>

            <Course>Mathematics I</Course>

            <Course>Data Structures</Course>

            <Course>Software Engineering</Course>

        </Courses>

    </Student>


    <Student enrollmentNumber="BCA2023004">

        <Name>Sarah Johnson</Name>

        <Programme>BCA</Programme>

        <Duration>3 years</Duration>

        <Courses>

            <Course>Database Management</Course>

            <Course>Operating Systems</Course>

            <Course>Mathematics II</Course>

        </Courses>

    </Student>


    <Student enrollmentNumber="BCA2023005">

        <Name>David Lee</Name>

        <Programme>BCA</Programme>

        <Duration>3 years</Duration>

        <Courses>

            <Course>Introduction to Computer Science</Course>

            <Course>Web Development</Course>

            <Course>Software Engineering</Course>

            <Course>Operating Systems</Course>

            <Course>Computer Networks</Course>

        </Courses>

    </Student>

</University>

```


---


DTD Document (`students.dtd`)


```dtd

<!ELEMENT University (Student+)>

<!ELEMENT Student (Name, Programme, Duration, Courses)>

<!ATTLIST Student enrollmentNumber ID #REQUIRED>


<!ELEMENT Name (#PCDATA)>

<!ELEMENT Programme (#PCDATA)>

<!ELEMENT Duration (#PCDATA)>

<!ELEMENT Courses (Course+)>

<!ELEMENT Course (#PCDATA)>

```


---


Explanation


1. **XML Document (`students.xml`)**:

   - The `<University>` element serves as the root element.

   - Each `<Student>` element contains details about the student, including `enrollmentNumber` as a unique attribute.

   - Inside each `<Student>`, there are sub-elements for `<Name>`, `<Programme>`, `<Duration>`, and `<Courses>`.

   - The `<Courses>` element contains one or more `<Course>` entries (minimum of one, maximum of five, as specified).


2. **DTD Document (`students.dtd`)**:

   - The `University` element can have one or more `Student` elements.

   - Each `Student` element has a required `enrollmentNumber` attribute of type `ID` to ensure uniqueness.

   - Inside the `Student` element, the required child elements are `Name`, `Programme`, `Duration`, and `Courses`.

   - `Courses` contains one or more `Course` elements, as specified in the question.

  

This XML and DTD setup will allow the university to maintain a structured list of students and validate their information easily. The DTD ensures that each student entry is consistent with the defined structure.


e) Write JavaScript code that displays the text "Welcome to JavaScript Event Demonstration". When you click on this text, then it changes to “We just demonstrated the click Event". You may use event handling to perform the action as stated above. Make suitable assumptions, if any. You should demonstrate this code at the time of viva.

Ans:- Here's the JavaScript code to demonstrate the click event on a text. The initial text, "Welcome to JavaScript Event Demonstration," changes to "We just demonstrated the click Event" when clicked.


HTML and JavaScript Code


```html

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>JavaScript Event Demonstration</title>

    <style>

        /* Styling for the text */

        #demoText {

            font-size: 18px;

            color: #333;

            text-align: center;

            margin-top: 50px;

            cursor: pointer;

        }

    </style>

</head>

<body>


    <div id="demoText" onclick="changeText()">Welcome to JavaScript Event Demonstration</div>


    <script>

        // JavaScript function to handle the click event

        function changeText() {

            document.getElementById("demoText").innerText = "We just demonstrated the click Event";

        }

    </script>

    

</body>

</html>

```


---


 Explanation


1. **HTML Structure**:

   - A `div` element with the `id` `demoText` displays the initial text, "Welcome to JavaScript Event Demonstration."

   - The `onclick` attribute is added to this `div` to call the `changeText()` function when clicked.


2. **JavaScript Code**:

   - The `changeText()` function changes the `innerText` of the `div` to "We just demonstrated the click Event" when called.

   

3. **CSS Styling**:

   - The text is centered, styled in a larger font, and the cursor changes to a pointer on hover, indicating that it is clickable.


This setup allows you to demonstrate the basic use of JavaScript events and dynamic content changes during the viva.


f) Explain the working of the WAP model. Also, list the benefits and limitations of WAP. Explain the following WML elements with the help of an example of each: 

 Preformatted text in WML 

 WML Navigational elements 

 WML

Ans:-  The **Wireless Application Protocol (WAP)** model was designed to enable mobile devices, especially early-generation mobile phones with limited processing power, memory, and display capabilities, to access information over the internet. WAP provided a standardized way for mobile devices to retrieve and display web content, optimizing data transfer and display for limited network bandwidth and screen size.


 Working of the WAP Model


The WAP model has a layered architecture, similar to the OSI model, which simplifies adding or updating new protocols without impacting the entire system. The key layers in the WAP architecture are:


1. **Application Layer**: Contains the Wireless Markup Language (WML) and WMLScript, tailored for mobile device displays and inputs.

2. **Session Layer (WSP)**: Wireless Session Protocol (WSP) handles communication sessions and maintains state between client and server.

3. **Transaction Layer (WTP)**: Wireless Transaction Protocol (WTP) enables reliable message exchanges, supporting operations like transactions or requests and responses.

4. **Security Layer (WTLS)**: Wireless Transport Layer Security (WTLS) provides data integrity, privacy, and authentication.

5. **Transport Layer (WDP)**: Wireless Datagram Protocol (WDP) enables the use of various data carriers, such as SMS or GSM.


A **WAP gateway** translates standard web content (HTTP and HTML) into WAP content (WSP and WML), which is then delivered to WAP-enabled devices.


Benefits of WAP


- **Platform Independence**: WAP is supported across various mobile devices and network carriers.

- **Data Efficiency**: Optimized for low-bandwidth networks, conserving mobile data.

- **Low Cost**: Reduced data usage made WAP cost-effective, especially in the early mobile web days.

- **Standardized Protocol**: Provides a unified access method across different devices and networks.


Limitations of WAP


- **Limited Graphics and Multimedia**: WML did not support rich media, limiting content types.

- **Small Display Support**: Optimized for small screens but led to simplified or limited information presentation.

- **Slow Speeds**: Early mobile networks offered limited speeds, resulting in delayed responses.

- **Outdated**: WAP has largely been replaced by more advanced web standards (e.g., HTML5, CSS) that are compatible with modern smartphones.


---


WML Elements with Examples


1. Preformatted Text in WML


In WML, preformatted text maintains whitespace and line breaks, displaying text exactly as it is written, which is useful for formatting content neatly on smaller screens.


**Example:**


```wml

<?xml version="1.0"?>

<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.1//EN" "http://www.wapforum.org/DTD/wml_1.1.xml">

<wml>

    <card id="preformatted" title="Preformatted Text">

        <p mode="wrap">

            <pre>

            Hello, User!

            Welcome to the WAP Service.

            </pre>

        </p>

    </card>

</wml>

```


Here, `<pre>` ensures that "Hello, User!" and "Welcome to the WAP Service." are displayed on separate lines.


---


 2. WML Navigational Elements


Navigational elements in WML allow users to navigate between cards (pages). Elements like `<go>` are used to define links between cards or URLs, while `<prev>` can be used for back navigation.


**Example:**


```wml

<?xml version="1.0"?>

<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.1//EN" "http://www.wapforum.org/DTD/wml_1.1.xml">

<wml>

    <card id="home" title="Home">

        <p>Welcome to the Home Page.</p>

        <p>

            <a href="#nextCard">Go to Next Page</a>

        </p>

    </card>


    <card id="nextCard" title="Next Page">

        <p>You have navigated to the next page.</p>

        <p>

            <a href="#home">Return to Home</a>

        </p>

    </card>

</wml>

```


This example has two cards. The `<a href="#nextCard">` link navigates to the "Next Page," and `<a href="#home">` returns to "Home."


---


 3. WML `<select>` Element


The `<select>` element in WML allows users to choose from multiple options, similar to an HTML dropdown. It is useful for creating menus or selection lists.


**Example:**


```wml

<?xml version="1.0"?>

<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.1//EN" "http://www.wapforum.org/DTD/wml_1.1.xml">

<wml>

    <card id="selection" title="Select Your Option">

        <p>Select a service:</p>

        <select name="service">

            <option value="1" onpick="#service1">Service 1</option>

            <option value="2" onpick="#service2">Service 2</option>

            <option value="3" onpick="#service3">Service 3</option>

        </select>

    </card>


    <card id="service1" title="Service 1">

        <p>You selected Service 1.</p>

    </card>

    <card id="service2" title="Service 2">

        <p>You selected Service 2.</p>

    </card>

    <card id="service3" title="Service 3">

        <p>You selected Service 3.</p>

    </card>

</wml>

```


In this example, the `<select>` element displays three options. Selecting an option triggers the `onpick` attribute, which links to a specific card related to the selected service.


---


These elements demonstrate WML’s ability to handle text, navigation, and selection in the limited environment of early mobile devices, allowing for interactive and structured content within the constraints of WAP technology.


Question 2: (Covers Block 2)

a) Explain the following with the help of a diagram/example, if needed: 

(i) Static web pages and Dynamic web pages

(ii) N-Tier Architecture

(iii) Tools for server side scripting

(iv) HTTP primitives 

(v) Web Container 

Ans:- Let's break down each concept with explanations, diagrams, and examples where applicable.


---


(i) Static Web Pages and Dynamic Web Pages


1. **Static Web Pages**: 

   - Content is fixed and doesn't change based on user interactions or other factors. 

   - Written in HTML and CSS, and they load the same content every time they’re accessed.

   - No need for server-side processing; often cached by the browser, which results in faster loading.

   - Examples include company “About Us” pages or digital brochures.


   **Diagram**:


   ```

   User Request -> Web Server -> HTML/CSS file -> Display in Browser

   ```


2. **Dynamic Web Pages**:

   - Content changes dynamically based on user interactions, database queries, or other factors.

   - Often involve server-side scripts (e.g., PHP, Python) or client-side scripts (e.g., JavaScript).

   - Can interact with databases to fetch or update data, making pages interactive.

   - Examples include e-commerce websites or social media feeds.


   **Diagram**:


   ```

   User Request -> Web Server -> Server-Side Processing (Database/Logic) -> Dynamic Content Display in Browser

   ```


---


(ii) N-Tier Architecture


**N-Tier Architecture** is a multi-layered software architecture model, typically with the following tiers:


1. **Presentation Layer (Client)**:

   - The UI that users interact with, often using HTML, CSS, and JavaScript.


2. **Application Layer (Business Logic)**:

   - Contains the business logic and controls interactions between the presentation layer and data layer. Typically written in a language like Python, Java, or PHP.


3. **Data Layer (Database)**:

   - Responsible for data storage and management, typically using databases like MySQL or MongoDB.


**Diagram**:


   ```

   [Client/Browser]

         |

   [Presentation Layer]

         |

   [Application Layer]

         |

   [Data Layer]

   ```


In **N-tier architecture**, each layer is isolated and can be scaled or updated independently, offering flexibility, scalability, and maintainability. Examples include e-commerce platforms and content management systems.


---


 (iii) Tools for Server-Side Scripting


Server-side scripting tools allow the server to process user requests, interact with databases, and deliver dynamic content. Common tools include:


1. **PHP**: Popular for web applications; used in WordPress and other CMS platforms.

2. **Python (Django, Flask)**: Python frameworks are often used for their readability and efficiency in building applications.

3. **Node.js**: Executes JavaScript on the server side, suitable for real-time applications like chat apps.

4. **ASP.NET**: A Microsoft framework that enables building dynamic web applications, especially popular in enterprise environments.

5. **Ruby on Rails**: Known for rapid development and convention-over-configuration.


Each of these tools interacts with databases and other services to generate dynamic, interactive web content.


---


(iv) HTTP Primitives


HTTP primitives are methods defining the types of actions that can be performed between a client and a server. These include:


1. **GET**: Requests data from a specified resource. Often used for reading or viewing data.

2. **POST**: Sends data to the server, usually for creating a new entry (e.g., submitting a form).

3. **PUT**: Updates an existing resource on the server.

4. **DELETE**: Removes a specified resource on the server.


**Diagram**:


   ```

   Client (Browser) -> HTTP Method (GET/POST/PUT/DELETE) -> Server -> Resource Action

   ```


HTTP primitives enable a structured way for the client to communicate with the server, supporting actions like viewing, updating, or deleting resources on a website.


---


 (v) Web Container


A **Web Container** (or Servlet Container) is a component in a server that manages the execution of web applications, specifically handling Java servlets and JavaServer Pages (JSP).


**Key Functions**:

1. **Servlet Life Cycle Management**: Manages the instantiation, initialization, and destruction of servlets.

2. **Request/Response Handling**: Receives HTTP requests and routes them to the appropriate servlet, then sends the generated response back to the client.

3. **Security**: Ensures secure communication and access control for applications.

4. **Session Management**: Tracks user sessions to support personalized and interactive web applications.


**Diagram**:


   ```

   [Client Request] -> Web Server -> [Web Container] -> Servlets / JSP -> Response to Client

   ```


**Example**: **Apache Tomcat** is a widely used web container, providing an environment for running Java applications.


---


Each of these components plays a fundamental role in building, deploying, and managing modern web applications.


b) Explain with the help of an example/diagram or write code for the following using JSP: 

(i) include and taglib directives of JSP

(ii) Write a JSP scriptlet to display a list of first 10 positive odd numbers.

(iii) and action elements of JSP 

(iv) session and application implicit objects in JSP 

(v) JSP Life cycle 

Ans:- (i) `include` and `taglib` Directives in JSP


1. **`include` Directive**: 

   - The `include` directive is used to include content from another file at compile time. 

   - It's generally used to insert reusable code or templates (e.g., headers or footers).


   **Syntax**: `<%@ include file="relativeURL" %>`


   **Example**: Including a header file.

   ```jsp

   <%@ include file="header.jsp" %>

   <html>

   <body>

       <h1>Welcome to My JSP Page</h1>

       <!-- Main content here -->

       <%@ include file="footer.jsp" %>

   </body>

   </html>

   ```


2. **`taglib` Directive**: 

   - The `taglib` directive is used to include a library of custom tags into the JSP. 

   - It provides a way to define and use custom tags in JSP pages, which helps modularize JSP code.


   **Syntax**: `<%@ taglib uri="URI" prefix="prefix" %>`


   **Example**: Using JSTL (Java Standard Tag Library).

   ```jsp

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

   <html>

   <body>

       <c:if test="${someCondition}">

           <p>Condition met!</p>

       </c:if>

   </body>

   </html>

   ```


---


 (ii) JSP Scriptlet to Display the First 10 Positive Odd Numbers


A JSP scriptlet can be used to execute Java code and display the result directly on the page.


**Code**:

```jsp

<html>

<body>

    <h3>First 10 Positive Odd Numbers</h3>

    <ul>

        <% 

            for(int i = 1, count = 0; count < 10; i += 2, count++) {

                out.println("<li>" + i + "</li>");

            }

        %>

    </ul>

</body>

</html>

```


This code uses a `for` loop to print the first 10 odd numbers in an unordered list.


---


 (iii) `<jsp:setProperty>` and `<jsp:getProperty>` Action Elements


1. **`<jsp:setProperty>`**: Used to set a property in a JavaBean.

   - It links form inputs to JavaBean properties.


   **Syntax**:

   ```jsp

   <jsp:setProperty name="beanName" property="propertyName" value="value" />

   ```


2. **`<jsp:getProperty>`**: Retrieves a property value from a JavaBean and displays it.


   **Syntax**:

   ```jsp

   <jsp:getProperty name="beanName" property="propertyName" />

   ```


**Example**:

Assume we have a `UserBean` with a `username` property.


```jsp

<jsp:useBean id="user" class="com.example.UserBean" scope="session" />

<jsp:setProperty name="user" property="username" value="JohnDoe" />


Hello, <jsp:getProperty name="user" property="username" />!

```


This will set the `username` property of `user` to "JohnDoe" and display "Hello, JohnDoe!" on the page.


---


 (iv) `session` and `application` Implicit Objects in JSP


1. **`session` Object**:

   - Represents the current user session and is used to store data across multiple requests from the same user.


   **Example**:

   ```jsp

   <% 

       session.setAttribute("username", "JohnDoe"); 

   %>

   Welcome, <%= session.getAttribute("username") %>!

   ```


2. **`application` Object**:

   - Represents the application context, shared across all users and sessions.


   **Example**:

   ```jsp

   <% 

       application.setAttribute("siteName", "MyWebsite"); 

   %>

   You are browsing <%= application.getAttribute("siteName") %>!

   ```


   Here, `application.getAttribute("siteName")` will return "MyWebsite" for all users.


---


(v) JSP Life Cycle


The JSP life cycle includes several phases from translation to cleanup, allowing the JSP page to respond to HTTP requests dynamically.


1. **Translation Phase**: The JSP file is compiled into a servlet by the server.

2. **Compilation Phase**: The generated servlet is compiled into bytecode.

3. **Initialization (`jspInit`)**: The `jspInit()` method is called once when the JSP page is loaded, initializing resources.

4. **Request Handling (`_jspService`)**: Each client request invokes `_jspService()`, which generates the dynamic content.

5. **Destruction (`jspDestroy`)**: `jspDestroy()` is called when the JSP page is about to be removed, cleaning up resources.


**Diagram**:

```

[JSP Source Code] -> [Translation & Compilation] -> [Servlet] -> [Initialization] -> [Request Handling] -> [Destruction]

```


c) Write JSP programs which can perform the following tasks (you may create a single or multiple webpages for these tasks): 

(i) Write a JSP code to create a webpage that requires input of three variables x, y, and z; after successful input of values in the variables, the JSP program finds the smallest of these three variables. 7 The code then displays the smallest value along with a message. 

(ii) Create a web page for issuing a Book of a library. The page takes input of three fields namely membershipID, bookID and date of return of the book. In case, the data is correctly entered in all the three fields - two cookies one for the membershipID and the second for the bookID are created.


Ans:-  Here’s how you can create JSP programs to accomplish both tasks.


---


 (i) JSP Code to Find the Smallest of Three Variables


1. **Description**: This JSP code creates a webpage where users enter three variables: `x`, `y`, and `z`. The code then finds and displays the smallest of these three numbers along with a message.


2. **Code**:


```jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

    <title>Find the Smallest Number</title>

</head>

<body>

    <h2>Enter three numbers to find the smallest:</h2>

    <form action="" method="post">

        X: <input type="number" name="x" required><br><br>

        Y: <input type="number" name="y" required><br><br>

        Z: <input type="number" name="z" required><br><br>

        <input type="submit" value="Find Smallest">

    </form>


    <% 

        String xStr = request.getParameter("x");

        String yStr = request.getParameter("y");

        String zStr = request.getParameter("z");


        if (xStr != null && yStr != null && zStr != null) {

            int x = Integer.parseInt(xStr);

            int y = Integer.parseInt(yStr);

            int z = Integer.parseInt(zStr);


            int smallest = Math.min(x, Math.min(y, z));


            out.println("<h3>The smallest number among " + x + ", " + y + ", and " + z + " is: " + smallest + "</h3>");

        }

    %>

</body>

</html>

```


- **Explanation**: 

  - The user inputs values for `x`, `y`, and `z`.

  - After submission, the JSP script processes the inputs to find the smallest number using `Math.min`.

  - The smallest value is displayed along with a message.


---


 (ii) JSP Code for Library Book Issue with Cookies


1. **Description**: This code creates a library book issue page where the user enters `membershipID`, `bookID`, and `returnDate`. If the data is correctly entered, two cookies are created for `membershipID` and `bookID`.


2. **Code**:


```jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

    <title>Library Book Issue</title>

</head>

<body>

    <h2>Issue a Book</h2>

    <form action="" method="post">

        Membership ID: <input type="text" name="membershipID" required><br><br>

        Book ID: <input type="text" name="bookID" required><br><br>

        Date of Return: <input type="date" name="returnDate" required><br><br>

        <input type="submit" value="Issue Book">

    </form>


    <% 

        String membershipID = request.getParameter("membershipID");

        String bookID = request.getParameter("bookID");

        String returnDate = request.getParameter("returnDate");


        if (membershipID != null && bookID != null && returnDate != null) {

            // Creating cookies for membershipID and bookID

            javax.servlet.http.Cookie membershipCookie = new javax.servlet.http.Cookie("membershipID", membershipID);

            javax.servlet.http.Cookie bookCookie = new javax.servlet.http.Cookie("bookID", bookID);


            // Setting cookie max age to 7 days

            membershipCookie.setMaxAge(7 * 24 * 60 * 60);

            bookCookie.setMaxAge(7 * 24 * 60 * 60);


            // Adding cookies to response

            response.addCookie(membershipCookie);

            response.addCookie(bookCookie);


            out.println("<h3>Book has been successfully issued!</h3>");

            out.println("<p>Membership ID: " + membershipID + "</p>");

            out.println("<p>Book ID: " + bookID + "</p>");

            out.println("<p>Return Date: " + returnDate + "</p>");

        }

    %>

</body>

</html>

```


- **Explanation**:

  - The form collects the `membershipID`, `bookID`, and `returnDate`.

  - If all fields are entered, cookies are created for `membershipID` and `bookID`.

  - The cookies are set to expire in 7 days (`setMaxAge(7 * 24 * 60 * 60)`), and a success message is displayed along with the entered details.


---


Both JSP pages process user input effectively, with the first page calculating the smallest number and the second page creating cookies for the library book issue details.


d) Create a database for Book Sales System consisting of the following two tables: 

Book (ISBNnumber, Title, FirstAuthor, YearOfPublication, CopiesAcquired) 

Sales (ISBNnumber, PersonName, NumberofCopiesSold) 

Develop and deploy a web based “Book Sales System” using JSP, a database backend and a web server (you may select DBMS and web server, as per your choice). Your system should use JDBC for input of information to both the tables. The system should output list of all the sales made for a Book whose ISBNnumber is given. Submit the JSP program, screens and database of the system. You must demonstrate this system at the time of viva voce. 

Make and state suitable assumptions, if any.

Ans:-  To create a **Book Sales System** using JSP, JDBC, and a database (e.g., MySQL), we will set up the following:


1. **Database Schema** for the `Book` and `Sales` tables.

2. **JSP Pages** for entering book details and recording sales.

3. **JDBC Code** to handle database operations for adding entries and displaying sales records.

4. **Deployment** on a web server like Apache Tomcat.


Let’s break down each part.


---


 Step 1: Database Schema


We assume the DBMS is MySQL. Here’s the SQL code to create the required tables.


```sql

CREATE DATABASE BookSalesSystem;


USE BookSalesSystem;


CREATE TABLE Book (

    ISBNnumber VARCHAR(20) PRIMARY KEY,

    Title VARCHAR(100),

    FirstAuthor VARCHAR(100),

    YearOfPublication INT,

    CopiesAcquired INT

);


CREATE TABLE Sales (

    ISBNnumber VARCHAR(20),

    PersonName VARCHAR(100),

    NumberOfCopiesSold INT,

    FOREIGN KEY (ISBNnumber) REFERENCES Book(ISBNnumber)

);

```


### Step 2: JSP Pages for Book Entry and Sales Recording


1. **bookEntry.jsp** - Adds a new book to the `Book` table.

2. **recordSale.jsp** - Records a sale for a book in the `Sales` table.

3. **viewSales.jsp** - Displays all sales for a specified `ISBNnumber`.


---


 Step 3: JDBC Code in JSP


Ensure the MySQL JDBC driver (`mysql-connector-java.jar`) is added to the `lib` folder of your Tomcat server.


 1. bookEntry.jsp (Add a New Book)


```jsp

<%@ page import="java.sql.*" %>

<!DOCTYPE html>

<html>

<head>

    <title>Add Book</title>

</head>

<body>

    <h2>Enter Book Details</h2>

    <form action="" method="post">

        ISBN Number: <input type="text" name="ISBNnumber" required><br><br>

        Title: <input type="text" name="Title" required><br><br>

        First Author: <input type="text" name="FirstAuthor" required><br><br>

        Year of Publication: <input type="number" name="YearOfPublication" required><br><br>

        Copies Acquired: <input type="number" name="CopiesAcquired" required><br><br>

        <input type="submit" value="Add Book">

    </form>


    <% 

        if (request.getMethod().equalsIgnoreCase("POST")) {

            String ISBNnumber = request.getParameter("ISBNnumber");

            String title = request.getParameter("Title");

            String firstAuthor = request.getParameter("FirstAuthor");

            int yearOfPublication = Integer.parseInt(request.getParameter("YearOfPublication"));

            int copiesAcquired = Integer.parseInt(request.getParameter("CopiesAcquired"));


            try {

                Class.forName("com.mysql.jdbc.Driver");

                Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/BookSalesSystem", "root", "password");


                String query = "INSERT INTO Book (ISBNnumber, Title, FirstAuthor, YearOfPublication, CopiesAcquired) VALUES (?, ?, ?, ?, ?)";

                PreparedStatement pstmt = con.prepareStatement(query);

                pstmt.setString(1, ISBNnumber);

                pstmt.setString(2, title);

                pstmt.setString(3, firstAuthor);

                pstmt.setInt(4, yearOfPublication);

                pstmt.setInt(5, copiesAcquired);


                int rows = pstmt.executeUpdate();

                if (rows > 0) {

                    out.println("<p>Book added successfully!</p>");

                }


                con.close();

            } catch (Exception e) {

                e.printStackTrace();

            }

        }

    %>

</body>

</html>

```


---


 2. recordSale.jsp (Record a Sale)


```jsp

<%@ page import="java.sql.*" %>

<!DOCTYPE html>

<html>

<head>

    <title>Record Sale</title>

</head>

<body>

    <h2>Record a Sale</h2>

    <form action="" method="post">

        ISBN Number: <input type="text" name="ISBNnumber" required><br><br>

        Buyer Name: <input type="text" name="PersonName" required><br><br>

        Number of Copies Sold: <input type="number" name="NumberofCopiesSold" required><br><br>

        <input type="submit" value="Record Sale">

    </form>


    <% 

        if (request.getMethod().equalsIgnoreCase("POST")) {

            String ISBNnumber = request.getParameter("ISBNnumber");

            String personName = request.getParameter("PersonName");

            int numberOfCopiesSold = Integer.parseInt(request.getParameter("NumberofCopiesSold"));


            try {

                Class.forName("com.mysql.jdbc.Driver");

                Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/BookSalesSystem", "root", "password");


                String query = "INSERT INTO Sales (ISBNnumber, PersonName, NumberofCopiesSold) VALUES (?, ?, ?)";

                PreparedStatement pstmt = con.prepareStatement(query);

                pstmt.setString(1, ISBNnumber);

                pstmt.setString(2, personName);

                pstmt.setInt(3, numberOfCopiesSold);


                int rows = pstmt.executeUpdate();

                if (rows > 0) {

                    out.println("<p>Sale recorded successfully!</p>");

                }


                con.close();

            } catch (Exception e) {

                e.printStackTrace();

            }

        }

    %>

</body>

</html>

```


---


 3. viewSales.jsp (Display Sales Records by ISBN)


```jsp

<%@ page import="java.sql.*" %>

<!DOCTYPE html>

<html>

<head>

    <title>View Sales</title>

</head>

<body>

    <h2>View Sales for a Book</h2>

    <form action="" method="get">

        ISBN Number: <input type="text" name="ISBNnumber" required><br><br>

        <input type="submit" value="View Sales">

    </form>


    <% 

        String ISBNnumber = request.getParameter("ISBNnumber");


        if (ISBNnumber != null) {

            try {

                Class.forName("com.mysql.jdbc.Driver");

                Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/BookSalesSystem", "root", "password");


                String query = "SELECT PersonName, NumberofCopiesSold FROM Sales WHERE ISBNnumber = ?";

                PreparedStatement pstmt = con.prepareStatement(query);

                pstmt.setString(1, ISBNnumber);


                ResultSet rs = pstmt.executeQuery();


                if (!rs.isBeforeFirst()) {

                    out.println("<p>No sales found for ISBN: " + ISBNnumber + "</p>");

                } else {

                    out.println("<h3>Sales Records for ISBN " + ISBNnumber + ":</h3>");

                    out.println("<ul>");

                    while (rs.next()) {

                        out.println("<li>Buyer: " + rs.getString("PersonName") + " - Copies Sold: " + rs.getInt("NumberofCopiesSold") + "</li>");

                    }

                    out.println("</ul>");

                }


                con.close();

            } catch (Exception e) {

                e.printStackTrace();

            }

        }

    %>

</body>

</html>

```


Step 4: Deployment


1. Save the `.jsp` files in the web app directory (e.g., `webapps/BookSalesSystem` if using Apache Tomcat).

2. Ensure `mysql-connector-java.jar` is in the `lib` directory of Tomcat.

3. Start the server and access the JSP pages in the browser to enter book details, record sales, and view sales for specific ISBNs.


--- 


These JSP pages allow adding book details, recording sales, and retrieving sales data based on ISBN numbers. At the time of demonstration, input various values to test and verify that the data is stored and displayed accurately.

No comments: