0% found this document useful (0 votes)
17 views51 pages

Web Technology Lab File Vaibhav PDF

The document contains a series of experiments demonstrating various HTML, CSS, and JavaScript implementations. It includes code for creating simple web pages, forms, and a calculator, showcasing skills in web development. Each experiment is structured with code examples and outputs for educational purposes.

Uploaded by

Arav 2511
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views51 pages

Web Technology Lab File Vaibhav PDF

The document contains a series of experiments demonstrating various HTML, CSS, and JavaScript implementations. It includes code for creating simple web pages, forms, and a calculator, showcasing skills in web development. Each experiment is structured with code examples and outputs for educational purposes.

Uploaded by

Arav 2511
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 51

Experiment no -01

write a simple HTML code to display data/ content on a web page.


Code: -
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple HTML Page</title>
</head>
<body>

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


<p>This is a simple web page made using only HTML.</p>

<h2>About Me</h2>
<p>Hi! My name is Vaibhav Kaushik.</p>

<h2>My Hobbies</h2>
<ul>
<li>Reading Books</li>
<li>Playing Cricket</li>
<li>Web Development</li>
</ul>
<h2>Contact Information</h2>
<p>Email: [email protected]</p>
<p>Phone: +91 9368472986</p>

</body>
</html>

Output: -

Experiment no -02
Write a HTML code to display your CV on a web page. Write a HTML
code to implement the concept of frames with 2 frames: one for
hyperlink and another for opening the content to that link.

Code: -
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My CV</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
padding: 20px;
background-color: #f4f4f4;
}

.container {
max-width: 800px;
background: white;
padding: 20px;
border-radius: 10px;
box-shadow: 0px 0px 10px gray;
}

h1, h2 {
color: #333;
}

.profile-pic {
width: 132px;
height: 170px;
border-radius: 10px;
object-fit: cover;
display: block;
margin-bottom: 10px;
}

.contact, .education, .experience, .skills {


margin-top: 20px;
}
</style>
</head>
<body>
<div class="container">
<h1>Vaibhav Kaushik</h1>
<img src="vaibhavphoto.2.jpg" alt="Profile Picture" class="profile-pic">
<p><strong>Web Developer</strong></p>
<div class="contact">
<h2>Contact Information</h2>
<p>Email: [email protected]</p>
<p>Phone: 9368472986</p>
</div>

<div class="education">
<h2>Education</h2>
<p><strong>Bachelor's in Computer Science</strong></p>
<p>Galgotias University, 2022-2026</p>
</div>

<div class="experience">
<h2>Work Experience</h2>
<p><strong>Front-End Developer</strong> - ABC Tech</p>
<p>June 2025 - Present</p>
<ul>
<li>Developed responsive web applications.</li>
<li>Optimized website performance.</li>
</ul>
</div>

<div class="skills">
<h2>Skills</h2>
<ul>
<li>HTML, CSS, JavaScript</li>
<li>React, Angular</li>
<li>Python, Django</li>
</ul>
</div>
</div>
</body>
</html>

Output: -
Experiment -03
Implement CSS using all the ways of HTML.
Code: -
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Implementation in HTML</title>

<!-- Internal CSS -->


<style>
body {
background-color: #f4f4f4;
font-family: Arial, sans-serif; margin:
20px;
} h1
{ color: blue;
text-align: center;
}
.internal-style {
color: green; font-
weight: bold;
}
</style>
<!-- Linking External CSS -->
<link rel="stylesheet" href="styles.css">
</head>
<body>

<!-- Inline CSS -->


<h1 style="color: red; text-decoration: underline;">This is an Inline Styled
Heading</h1>

<p class="internal-style">This paragraph is styled using Internal CSS.</p>

<p class="external-style">This paragraph is styled using External CSS.</p>

</body>
</html>

Style.css:-
.external-style {
font-size: 20px; color:
darkblue;
background-color: lightyellow;
padding: 10px; border: 2px
solid black;

Output: -

Experiment -04

Design HTML form for keeping student record and validate it


using java script.

Code: -
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Student Record Form</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0; padding: 20px;
}
.container {
width: 50%;
background: white;
padding: 20px;
border-radius: 10px; box-
shadow: 0px 0px 10px gray;
margin: auto;
} h2
{ text-align:
center; color:
#333;
} label
{ font-weight:
bold;
}
input, select, textarea {
width: 100%; padding:
8px; margin: 5px 0;
border: 1px solid #ddd;
border-radius: 5px;
}
button { width: 100%;
padding: 10px; background-
color: #28a745; color:
white;
border: none;
border-radius:
5px; font-size:
16px;
}
button:hover {
background-color: #218838;
}
.error
{ color: red;
font-size: 14px;
}
</style>
</head>
<body>

<div class="container">
<h2>Student Record Form</h2>
<form name="studentForm" onsubmit="return validateForm()">
<label for="name">Full Name:</label>
<input type="text" id="name" name="name">
<span class="error" id="nameError"></span>

<label for="email">Email:</label>
<input type="email" id="email" name="email">
<span class="error" id="emailError"></span>
<label for="age">Age:</label>
<input type="number" id="age" name="age" min="10" max="100">
<span class="error" id="ageError"></span>

<label>Gender:</label>
<input type="radio" name="gender" value="Male"> Male
<input type="radio" name="gender" value="Female"> Female
<span class="error" id="genderError"></span>

<label for="course">Course:</label>
<select id="course" name="course">
<option value="">Select a Course</option>
<option value="Computer Science">Computer Science</option>
<option value="Business Administration">Business
Administration</option>
<option value="Engineering">Engineering</option>
</select>
<span class="error" id="courseError"></span>

<label for="address">Address:</label>
<textarea id="address" name="address"></textarea>
<span class="error" id="addressError"></span>

<button type="submit">Submit</button>
</form>
</div>
<script>
function validateForm() {
let isValid = true;

// Clear previous errors


document.getElementById("nameError").innerHTML = "";
document.getElementById("emailError").innerHTML = "";
document.getElementById("ageError").innerHTML = "";
document.getElementById("genderError").innerHTML = "";
document.getElementById("courseError").innerHTML = "";
document.getElementById("addressError").innerHTML = "";

let name = document.forms["studentForm"]["name"].value;


let email = document.forms["studentForm"]["email"].value; let
age = document.forms["studentForm"]["age"].value; let gender
= document.forms["studentForm"]["gender"].value; let course =
document.forms["studentForm"]["course"].value; let address =
document.forms["studentForm"]["address"].value;

// Name validation (required, min 3 chars)


if (name === "" || name.length < 3) {
document.getElementById("nameError").innerHTML = "Name must be
at least 3 characters.";
isValid = false;
}
// Email validation (required, proper format)
let emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if (email === "" || !emailPattern.test(email)) {
document.getElementById("emailError").innerHTML = "Enter a valid
email address.";
isValid = false;
}

// Age validation (required, 10-100)


if (age === "" || age < 10 || age > 100) {
document.getElementById("ageError").innerHTML = "Age must be
between 10 and 100."; isValid = false;
}

// Gender validation (must select one)


if (!document.querySelector('input[name="gender"]:checked')) {
document.getElementById("genderError").innerHTML = "Please select a
gender.";
isValid = false;
}

// Course validation (must select one)


if (course === "") {
document.getElementById("courseError").innerHTML = "Please select
a course.";
isValid = false;
}
// Address validation (required, min 10 chars)
if (address === "" || address.length < 10) {
document.getElementById("addressError").innerHTML = "Address
must be at least 10 characters.";
isValid = false;
}

return isValid;
}
</script>

</body>
</html>

Output: -
Experiment -05
Complete Web page with HTML and CSS using bootstrap.

Code: -
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Bootstrap Web Page</title>
<link
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.cs
s" rel="stylesheet">
<style>
body {
background-color: #f8f9fa;
}
.hero-section {
background: url('https://source.unsplash.com/1600x900/?nature')
norepeat center center; background-size: cover;
height: 400px;
display: flex; align-
items: center;
justify-content: center;
color: white;
text-shadow: 2px 2px 10px rgba(0, 0, 0, 0.7);
}
</style>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container">
<a class="navbar-brand" href="#">My Website</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse"
data-bs-target="#navbarNav">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav ms-auto">
<li class="nav-item"><a class="nav-link" href="#">Home</a></li>
<li class="nav-item"><a class="nav-link"
href="#about">About</a></li>
<li class="nav-item"><a class="nav-link"
href="#contact">Contact</a></li>
</ul>
</div>
</div>
</nav>
<header class="hero-section">
<h1>Welcome to My Website</h1>
</header>

