XAVA
XAVA
CODE:
Database table creation:
CREATE TABLE users (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100),
email VARCHAR(100)
);
try {
Class.forName("com.mysql.cj.jdbc.Driver"); // Load the driver
Connection conn = DriverManager.getConnection(url, user, pass);
String query = "INSERT INTO users (name, email) VALUES (?, ?)";
PreparedStatement stmt = conn.prepareStatement(query);
stmt.setString(1, name);
stmt.setString(2, email);
stmt.close();
conn.close();
} catch (Exception e) {
out.println("<p style='color:red;'>Error: " + e.getMessage() + "</p>");
}
}
%>
<h2>Insert User</h2>
<form method="post" action="insert.jsp">
Name: <input type="text" name="name" required><br><br>
Email: <input type="email" name="email" required><br><br>
<input type="submit" value="Insert">
</form>
</body>
</html>
OUTPUT:
User input:
Name: [ ]
Email: [ ]
[ Insert ]
CODE:
Creating formValidation.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Form Validation</title>
<script>
// Client-side validation
function validateForm() {
var name = document.forms["userForm"]["name"].value;
var email = document.forms["userForm"]["email"].value;
var emailRegex = /^[^@]+@[^@]+\.[a-zA-Z]{2,}$/;
<%
// Server-side validation
String name = request.getParameter("name");
String email = request.getParameter("email");
boolean valid = true;
String errorMsg = "";
if (request.getMethod().equalsIgnoreCase("POST")) {
if (name == null || name.trim().equals("")) {
valid = false;
errorMsg += "Name is required.<br>";
}
if (email == null || !email.matches("^[^@]+@[^@]+\\.[a-zA-Z]{2,}$")) {
valid = false;
errorMsg += "Invalid email format.<br>";
}
if (valid) {
%>
<h3 style="color: green;">Form submitted successfully!</h3>
<p><strong>Name:</strong> <%= name %></p>
<p><strong>Email:</strong> <%= email %></p>
<%
} else {
%>
<h3 style="color: red;">Errors:</h3>
<p><%= errorMsg %></p>
<%
}
}
%>
<h2>User Form</h2>
<form name="userForm" method="post" action="formValidation.jsp"
onsubmit="return validateForm();">
Name: <input type="text" name="name" value="<%= (name != null) ? name :
"" %>"><br><br>
Email: <input type="text" name="email" value="<%= (email != null) ? email :
"" %>"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
OUTPUT:
Valid submission:
Form submitted successfully!
Name: Hanumanth
Email: [email protected]
EXPERIMENT-8
AIM: Write a program in java to show user validation using servlet.
SOFTWARE USED: VS CODE
THEORY:
What is User Validation?
User validation means checking whether the entered username and password
match with the records stored (either hardcoded or from a DB).
What is a Servlet?
A Servlet is a Java class used to handle requests and responses in a Java web
application. It runs on a server and responds to web client requests (usually
over HTTP).
CODE:
Creating login.html
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<h2>User Login</h2>
<form action="LoginServlet" 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>
Creating LoginServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// Hardcoded validation
if ("admin".equals(username) && "password123".equals(password)) {
out.println("<h3 style='color:green;'>Login Successful!</h3>");
} else {
out.println("<h3 style='color:red;'>Invalid Username or
Password</h3>");
}
out.close();
}
}
INPUT:
Username: admin
Password: password123
OUTPUT:
Login Successful!
CBS-1
AIM: Develop a small web program using servlets , JSPs with database
conncectivity.
SOFTWARE USED: VS CODE
THEORY:
What are Servlets?
Servlets are Java classes that handle HTTP requests and responses on a web
server. They sit between the client (browser) and the backend (database, logic,
etc.).
What is JSP (JavaServer Pages)?
JSP is a technology to create dynamically generated HTML based on Java code.
It's mostly used for UI.
JDBC (Java Database Connectivity)
JDBC is the standard API to connect Java applications with relational databases
like MySQL.
TECH STACK
Component Tool
Backend Servlet
Frontend JSP
Database MySQL
GOAL
Build a mini-app to:
Collect user info (name and email)
Insert it into the database
Display all users from the database
CODE:
Database Setup (MySQL):
CREATE DATABASE userdb;
USE userdb;
CREATE TABLE users (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100),
email VARCHAR(100)
);
JSP page(index.jsp)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>User Form</title></head>
<body>
<h2>Register User</h2>
<form method="post" action="insert">
Name: <input type="text" name="name" required /><br><br>
Email: <input type="email" name="email" required /><br><br>
<input type="submit" value="Submit" />
</form>
</body>
</html>
SERVLET(InsertUserServlet.java):
package com.example;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h2>User Inserted Successfully!</h2>");
out.println("<a href='index.jsp'>Back to form</a>");
}
}
DB Connection Utility (DBUtil.java):
package com.example;
import java.sql.*;
Class.forName("com.mysql.cj.jdbc.Driver"); // MySQL 8+
return DriverManager.getConnection(url, username, password);
}
}
Deployment Descriptor (web.xml):
<web-app xmlns="http://java.sun.com/xml/ns/javaee" version="3.0">
<servlet>
<servlet-name>InsertUserServlet</servlet-name>
<servlet-class>com.example.InsertUserServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>InsertUserServlet</servlet-name>
<url-pattern>/insert</url-pattern>
</servlet-mapping>
</web-app>
OUTPUT:
AFTER SUBMISSION:
<h2>User Inserted Successfully!</h2>
<a href='index.jsp'>Back to form</a>
CBS-2
AIM: Develop a small online quiz program using servlet and jsp.
SOFTWARE USED: VS CODE
THEORY:
What is an Online Quiz System?
An Online Quiz System is a web-based application that presents users with a
set of questions (usually multiple-choice), allows them to select answers, and
then calculates the total score based on correct responses. These systems are
commonly used in educational websites, competitive exams, and recruitment
platforms.
Technologies Used
1. JSP (JavaServer Pages):
JSP is a server-side technology that allows embedding Java code into HTML
pages using special tags. It is mainly used for displaying data and building user
interfaces. In this experiment, JSP is used to display the quiz questions and
collect the user’s answers via a form.
2. Servlets:
A Servlet is a Java class used to handle HTTP requests and responses. It runs on
the server and contains business logic. Here, the servlet processes the quiz
form submission, evaluates the answers, and returns the result to the user.
3. HTTP Protocol:
The quiz is submitted using the POST method, which is part of the HTTP
protocol. The Servlet uses HttpServletRequest to retrieve submitted answers
and HttpServletResponse to send back the score.
4. Web.xml (Deployment Descriptor):
This is the configuration file used in Java EE applications to map URLs to specific
servlets. It tells the server which class should handle requests to a particular
URL.
CODE:
Creating quiz.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<html>
<head>
<title>Online Quiz</title>
</head>
<body>
<h2>Simple Online Quiz</h2>
<form action="ResultServlet" method="post">
<p>1. What is the capital of France?</p>
<input type="radio" name="q1" value="Paris"> Paris<br>
<input type="radio" name="q1" value="London"> London<br>
<input type="radio" name="q1" value="Berlin"> Berlin<br>
int score = 0;
String q1 = request.getParameter("q1");
String q2 = request.getParameter("q2");
String q3 = request.getParameter("q3");
if ("Paris".equals(q1)) score++;
if ("James Gosling".equals(q2)) score++;
if ("Hyper Text Markup Language".equals(q3)) score++;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h2>Quiz Result</h2>");
out.println("<p>Your Score: " + score + "/3</p>");
if (score == 3) {
out.println("<p> Perfect! You nailed it!</p>");
} else if (score == 2) {
out.println("<p>Good job!</p>");
} else {
out.println("<p> Needs improvement. Give it another shot!</p>");
}
out.println("</body></html>");
}
}
Creating web.xml:
<web-app>
<servlet>
<servlet-name>ResultServlet</servlet-name>
<servlet-class>ResultServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ResultServlet</servlet-name>
<url-pattern>/ResultServlet</url-pattern>
</servlet-mapping>
</web-app>
SERVELT OUTPUT:
Quiz Result
Your Score: 3/3
Perfect! You nailed it!
Quiz Result
Your Score: 2/3
Good job!
Quiz Result
Your Score: 2/3
Good job!