0% found this document useful (0 votes)
2 views

XAVA

The document outlines several experiments involving JSP and Servlets for web application development, focusing on data insertion, form validation, user authentication, and an online quiz system. It includes detailed steps and code snippets for creating HTML forms, establishing database connections, and handling user input. The experiments aim to demonstrate the use of Java technologies in building dynamic web applications with database connectivity.

Uploaded by

Suhana
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

XAVA

The document outlines several experiments involving JSP and Servlets for web application development, focusing on data insertion, form validation, user authentication, and an online quiz system. It includes detailed steps and code snippets for creating HTML forms, establishing database connections, and handling user input. The experiments aim to demonstrate the use of Java technologies in building dynamic web applications with database connectivity.

Uploaded by

Suhana
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

EXPERIMENT-6

AIM: Write a program to insert data into a table using jsp.


SOFTWARE USED: VS CCODE
THEORY: JavaServer Pages (JSP) is a server-side technology used to create
dynamic web applications. It allows embedding Java code directly into HTML
pages to perform backend operations such as interacting with a database.
To insert data into a database table using JSP, the following steps are typically
followed:
1. Designing the HTML Form
An HTML form is created within a JSP page to collect user input. The form uses
the POST method and sends the data to the same or another JSP page for
processing.
2. Retrieving Form Data
When the form is submitted, the input values are retrieved in the JSP page
using the request.getParameter() method.
3. Establishing Database Connection
JSP uses JDBC (Java Database Connectivity) to connect with the database. The
database driver is loaded using Class.forName(), and a connection is
established using DriverManager.getConnection().
4. Executing SQL Insert Query
A PreparedStatement object is used to prepare and execute an INSERT SQL
query. Prepared statements help prevent SQL injection and ensure better
performance.
5. Closing Resources
After executing the query, it is important to close the PreparedStatement and
Connection objects to free up resources.

CODE:
Database table creation:
CREATE TABLE users (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100),
email VARCHAR(100)
);

Creating JSP page:


<%@ page import="java.sql.*" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Insert User</title>
</head>
<body>
<%
String name = request.getParameter("name");
String email = request.getParameter("email");
boolean inserted = false;

if (name != null && email != null) {


// JDBC connection setup
String url = "jdbc:mysql://localhost:3306/your_database_name";
String user = "your_username";
String pass = "your_password";

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);

int rows = stmt.executeUpdate();


if (rows > 0) {
inserted = true;
}

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>

<% if (inserted) { %>


<p style="color:green;">User inserted successfully!</p>
<% } %>

</body>
</html>

 Put the MySQL JDBC driver (mysql-connector-j.jar) in your project’s lib


folder or add it to your classpath.
 Replace your_database_name, your_username, and your_password with
actual values.

OUTPUT:
User input:
Name: [ ]
Email: [ ]
[ Insert ]

After Submitting the Form (POST Request)


Let’s say you type:
 Name: Hanumanth
 Email: [email protected]
Then click "Insert".
EXPERIMENT -7
AIM: Write a jsp program to implement form data validation.
SOFTWARE USED: VS CODE
THEORY: Form data validation ensures that the user inputs valid and expected
data before it's processed or stored. The validation helps prevent:
 Inserting garbage data into databases
 Application crashes due to unexpected input
 Security issues (like SQL injection, XSS)
Types of validation:
1. Client-side Validation (JavaScript):
o Happens in the browser.
o Fast, but not secure (users can disable JS).
2. Server-side Validation (JSP/Servlet):
o Happens on the server.
o Slower, but secure and necessary for reliable data processing.
We’ll create a form that accepts:
 Name (must not be empty)
 Email (must be valid format)
We’ll do both client-side and server-side validation in one JSP file
(formValidation.jsp).

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,}$/;

if (name.trim() === "") {


alert("Name is required.");
return false;
}
if (!emailRegex.test(email)) {
alert("Invalid email format.");
return false;
}
return true;
}
</script>
</head>
<body>

<%
// 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).

Flow of User Validation using Servlet


1. User opens an HTML login page.
2. User enters username and password.
3. Form is submitted to a Servlet.
4. Servlet validates credentials (hardcoded or DB).
5. Servlet responds with either:
o "Login Successful"
o "Invalid Credentials"

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;

@WebServlet("/LoginServlet") // URL mapping


public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();

// Get values from form


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

// 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

Web Container Apache Tomcat

IDE Eclipse / IntelliJ (recommended)

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.*;

public class InsertUserServlet extends HttpServlet {


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

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


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

try (Connection conn = DBUtil.getConnection()) {


String sql = "INSERT INTO users (name, email) VALUES (?, ?)";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, name);
stmt.setString(2, email);
stmt.executeUpdate();
} catch (Exception e) {
throw new ServletException("DB Error: " + e.getMessage());
}

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.*;

public class DBUtil {


public static Connection getConnection() throws Exception {
String url = "jdbc:mysql://localhost:3306/userdb";
String username = "root"; // your db username
String password = "yourpassword"; // your db password

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.

Working of the Quiz System


1. User Interface (quiz.jsp):
o A JSP file displays the quiz containing multiple-choice questions.
o Each question has radio buttons, allowing the user to choose one
answer.
o When the user clicks the Submit button, the form is submitted to
the Servlet using the POST method.
2. Form Submission:
o The form data (selected answers) is sent to the server.
o The request is mapped to a specific Servlet (e.g., ResultServlet)
using web.xml.
3. Servlet Processing (ResultServlet.java):
o The Servlet retrieves the user's selected answers using
request.getParameter().
o It compares the answers against a predefined set of correct
answers.
o A score is calculated based on how many answers are correct.
4. Display of Result:
o The Servlet generates an HTML response dynamically using
PrintWriter.
o The user’s score is displayed along with a message based on their
performance.
Advantages of Using Servlet and JSP for Quizzes
 Separation of Concerns: JSP handles the view, while Servlets handle
business logic.
 Secure: Since logic is on the server, it’s harder for users to manipulate
scores.
 Scalable: Easily extendable to add more questions, sessions, database
support, etc.
 Web-based: No installation needed — accessible through a browser.
Real-World Applications
 Online assessments in colleges and coaching centers.
 Preliminary tests for hiring processes.
 E-learning platforms like Udemy, Coursera, and Skillshare.
 Self-evaluation modules in school and university websites.

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>

<p>2. Who invented Java?</p>


<input type="radio" name="q2" value="James Gosling"> James
Gosling<br>
<input type="radio" name="q2" value="Guido van Rossum"> Guido van
Rossum<br>
<input type="radio" name="q2" value="Dennis Ritchie"> Dennis
Ritchie<br>

<p>3. What does HTML stand for?</p>


<input type="radio" name="q3" value="Hyper Text Markup Language">
Hyper Text Markup Language<br>
<input type="radio" name="q3" value="High Text Machine Language">
High Text Machine Language<br>
<input type="radio" name="q3" value="Home Tool Markup Language">
Home Tool Markup Language<br><br>

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


</form>
</body>
</html>
Creating ResultServlet.java:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ResultServlet extends HttpServlet {


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

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!

You might also like