<div class="container mt-5">


<div class="row">
<div class="col-md-4">
<div class="card">
<img src="https://source.unsplash.com/400x300/?technology"
class="card-img-top" alt="Tech">
<div class="card-body">
<h5 class="card-title">Technology</h5>
<p class="card-text">Latest trends in technology and
innovation.</p>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card">
<img src="https://source.unsplash.com/400x300/?business"
class="card-img-top" alt="Business">
<div class="card-body">
<h5 class="card-title">Business</h5>
<p class="card-text">Insights on business and
entrepreneurship.</p>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card">
<img src="https://source.unsplash.com/400x300/?travel"
class="card-img-top" alt="Travel">
<div class="card-body">
<h5 class="card-title">Travel</h5>
<p class="card-text">Explore beautiful destinations
worldwide.</p>
</div>
</div>
</div>
</div>
</div>

<footer class="bg-dark text-white text-center py-3 mt-5">


&copy; 2025 My Website | Designed with Bootstrap
</footer>

<script
src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.m
in.js"></script>
</body>
</html>
Output: -

Experiment -06

Write a Java Script to design a simple calculator to perform the


following operations: sum,product,difference and quotient.
Code:-
<script> function
add()
{
const v1 = document.querySelector("#val1").value;
const v2 = document.querySelector("#val2").value;
document.querySelector("#ans").value = parseFloat(v1)+parseFloat(v2);
}
function sub()
{
const v1 = document.querySelector("#val1").value;
const v2 = document.querySelector("#val2").value;
document.querySelector("#ans").value = v1-v2;
}
function mul()
{
const v1 = document.querySelector("#val1").value;
const v2 = document.querySelector("#val2").value;
document.querySelector("#ans").value = v1*v2;
}
function div()
{
const v1 = document.querySelector("#val1").value;
const v2 = document.querySelector("#val2").value; if(v2!
=0)
document.querySelector("#ans").value = v1/v2;
else
{
document.querySelector("#ans").value = 0;
alert('Divide by Zero error');
}
}
function cls()
{
document.querySelector("#val1").value = 0;
document.querySelector("#val2").value = 0;
document.querySelector("#ans").value = 0;
}
</script>
<table border=10 align=center>
<tr>
<th colspan=4 style="text-align:center;">Simple Calculator</th>
</tr>
<tr>
<td>Value1</td>
<td colspan=3><input type="number" id="val1" value="0"></td>
</tr>
<tr>
<td>Value2</td>
<td colspan=3><input type="number" id="val2" value="0"></td>
</tr>
<tr>
<td>Answer</td>
<td colspan=2><input type="number" value="0" id="ans" disabled></td>
<td><input type="button" value="C / CE" onclick="cls()"></td>
</tr>
<tr>
<td><input type="button" value="Addition" onclick="add()"></td>
<td><input type="button" value="Subtraction"
onclick="sub()"></td>
<td><input type="button" value="Multiplication"
onclick="mul()"></td>
<td><input type="button" value="Division" onclick="div()"></td>
</tr>
</table>
Output: -

Experiment -07

Write a program to implement AJAX.


Code: -
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AJAX Example</title>
</head>
<body>
<h2>AJAX Demo</h2>

<button onclick="loadData()">Get Data</button>


<div id="result"></div>

<script>
function loadData() {
// Create an XMLHttpRequest object
var xhttp = new XMLHttpRequest(); //
Define what happens when the response is
loaded xhttp.onload = function() {
if (this.status === 200) {
// Update the result div with response
document.getElementById("result").innerHTML = this.responseText;
}
};

// Open the request (method, url, async)


xhttp.open("GET", "data.php", true);

// Send the request


xhttp.send();
}
</script>
</body>
</html>
Output: -

Experiment -08

Implementation of JSP to generate server side response Write a JSP


