SERVLET SESSION TRACKING:
PROGRAM:
[Link]
<!DOCTYPE html>
<html>
<head>
<title>Session Login</title>
<style>
.box{
border:5px solid white;
margin-top:8rem;
margin-left:25rem;
width:500px;
height:200px;
text-align:centre;
border-radius:100rem;
}
.in{
margin-left:3rem;
border-radius:5px;
width:70px;
height:30px;
}
</style>
</head>
<body style="background-color:black;color:white">
<div class="box">
<h1>User Login</h1>
<form action="login" method="post">
Username: <input type="text" name="username" required><br><br>
<input class="in" style="background-color:blue;color:white" type="submit"
value="Login">
</form>
</div>
</body>
</html>
[Link]:
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
String username = [Link]("username");
// 1. Create or retrieve the existing session.
// [Link]() defaults to true, creating a new session if one doesn't exist.
HttpSession session = [Link]();
// 2. Store the data (username) in the session object
[Link]("user", username);
[Link]("<html><body>");
[Link]("<h2>Welcome, " + username + "!</h2>");
[Link]("<p>Session Created! Your Session ID: **" + [Link]() + "**</p>");
[Link]("<a href='profile'>Go to Profile Page</a>"); // Link to next servlet
[Link]("</body></html>");
}
}
[Link]:
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@WebServlet("/profile")
public class ProfileServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
// 1. Get the existing session, but DONT create a new one (false)
HttpSession session = [Link](false);
if (session != null) {
// 2. Retrieve the stored attribute from the session
String username = (String) [Link]("user");
if (username != null) {
[Link]("<html><body>");
[Link]("<h2>Welcome back, " + username + "! (Session Active)</h2>");
[Link]("<p>This page confirms successful session tracking.</p>");
[Link]("<a href='logout'>Logout</a>");
[Link]("</body></html>");
} else {
[Link]("<h1>Session Active, but User Data Not Found!</h1>");
}
} else {
[Link]("<h1>No Session Found! Please Login.</h1>");
[Link]("<a href='[Link]'>Go to Login Page</a>");
}
}
}
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@WebServlet("/logout")
public class LogoutServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html");
HttpSession session = [Link](false);
PrintWriter out = [Link]();
if(session!=null) {
String username = (String) [Link]("user");
[Link]();
if(username!=null) {
[Link]("<h1>"+username+",You have been successfully logged
out!</h1>");
}
}
}
}
OUTPUT:
AJAX:
PROGRAM:
Ajaz_quiz.html:
<!DOCTYPE html>
<html>
<head>
<title>AJAX JDBC Quiz</title>
<style>
body { font-family: Arial, sans-serif; padding: 20px; }
#question-box { border: 1px solid #004d99; padding: 15px; margin-bottom: 20px; }
#nextBtn { padding: 10px 20px; cursor: pointer; }
</style>
</head>
<body>
<h1>AJAX Quiz</h1>
<p>Question: <span id="qNum">1</span></p>
<div id="question-box">
Loading question...
</div>
<button id="nextBtn" onclick="loadQuestion()">Next Question</button>
<div id="status"></div>
<script>
var currentQId = 1;
var totalQuestions = 3; // Must match your total count in the DB
function loadQuestion() {
if (currentQId > totalQuestions) {
[Link]('question-box').innerHTML = "<h2>Quiz
Finished!</h2>";
[Link]('nextBtn').disabled = true;
return;
}
[Link]('status').innerText = "Loading Q" + currentQId + "...";
[Link]('qNum').innerText = currentQId;
var xhr = new XMLHttpRequest();
// Construct the URL to call the Servlet, passing the current question ID
var url = "getQuestion?qId=" + currentQId;
[Link]('GET', url, true);
[Link] = function() {
if ([Link] === 4 && [Link] === 200) {
var qData = [Link]([Link]);
if ([Link]) {
[Link]('question-box').innerHTML = "Error: " +
[Link];
return;
}
// 1. Construct the HTML for the question and options
var html = '<strong>' + [Link] + '</strong><br><br>';
html += '<label><input type="radio" name="answer" value="1">' + qData.op1 +
'</label><br>';
html += '<label><input type="radio" name="answer" value="2">' + qData.op2 +
'</label><br>';
html += '<label><input type="radio" name="answer" value="3">' + qData.op3 +
'</label><br>';
// 2. Update the display
[Link]('question-box').innerHTML = html;
[Link]('status').innerText = "Question " + currentQId + "
loaded.";
// 3. Increment the ID for the next click
currentQId++;
} else if ([Link] === 4) {
[Link]('status').innerText = "Server error! Status: " +
[Link];
}
};
[Link]();
}
// Load the first question when the page loads
[Link] = loadQuestion;
</script>
</body>
</html>
[Link]:
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link].*;
Servlet implementation class QuizDataServlet
@WebServlet("/getQuestion")
public class QuizDataServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
final String DB_URL = "jdbc:mysql://localhost:3306/quiz_db";
final String USER = "root";
final String PASS = "7349";
[Link]("application/json");
[Link]("UTF-8");
PrintWriter out = [Link]();
String qIdParam = [Link]("qId");
int questionId = (qIdParam != null) ? [Link](qIdParam) : 1;
Connection conn = null;
PreparedStatement stmt = null;
String jsonResponse = "{}";
try {
[Link]("[Link]");
conn = [Link](DB_URL, USER, PASS);
String sql = "SELECT * FROM questions WHERE q_id = ?";
stmt = [Link](sql);
[Link](1, questionId);
ResultSet rs = [Link]();
if ([Link]()) {
jsonResponse = [Link](
"{\"id\":%d, \"text\":\"%s\", \"op1\":\"%s\", \"op2\":\"%s\", \"op3\":\"%s\"}",
[Link]("q_id"),
[Link]("question_text"),
[Link]("option1"),
[Link]("option2"),
[Link]("option3")
);
} else {
jsonResponse = "{\"error\": \"Question not found.\"}";
}
} catch (Exception e) {
[Link]("JDBC/SQL Error: " + [Link]());
jsonResponse = "{\"error\": \"Database connection error.\"}";
} finally {
try { if (stmt != null) [Link](); } catch (SQLException se) {}
try { if (conn != null) [Link](); } catch (SQLException se) {}
}
[Link](jsonResponse);
}
}
OUTPUT:
ANGULAR:
PROGRAM:
[Link]:
<div class="login-container">
<h2>Login</h2>
<!-- 🧠 Reactive Form -->
<form [formGroup]="loginForm" (ngSubmit)="onSubmit()">
<!-- Name Field -->
<label>Name</label>
<input
type="text"
formControlName="name"
[(ngModel)]="nameModel"
name="name"
[value]="defaultName"
/>
<div *ngIf="[Link]('name')?.invalid && [Link]('name')?.touched">
<small>Name is required.</small>
</div>
<div class="preview">
<p><strong>Live Name:</strong> {{ nameModel }}</p>
</div>
<!-- Password Field -->
<label>Password</label>
<input
type="password"
formControlName="password"
[(ngModel)]="passwordModel"
name="password"
[value]="defaultPassword"
/>
<div *ngIf="[Link]('password')?.invalid && [Link]('password')?.touched">
<small *ngIf="[Link]('password')?.errors?.['required']">Password is
required.</small>
<small *ngIf="[Link]('password')?.errors?.['minlength']">Password must be at
least 6 characters.</small>
</div>
<button type="submit" [disabled]="[Link]">Login</button>
</form>
<!-- Event-to-Attribute: input updates component property -->
<input type="text" placeholder="Type message" (input)="message = $[Link]" />
<p><strong>Live Message:</strong> {{ message }}</p>
<!-- Attribute-to-Event: inline assignment -->
<button (click)="message = 'Hello, ' + nameModel">Update Message</button>
<!-- 🔍 One-Way Binding Preview -->
<div class="preview">
<p><strong>Default Name:</strong> {{ defaultName }}</p>
<p><strong>Default Password:</strong> {{ defaultPassword }}</p>
</div>
<!-- 🔄 Two-Way Binding Preview -->
</div>
[Link]:
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-login-component',
standalone: false,
templateUrl: './[Link]',
styleUrl: './[Link]'
})
export class LoginComponent {
loginForm: FormGroup;
// Two-way binding variables
nameModel = '';
passwordModel = '';
// One-way binding values
defaultName = 'guest';
defaultPassword = '123456';
// Event-driven attribute
message = 'Welcome!';
// Stored credentials
users = [
{ name: 'mani', password: 'mani@123' },
{ name: 'bob', password: 'bob456' },
{ name: 'charlie', password: 'charlie789' }
];
constructor(private fb: FormBuilder) {
[Link] = [Link]({
name: ['', [Link]],
password: ['', [[Link], [Link](6)]]
});
}
onSubmit(): void {
const { name, password } = [Link];
const match = [Link](user => [Link] === name && [Link] ===
password);
alert(match ? 'Login successful' : 'Invalid credentials');
}
updateMessage(newMsg: string): void {
[Link] = newMsg;
}
}
[Link]:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
const routes: Routes = [];
@NgModule({
imports: [[Link](routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
[Link]:
import { NgModule, provideBrowserGlobalErrorListeners } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms'; // ✅ Import
FormsModule
import { AppRoutingModule } from './app-routing-module';
import { App } from './app';
import { LoginComponent } from './login-component/login-component';
@NgModule({
declarations: [
App,
LoginComponent
],
imports: [
BrowserModule,
AppRoutingModule,
ReactiveFormsModule,
FormsModule // ✅ Add this to enable ngModel
],
providers: [
provideBrowserGlobalErrorListeners()
],
bootstrap: [App]
})
export class AppModule { }
[Link]:
body {
background-image: url('[Link]
background-repeat: no-repeat; /* Prevents the image from repeating */
background-size: cover; /* Ensures the image covers the entire element */
background-position: center; /* Centers the image */
}
OUTPUT:
JSP QUIZ:
PROGRAM:
start_JDBC.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="[Link]" %>
<%@ page import="[Link].*" %>
<!DOCTYPE html>
<html>
<head>
<title>Online Quiz - JDBC</title>
<style>
body { font-family: Arial, sans-serif; padding: 20px; }
.question { margin-bottom: 20px; padding: 10px; border: 1px solid #004d99;
background-color: #e6f0ff; }
.score-info { color: #008000; font-weight: bold; }
</style>
</head>
<body>
<%
// --- 1. JDBC CONNECTION DETAILS ---
final String JDBC_DRIVER = "[Link]";
final String DB_URL = "jdbc:mysql://localhost:3306/quiz_db";
final String USER = "root"; // CHANGE THIS TO YOUR DB USERNAME
final String PASS = "7349"; // CHANGE THIS TO YOUR DB PASSWORD
// --- 2. SESSION VARIABLES ---
HttpSession currentSession = [Link](true);
Integer qIdObj = (Integer) [Link]("currentQId");
Integer scoreObj = (Integer) [Link]("score");
int currentQId = (qIdObj != null) ? [Link]() : 1; // Start with Q_ID 1
int score = (scoreObj != null) ? [Link]() : 0;
int maxQuestions = 3; // Total number of questions in your DB
// --- 3. ANSWER PROCESSING ---
String submittedAnswerIndex = [Link]("answer");
String lastQIdParam = [Link]("lastQId");
if (submittedAnswerIndex != null && lastQIdParam != null) {
int lastQId = [Link](lastQIdParam);
int submittedIndex = [Link](submittedAnswerIndex);
Connection conn = null;
PreparedStatement stmt = null;
try {
[Link](JDBC_DRIVER);
conn = [Link](DB_URL, USER, PASS);
// Retrieve the correct answer for the question the user just answered
stmt = [Link]("SELECT correct_option FROM questions WHERE
q_id = ?");
[Link](1, lastQId);
ResultSet rs = [Link]();
if ([Link]()) {
int correctIndex = [Link]("correct_option");
// Check if the submitted index matches the correct index
if (submittedIndex == correctIndex) {
score++;
}
}
} catch (Exception e) {
[Link]("Database Error during Answer Processing: " + [Link]());
} finally {
try { if (stmt != null) [Link](); } catch (SQLException se) {}
try { if (conn != null) [Link](); } catch (SQLException se) {}
}
}
// --- 4. NAVIGATION LOGIC ---
// Update question ID and score for the NEXT display cycle
if (submittedAnswerIndex != null) {
currentQId++;
}
[Link]("currentQId", currentQId);
[Link]("score", score);
// --- 5. DISPLAY LOGIC ---
if (currentQId <= maxQuestions) {
// Fetch and display the current question
Connection conn = null;
PreparedStatement stmt = null;
try {
[Link](JDBC_DRIVER);
conn = [Link](DB_URL, USER, PASS);
stmt = [Link]("SELECT * FROM questions WHERE q_id = ?");
[Link](1, currentQId);
ResultSet rs = [Link]();
if ([Link]()) {
%>
<h1>Online Quiz (JDBC) - Question <%= currentQId %> of <%= maxQuestions
%></h1>
<div class="question">
<p><strong><%= [Link]("question_text") %></strong></p>
<form action="start_jdbc.jsp" method="post">
<input type="hidden" name="lastQId" value="<%= currentQId %>">
<%
// Display options dynamically (1-based indexing for simplicity)
for (int i = 1; i <= 3; i++) {
%>
<label style="margin-right: 20px;">
<input type="radio" name="answer" value="<%= i %>" required>
<%= [Link]("option" + i) %>
</label>
<%
}
%>
<br><br>
<input type="submit" value="Submit Answer">
</form>
</div>
<p class="score-info">Current Score: <%= score %></p>
<%
} else {
[Link]("<h1>Error: Question ID " + currentQId + " not found in
database.</h1>");
}
} catch (Exception e) {
[Link]("<h2>Database Connection/Query Error:</h2><p>" + [Link]() +
"</p>");
} finally {
try { if (stmt != null) [Link](); } catch (SQLException se) {}
try { if (conn != null) [Link](); } catch (SQLException se) {}
}
} else {
// --- 6. QUIZ END: DISPLAY FINAL RESULT ---
%>
<h1>Quiz Completed!</h1>
<div class="final-score">
Your Final Score: <%= score %> / <%= maxQuestions %>
</div>
<p>Thank you for participating!</p>
<a href="start_jdbc.jsp" onclick="[Link]()">Start New Quiz</a>
<%
// Invalidate the session to reset the score and index
if (currentSession != null) {
[Link]();
}
%>
<%
}
%>
</body>
</html>
OUTPUT:
XSLT:
PROGRAM:
[Link]
<?xml-stylesheet type = "text/xsl" href = "[Link]"?>
<products>
<product id="P001">
<name>Laptop Pro</name>
<category>Electronics</category>
<price>1200.00</price>
</product>
<product id="P002">
<name>Mechanical Keyboard</name>
<category>Accessories</category>
<price>150.50</price>
</product>
<product id="P003">
<name>4K Monitor 27"</name>
<category>Electronics</category>
<price>450.99</price>
</product>
<product id="P004">
<name>Wireless Mouse</name>
<category>Accessories</category>
<price>35.75</price>
</product>
</products>
[Link]
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="[Link]
<xsl:template match="/products">
<html>
<head>
<title>Product List</title>
<style type="text/css">
body { font-family: Arial, sans-serif; margin: 20px; background-color: #f4f4f9; }
h1 { color: #333; }
table {
width: 80%;
border-collapse: collapse;
margin: 25px 0;
font-size: 1em;
min-width: 400px;
box-shadow: 0 0 20px rgba(0, 0, 0, 0.15);
background-color: white;
margin-left: auto;
margin-right: auto;
}
thead tr {
background-color: #009879;
color: #ffffff;
text-align: left;
}
th, td {
padding: 12px 15px;
border: 1px solid #dddddd;
}
tbody tr {
border-bottom: 1px solid #dddddd;
}
tbody tr:nth-of-type(even) {
background-color: #f3f3f3;
}
tbody tr:last-of-type {
border-bottom: 2px solid #009879;
}
</style>
</head>
<body>
<h1>Product Inventory (Sorted by Name)</h1>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Category</th>
<th>Price ($)</th>
</tr>
</thead>
<tbody>
<xsl:apply-templates select="product">
<xsl:sort select="name" order="ascending" data-type="text"/>
</xsl:apply-templates>
</tbody>
</table>
</body>
</html>
</xsl:template>
<xsl:template match="product">
<tr>
<td><xsl:value-of select="@id"/></td>
<td><xsl:value-of select="name"/></td>
<td><xsl:value-of select="category"/></td>
<td><xsl:value-of select="format-number(price, '0.00')"/></td>
</tr>
</xsl:template>
</xsl:stylesheet>
OUTPUT:
XML SCHEMA:
PROGRAM:
[Link]
<?xml-stylesheet type = "text/xsl" href = "[Link]"?>
<products xmlns:xsi="[Link]
xsi:noNamespaceSchemaLocation="[Link]
<product id="P001">
<name>Laptop Pro</name>
<category>Electronics</category>
<price>1200.00</price>
</product>
<product id="P002">
<name>Mechanical Keyboard</name>
<category>Accessories</category>
<price>150.50</price>
</product>
<product id="P003">
<name>4K Monitor 27"</name>
<category>Electronics</category>
<price>450.99</price>
</product>
<product id="P004">
<name>Wireless Mouse</name>
<category>Accessories</category>
<price>35.75</price>
</product>
</products>
[Link]
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="[Link]
<xs:element name="category">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value="Accessories"/>
<xs:enumeration value="Electronics"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name="name">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value="4K Monitor 27""/>
<xs:enumeration value="Laptop Pro"/>
<xs:enumeration value="Mechanical Keyboard"/>
<xs:enumeration value="Wireless Mouse"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name="price">
<xs:simpleType>
<xs:restriction base="xs:decimal">
<xs:enumeration value="1200"/>
<xs:enumeration value="150.5"/>
<xs:enumeration value="35.75"/>
<xs:enumeration value="450.99"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name="product">
<xs:complexType>
<xs:sequence>
<xs:element ref="name"/>
<xs:element ref="category"/>
<xs:element ref="price"/>
</xs:sequence>
<xs:attribute name="id" use="required">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value="P001"/>
<xs:enumeration value="P002"/>
<xs:enumeration value="P003"/>
<xs:enumeration value="P004"/>
</xs:restriction>
</xs:simpleType>
</xs:attribute>
</xs:complexType>
</xs:element>
<xs:element name="products">
<xs:complexType>
<xs:sequence>
<xs:element ref="product" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element></xs:schema>
OUTPUT: