prac -1C(registration servlet )
database
1. Open MySQL Command Line Client.
2. Create database: create database database_name;
3. Using the database: use database_name;
4. Create table: create table user(username varchar(20) PRIMARY KEY, password
varchar(20), email varchar(50), country varchar(20));
5. Insert data into table: insert into user values
('sophia','spd@24',’dcruzsophia24@gmail.com','India');
6. View data: select * from user;
7. Now open Netbeans. File – New Project – Java Web – Web Application. Give it
appropriate name – Next – choose Glassfish Server – Next – Don’t choose any
framework – Finish.
index.html
< action="RegisterServlet" >
<H1>Welcome to Registration page</H1>
Enter User Name <input type="text" name="txtUid"><br>
Enter Password <input type="password" name="txtPass"><br>
Enter Email <input type="text" name="txtEmail" ><br>
Enter Country <input type="text" name="txtCon" ><br>
<input type="reset" ><input type="submit" value="REGISTER" >
</form>
RegisterServlet.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author Sophia
*/
public class RegisterServlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet RegisterServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet RegisterServlet at " + request.getContextPath() + "</h1>");
String id = request.getParameter("txtUid");
String ps = request.getParameter("txtPass");
String em = request.getParameter("txtEmail");
String co = request.getParameter("txtCon");
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con =DriverManager.getConnection("jdbc:mysql://localhost:3306/login","root","root");
PreparedStatement pst = con.prepareStatement("insert into user values(?,?,?,?)");
pst.setString(1,id);
pst.setString(2,ps);
pst.setString(3,em);
pst.setString(4,co);
int row = pst.executeUpdate();
out.println("<h1>"+row+ " Inserted Succesfullyyyyy");
}catch(Exception e){out.println(e);}
out.println("</body>");
out.println("</html>");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
prac -4C(Create a registration and login JSP application to register and authenticate the user
based on username and password using JDBC.)
index.html
<action="register.jsp" method="post">
<h1>REGISTRATION FORM</h1>
ENTER USER NAME: <input type="text" name="txtName" required><br>
ENTER PASSWORD: <input type="password" name="txtPass1" required><br>
RE-ENTER PASSWORD: <input type="password" name="txtPass2" required><br>
ENTER EMAIL: <input type="email" name="txtEmail" required><br>
ENTER COUNTRY NAME: <input type="text" name="txtCon" required><br><br>
<input type="reset">
<input type="submit" name="register" value="Register">
</form>
login.html
<action="login.jsp" method="post">
<h1>LOGIN FORM</h1>
ENTER USER NAME: <input type="text" name="txtName" required><br>
ENTER PASSWORD: <input type="password" name="txtPass" required><br><br>
<input type="submit" name="login" value="Login">
</form>
login.jsp
<%--
Document : login
Created on : 21 Sep, 2024, 3:38:55 PM
Author : Sophia
--%>
<%@ page import="java.sql.*" %>
<%
String username = request.getParameter("txtName");
String password = request.getParameter("txtPass");
try {
Class.forName("com.mysql.jdbc.Driver"); // Load the JDBC driver for MySQL
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/userdb", "root", "root");
String query = "SELECT * FROM users WHERE username=? AND password=?";
PreparedStatement pstmt = con.prepareStatement(query);
pstmt.setString(1, username);
pstmt.setString(2, password);
ResultSet rs = pstmt.executeQuery();
if(rs.next()) {
out.println("<h1>Login Successful!</h1>");
} else {
out.println("<h1>Invalid Username or Password.</h1>");
}
rs.close();
pstmt.close();
con.close();
} catch(Exception e) {
out.println("Error: " + e.getMessage());
}
%>
resgister.jsp
<%--
Document : register
Created on : 21 Sep, 2024, 3:37:55 PM
Author : Sophia
--%>
<%@ page import="java.sql.*" %>
<%
String username = request.getParameter("txtName");
String password1 = request.getParameter("txtPass1");
String password2 = request.getParameter("txtPass2");
String email = request.getParameter("txtEmail");
String country = request.getParameter("txtCon");
if(password1.equals(password2)) {
try {
Class.forName("com.mysql.jdbc.Driver"); // Load the JDBC driver for MySQL
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/userdb", "root", "");
String query = "INSERT INTO users (username, password, email, country) VALUES (?, ?, ?, ?)";
PreparedStatement pstmt = con.prepareStatement(query);
pstmt.setString(1, username);
pstmt.setString(2, password1);
pstmt.setString(3, email);
pstmt.setString(4, country);
int result = pstmt.executeUpdate();
if(result > 0) {
out.println("<h1>Registration Successful!</h1>");
out.println("<a href='login.html'>Login Here</a>");
} else {
out.println("<h1>Registration Failed. Please Try Again.</h1>");
}
pstmt.close();
con.close();
} catch(Exception e) {
out.println("Error: " + e.getMessage());
}
} else {
out.println("<h1>Passwords do not match. Try again.</h1>");
}
%>
prac -5A(Create an html page with fields, eno, name, age, desg, salary. Now on submit this data to a JSP page which will update the employee table of database with matching eno.)
Database
CREATE DATABASE employee_db;
USE employee_db;
CREATE TABLE employee (
eno INT PRIMARY KEY,
name VARCHAR(100),
age INT,
designation VARCHAR(50),
salary DECIMAL(10, 2)
);
INSERT INTO employee (eno, name, age, designation, salary) VALUES
(101, ‘Sophia Dcruz’, 23, 'Software Engineer', 22000.00),
(102, ‘Ankit Rawat’, 28, 'Project Manager', 75000.00),
(103, 'Alice Johnson', 35, 'Team Lead', 65000.00);
index.html
<h2>Update Employee Information</h2>
< action="updateEmployee.jsp" method="post">
<label for="eno">Employee No:</label>
<input type="text" id="eno" name="eno" required><br><br>
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br><br>
<label for="age">Age:</label>
<input type="number" id="age" name="age" required><br><br>
<label for="desg">Designation:</label>
<input type="text" id="desg" name="desg" required><br><br>
<label for="salary">Salary:</label>
<input type="number" id="salary" name="salary" required><br><br>
<input type="submit" value="Submit">
</form>
updateEmployee.jsp
<%--
Document : updateEmployee
Created on : 21 Sep, 2024, 8:52:46 PM
Author : Sophia
--%>
<%@ page import="java.sql.*" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
<title>Update Employee</title>
</head>
<body>
<%
// Get form parameters
String eno = request.getParameter("eno");
String name = request.getParameter("name");
String age = request.getParameter("age");
String desg = request.getParameter("desg");
String salary = request.getParameter("salary");
Connection conn = null;
PreparedStatement stmt = null;
try {
// Load the JDBC driver (assuming MySQL here)
Class.forName("com.mysql.jdbc.Driver");
// Connect to the database
String dbURL = "jdbc:mysql://localhost:3306/employee_db"; // Update with your DB details
String username = "root"; // Update with your DB username
String password = ""; // Update with your DB password
conn = DriverManager.getConnection(dbURL, username, password);
// SQL query to update the employee record
String sql = "UPDATE employee SET name=?, age=?, designation=?, salary=? WHERE eno=?";
stmt = conn.prepareStatement(sql);
// Set parameters
stmt.setString(1, name);
stmt.setInt(2, Integer.parseInt(age));
stmt.setString(3, desg);
stmt.setDouble(4, Double.parseDouble(salary));
stmt.setString(5, eno);
// Execute the update
int rows = stmt.executeUpdate();
if (rows > 0) {
out.println("<h3>Employee record updated successfully!</h3>");
} else {
out.println("<h3>Error: Employee not found with eno " + eno + "</h3>");
}
} catch (Exception e) {
out.println("<h3>Error: " + e.getMessage() + "</h3>");
} finally {
// Close resources
if (stmt != null) stmt.close();
if (conn != null) conn.close();
}
%>
</body>
</html>
prac -6B(Simple Room Reservation System Application Using EJB.)
Database
Create database:
CREATE DATABASE patkar;
USE patkar;
CREATE TABLE book (
roomId INT AUTO_INCREMENT PRIMARY KEY,
RoomType VARCHAR(50),
cust VARCHAR(100) DEFAULT '',
mob VARCHAR(15) DEFAULT '',
status VARCHAR(20) DEFAULT 'Not Booked',
charges DECIMAL(10, 2)
);
INSERT INTO book (RoomType, status, charges)
VALUES
('Single', 'Not Booked', 1500.00),
('Double', 'Not Booked', 2500.00),
('Delux', 'Not Booked', 3500.00),
('Super', 'Not Booked', 4500.00),
('Single', 'Not Booked', 1500.00),
('Double', 'Not Booked', 2500.00),
('Delux', 'Not Booked', 3500.00),
('Super', 'Not Booked', 4500.00);
index.html
<h1>Welcome To Room Booking Portal</h1><br>
< action="RoomBook">
Select a type of room:
<input type="radio" name="txtType" value="Single">Single
<input type="radio" name="txtType" value="Double">Double
<input type="radio" name="txtType" value="Delux">Delux
<input type="radio" name="txtType" value="Super">Super
<br>
Enter your name: <input type="text" name="txt1"><br>
Enter your phone number: <input type="text" name="txt2"><br>
<input type="submit" value="Book A room">
<br><input type="reset" value="Reset"><br>
</form>
NewSessionBean.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.ejb.Stateless;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Sophia
*/
@Stateless
public class NewSessionBean {
public NewSessionBean() {
}
public String roombook(String rt, String cn, String cm)
{
String confirmationMsg="";
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con =DriverManager.getConnection("jdbc:mysql://localhost:3306/patkar","root","root");
PreparedStatement pst = con.prepareStatement("select * from book where RoomType=? and status='Not Booked'");
pst.setString(1, rt);
ResultSet rs = pst.executeQuery();
if(rs.next())
{
String rno = rs.getString(1);
PreparedStatement stm = con.prepareStatement("UPDATE book SET cust=?, mob=?, status='Booked' WHERE roomId=?");
stm.setString(1, cn);
stm.setString(2, cm);
stm.setString(3, rno);
stm.executeUpdate();
confirmationMsg = "Room " + rno + " has been reserved <br> The charges applicable for the room is Rs. " + rs.getString(6);
}
else
{
confirmationMsg="Room "+rt+" is currently not available ...please try again for another room";
}
}
catch( ClassNotFoundException | SQLException e)
{
confirmationMsg=""+e;
}
return confirmationMsg;
} }
RoomBook.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.IOException;
import java.io.PrintWriter;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author Sophia
*/
public class RoomBook extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@EJB
NewSessionBean obj;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
String rt = request.getParameter("txtType");
String cn = request.getParameter("txt1");
String cm = request.getParameter("txt2");
String msg = obj.roombook(rt,cn,cm);
out.println(msg);
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
prac -7(Marks Entry Application to demonstrate accessing Database)
Database
CREATE DATABASE student_records;
USE student_records; CREATE TABLE students (
studentId INT AUTO_INCREMENT PRIMARY KEY,
studentName VARCHAR(100),
subject1Marks INT,
subject2Marks INT,
subject3Marks INT,
totalMarks INT
);
index.html
<action="NewServlet">
<h1>Students Details</h1><br>
Enter Student Name :- <input type="text" name="SName"/><br>
Enter Subject1 Marks :- <input type="number" name="Sub1"/><br>
Enter Subject2 Marks :- <input type="number" name="Sub2"/><br>
Enter Subject3 Marks :- <input type="number" name="Sub3"/><br>
<input type="submit" value="Insert">
<input type="reset" value="Clear">
</form>
NewServlet.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.IOException;
import java.io.PrintWriter;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author Sophia
*/
public class NewServlet extends HttpServlet {
@EJB
StudentBean obj;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
String msg="";
String Studname=request.getParameter("SName");
int mark1=Integer.parseInt(request.getParameter("Sub1"));
int mark2=Integer.parseInt(request.getParameter("Sub2"));
int mark3=Integer.parseInt(request.getParameter("Sub3"));
int totalmarks=mark1+mark2+mark3;
msg=obj.marksEntry(Studname,mark1,mark2,mark3,totalmarks);
out.println(msg);
}
}
}
StudentBean.java
import java.sql.*;
import javax.ejb.Stateless;
@Stateless
public class StudentBean {
public StudentBean(){}
public String marksEntry(String name,int mrk1,int mrk2,int mrk3,int total)
{
String confirmationMsg;
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/student_records","root","root");
PreparedStatement ps = con.prepareStatement("insert into student values(?,?,?,?,?)");
ps.setString(1, name);
ps.setInt(2, mrk1);
ps.setInt(3, mrk2);
ps.setInt(4, mrk3);
ps.setInt(5, total);
int r=ps.executeUpdate();
if(r==1)
{
confirmationMsg="<h3><b>" + name + " your marks have been updated successfully<b><h1>";
}
else
{
confirmationMsg="<h2> Could not update data.Please try Again!!!</h2>";
}
}
catch(ClassNotFoundException | SQLException e)
{
confirmationMsg=""+e;
}
return confirmationMsg;
}
}
Comments
Post a Comment