code to generate dynamic webpage using server response Write a
code to create a navigation bar using Bootstrap and create a
responsive website for your Institute.

Code: -
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="java.util.Date" %>
<%
String instituteName = "Global Institute of Technology";
Date now = new Date();
%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title><%= instituteName %></title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CDN -->
<link
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.cs
s" rel="stylesheet">
</head>
<body>
<!-- Navigation Bar -->
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
<div class="container-fluid">
<a class="navbar-brand" href="#"><%= instituteName %></a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse"
data-bs-target="#navbarNav">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav ms-auto">
<li class="nav-item">
<a class="nav-link active" href="#home">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#about">About</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#contact">Contact</a>
</li>
</ul>
</div>
</div>
</nav>

<!-- Main Content -->


<div class="container mt-4">
<div class="text-center">
<h1>Welcome to <%= instituteName %></h1>
<p>Current server time: <%= now.toString() %></p>
</div>

<section id="home" class="mt-5">


<h2>Home</h2>
<p>This is the homepage of our institute. Stay tuned for updates.</p>
</section>

<section id="about" class="mt-5">


<h2>About Us</h2>
<p>We provide quality education in engineering, science, and
management.</p>
</section>

<section id="contact" class="mt-5 mb-5">


<h2>Contact</h2>
<p>Email: [email protected]</p>
<p>Phone: +91 12345 67890</p>
</section>
</div>

<!-- Bootstrap JS CDN -->


<script
src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.m
in.js"></script>
</body>
</html>

Output:-

Experiment -09
Write a program in jquery to click the button and display the
content.

Code:-
<!DOCTYPE html>
<html>
<head>
<title>jQuery Button Click and display the content</title>
<!-- Include jQuery library (via CDN) -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
#content {
display: none; /* Hidden by default */ margin-
top: 10px;

color: green; font-


weight: bold;
}
</style>
</head>
<body>

<button id="showBtn">Click Me!</button>

<div id="content">Thank you</div>

<script>
$(document).ready(function() {
$("#showBtn").click(function() {
$("#content").show(); // Show the hidden content
});
});
</script>
</body>
</html>

Output:-

Experiment -10
Design a Web Page using Jquery Selectors.

Code:-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery Selectors Demo</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f2f2f2;
padding: 20px;
}
.highlight {
background-color: yellow;
}
.info {
color: green;
}
</style>
</head>
<body>

<h1 id="mainTitle">jQuery Selector Example</h1>

<p class="info">This is a paragraph with class "info".</p>


<p>This is a normal paragraph.</p>

<input type="text" id="nameInput" placeholder="Enter your name">


<button id="submitBtn">Submit</button>

<br><br>

<a href="#" data-toggle="info">Toggle Info Class</a>

<script>
$(document).ready(function () {
// ID selector
$('#submitBtn').click(function () {
let name = $('#nameInput').val();
alert('Hello, ' + name + '!');
});

// Element selector
$('p').hover(function () {
$(this).addClass('highlight');
}, function () {
$(this).removeClass('highlight');
});

// Class selector $
('.info').click(function () { alert('You
clicked on an info paragraph.');
});

// Attribute selector
$('[data-toggle="info"]').click(function (e) {
e.preventDefault();
$('.info').toggleClass('highlight');
});
});
</script>

</body>
</html>

Output:

Experiment -11
11. Design a web page to create a button for to change button color,
show text, show image, and Reset Button using Jquery.

Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery Button Actions</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style> body { font-family: Arial, sans-serif;
padding: 20px; background-color: #f4f4f4;
}

button { margin: 10px; padding: 10px 20px; font-size: 16px;


cursor: pointer;
}

#outputText { margin-top: 20px; font-size: 18px; color: blue;


}

#outputImage { margin-top: 20px; display: none; max-width: 300px;


}

.color-changed { background-color: crimson; color: white;


}
</style>
</head>
<body>

<h2>jQuery Button Actions</h2>

<button id="changeColorBtn">Change My Color</button>


<button id="showTextBtn">Show Text</button>
<button id="showImageBtn">Show Image</button>
<button id="resetBtn">Reset</button>
<div id="outputText"></div>
<img id="outputImage" src="Screenshot 2025-05-29 000839.png">

<script>
$(document).ready(function () {
// Change button color
$('#changeColorBtn').click(function () {
$(this).toggleClass('color-changed');
});

// Show text
$('#showTextBtn').click(function () {
$('#outputText').text('Hello! My name is Vaibhav.');
});
// Show image
$('#showImageBtn').click(function () {
$('#outputImage').show();
});

// Reset all
$('#resetBtn').click(function () {
$('#changeColorBtn').removeClass('color-changed');
$('#outputText').text('');
$('#outputImage').hide();
});
});
</script>

</body>
</html>

Output:

Experiment -12
Write a program using SERVLET/ JSP and HTML to create a form and
display the details entered by the user.

Code:
1.form.html – Input Form
<!DOCTYPE html>
<html>
<head><title>User Form</title></head>
<body>
<h2>User Registration Form</h2>
<form action="submitForm" method="post">
Name: <input type="text" name="name" required><br><br>
Email: <input type="email" name="email" required><br><br>
Gender:
<input type="radio" name="gender" value="Male"> Male
<input type="radio" name="gender" value="Female"> Female<br><br>
Country:
<select name="country">
<option value="India">India</option>
<option value="USA">USA</option>
<option value="UK">UK</option>
</select><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
2. FormServlet.java – Servlet to Handle Form Submission
import java.io.IOException; import javax.servlet.*; import
javax.servlet.http.*;

public class FormServlet extends HttpServlet {


protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
// Get form data
String name = request.getParameter("name");
String email = request.getParameter("email");
String gender = request.getParameter("gender");
String country = request.getParameter("country");

// Set attributes to forward to JSP


request.setAttribute("name", name);
request.setAttribute("email", email);
request.setAttribute("gender", gender);
request.setAttribute("country", country);

// Forward to JSP
RequestDispatcher dispatcher =
request.getRequestDispatcher("display.jsp");
dispatcher.forward(request, response);
}
}
3. display.jsp – Show Submitted Details
<%@ page language="java" %>
<html>
<head><title>User Details</title></head>
<body>
<h2>User Submitted Details</h2>
<p><strong>Name:</strong> <%= request.getAttribute("name") %></p>
<p><strong>Email:</strong> <%= request.getAttribute("email") %></p>
<p><strong>Gender:</strong> <%= request.getAttribute("gender") %></p>
<p><strong>Country:</strong> <%= request.getAttribute("country") %></p>
</body>
</html>

4. web.xml – Servlet Mapping


<web-app>
<servlet>
<servlet-name>FormServlet</servlet-name>
<servlet-class>FormServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>FormServlet</servlet-name>
<url-pattern>/submitForm</url-pattern>
</servlet-mapping>
</web-app>

Output:-
Experiment -13

13. Write simple SERVLET/JSP program to set cookies and read it.

Code:
1. JSP Page to Set Cookie (setcookie.jsp)
<%@ page language="java" %>
<html>
<head><title>Set Cookie</title></head>
<body>
<%
String userName = "JohnDoe";
Cookie cookie = new Cookie("username", userName);
cookie.setMaxAge(60 * 60); // 1 hour response.addCookie(cookie);
%>
<h3>Cookie has been set for user: <%= userName %></h3>
<a href="readcookie">Read Cookie</a>
</body>
</html>
2. Servlet to Read Cookie (ReadCookieServlet.java)
import java.io.IOException; import javax.servlet.*;
import javax.servlet.http.*;

public class ReadCookieServlet extends HttpServlet {


protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException
{ response.setContentType("text/html");
java.io.PrintWriter out = response.getWriter();

Cookie[] cookies = request.getCookies();


String user = "Not Found";

if (cookies != null) { for (Cookie cookie :


cookies) { if
("username".equals(cookie.getName())) {
user = cookie.getValue(); break;
}
}
}

out.println("<html><body>");
out.println("<h3>Cookie Retrieved: " + user + "</h3>");
out.println("</body></html>");
}
}
3. web.xml Configuration
<web-app>
<servlet>
<servlet-name>ReadCookieServlet</servlet-name>
<servlet-class>ReadCookieServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>ReadCookieServlet</servlet-name>
<url-pattern>/readcookie</url-pattern>
</servlet-mapping>
/web-app>

Output:
Experiment -14
14.Create a SERVLET/JSP/JSP page for login system using session.

Code:-
1. login.jsp – User Login Page
<%@ page language="java" %>
<html>
<head><title>Login Page</title></head>
<body>
<h2>Login</h2>
<form action="login" method="post">
Username: <input type="text" name="username" required><br><br>
Password: <input type="password" name="password" required><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>
2.LoginServlet.java – Handles Login Logic
import java.io.IOException; import
javax.servlet.*; import
javax.servlet.http.*;

public class LoginServlet extends HttpServlet {


protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {

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


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

// Simple static validation (replace with DB validation in real systems)


if ("admin".equals(username) && "1234".equals(password))
{ HttpSession session = request.getSession();
session.setAttribute("username", username);
response.sendRedirect("welcome.jsp");
} else {
response.setContentType("text/html");
response.getWriter().println("<h3>Invalid credentials!</h3>");
response.getWriter().println("<a href='login.jsp'>Try Again</a>");
}
}
}

3. welcome.jsp – Page After Successful Login


<%@ page language="java" %>
<%
HttpSession session = request.getSession(false);
String user = (session != null) ? (String) session.getAttribute("username") :
null;
if (user == null) {
response.sendRedirect("login.jsp");
return;
}
%>
<html>
<head><title>Welcome</title></head>
<body>
<h2>Welcome, <%= user %>!</h2>
<a href="logout.jsp">Logout</a>
</body>
</html>
4. logout.jsp – (Optional) Logout Page
<%@ page language="java" %>
<%
session.invalidate();
response.sendRedirect("login.jsp");%>
5. web.xml – Servlet Configuration
<web-app>
<servlet>
<servlet-name>LoginServlet</servlet-name> <servlet-
class>LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>

Output:-

Experiment -15

15.Write a SERVLET/JSP/JSP program for sending e-mail.


Code:-
1.emailform.jsp – JSP Input Form
<%@ page language="java" %>
<html>
<head><title>Send Email</title></head>
<body>
<h2>Send Email</h2>
<form action="sendemail" method="post">
To: <input type="email" name="to" required><br><br>
Subject: <input type="text" name="subject" required><br><br>
Message:<br>
<textarea name="message" rows="5" cols="40"
required></textarea><br><br>
<input type="submit" value="Send Email">
</form>
</body>
</html>
2.SendEmailServlet.java – Servlet to Send Email
import jakarta.servlet.*; import
jakarta.servlet.http.*; import jakarta.mail.*;
import jakarta.mail.internet.*;

import java.io.IOException; import


java.util.Properties;

public class SendEmailServlet extends HttpServlet {


protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {

String to = request.getParameter("to");
String subject = request.getParameter("subject");
String messageText = request.getParameter("message");

// SMTP config (Gmail example)


String from = "[email protected]"; // your email
String password = "yourapppassword"; // App-specific password
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");

Session mailSession = Session.getInstance(props, new Authenticator() {


protected PasswordAuthentication getPasswordAuthentication()
{ return new PasswordAuthentication(from, password);
}
}); try
{
Message message = new MimeMessage(mailSession);
message.setFrom(new InternetAddress(from));
message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(subject);
message.setText(messageText);

Transport.send(message);
request.setAttribute("status", "Email sent successfully!");
} catch (MessagingException e) {
e.printStackTrace();
request.setAttribute("status", "Email sending failed: " + e.getMessage());
}
RequestDispatcher dispatcher =
request.getRequestDispatcher("status.jsp");
dispatcher.forward(request, response);
}
}
3.status.jsp – Display Result
<%@ page language="java" %>
<html>
<head><title>Status</title></head>
<body>
<h2><%= request.getAttribute("status") %></h2>
<a href="emailform.jsp">Send Another Email</a>
</body>
</html>
4.web.xml – Servlet Mapping
<web-app>
<servlet>
<servlet-name>SendEmailServlet</servlet-name>
<servlet-class>SendEmailServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>SendEmailServlet</servlet-name>
<url-pattern>/sendemail</url-pattern>
</servlet-mapping>
</web-app>

Output:-

You might also like