Practical - 1 Aim:-: 1 Krishna Ghandi 12202040701081

Download as pdf or txt
Download as pdf or txt
You are on page 1of 94

Bachelor of Technology (Computer Engineering)

Advanced Java Programming (202045605)

PRACTICAL - 1
Aim :-
Write a JDBC desktop program to perform following CRUD and Searchoperation. Create
appropriate table in database to store objects of Student class.
1. Add Student. (Create)
2. View Students. (Display all students)
3. Edit Student. (Update)
4. Delete Student. (Delete)
5. Search Student (Find student based on enrolment No)

Code :-
import java.sql.*;
import java.util.Scanner;

public class Book {


Scanner sc = new Scanner(System.in);
public void printTable(ResultSet rs) throws SQLException{
System.out.println("\n
");
System.out.println("Id\tFirst Name\tLast Name\tContact\t\tBranch\t\tAddress\t\tDOB");
while(rs.next())
System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t\t"+rs.getString(3)+"\t\t"+rs.getString(
4)+"\t"+rs.getString(5)+"\t\t"+rs.getString(6)+"\t\t"+rs.getString(7));
System.out.println("
");
}
public int updateCommon(PreparedStatement update,String column) throws
SQLException{
int i = 0;
Book obj = new Book();
System.out.println("\nEnter "+column+" Value : ");
update.setString(1, obj.sc.next());
System.out.println("\nEnter Id : ");

12202040701081 Krishna Ghandi 1


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)
update.setInt(2, obj.sc.nextInt());
i = update.executeUpdate();
return i;
}

public static void main(String[] args) {


Book obj = new Book();
try{
boolean flag = true;
int choice=0;
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test",
"root", "");
PreparedStatement insert = con.prepareStatement("insert into student
values(?,?,?,?,?,?,?)");
PreparedStatement updateFname = con.prepareStatement("update student set
First_name=? where id=?");
PreparedStatement updateLname = con.prepareStatement("update student set
Last_name=? where id=?");
PreparedStatement updateContact = con.prepareStatement("update student set
Contact_no=? where id=?");
PreparedStatement updateBranch = con.prepareStatement("update student setBranch=?
where id=?");
PreparedStatement updateAddress = con.prepareStatement("update student set
Address=? where id=?");
PreparedStatement updateDOB = con.prepareStatement("update student set DOB=?
where id=?");
PreparedStatement delete = con.prepareStatement("delete from student where id = ?");
PreparedStatement view = con.prepareStatement("select * from student where Id = ?");
PreparedStatement viewAll = con.prepareStatement("select * from student");

while(flag){
System.out.println("\nEnter 1 For Insert");

12202040701081 Krishna Ghandi 2


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)
System.out.println("Enter 2 For Update");
System.out.println("Enter 3 For Delete");
System.out.println("Enter 4 For View");
System.out.println("Enter 5 For ViewAll");
System.out.println("Enter 6 For Exit");
System.out.println("\nEnter Your Choice : ");

if(obj.sc.hasNextInt()){
choice = obj.sc.nextInt();
}
switch(choice){
case 1:
System.out.println("Enter Student Id : ");
insert.setInt(1, obj.sc.nextInt());
System.out.println("Enter First Name : ");
insert.setString(2, obj.sc.next());
System.out.println("Enter Last Name : ");
insert.setString(3, obj.sc.next());
System.out.println("Enter Contact No : ");
insert.setString(4, obj.sc.next());
System.out.println("Enter Branch : ");
insert.setString(5, obj.sc.next());
System.out.println("Enter Address : ");
insert.setString(6, obj.sc.next());
System.out.println("Enter DOB(dd-mm-yyyy) : ");
insert.setString(7, obj.sc.next());

int i = insert.executeUpdate();
System.out.println("\n"+i+ " Row Inserted");

12202040701081 Krishna Ghandi 3


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)
break;

case 2:
int upadatecol = 0;
String column="";

do{
System.out.println("-------Which Field You Want To Update ------- ");
System.out.println("\nEnter 1 For First Name");
System.out.println("Enter 2 For Last Name");
System.out.println("Enter 3 For Contact No");
System.out.println("Enter 4 For Branch");
System.out.println("Enter 5 For Address");
System.out.println("Enter 6 For DOB");
System.out.println("Enter Your Choice : ");
upadatecol = obj.sc.nextInt();
if(upadatecol>0 && upadatecol <= 4)
break;
}while(true);
int up=0;
switch(upadatecol){
case 1:
column = "First_name";
up = obj.updateCommon(updateFname, column);
break;
case 2:
column = "Last_name";
up = obj.updateCommon(updateLname, column);
break;
case 3:

12202040701081 Krishna Ghandi 4


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)
column = "Contact_no";
up = obj.updateCommon(updateContact, column);
break;
case 4:
column = "Branch";
up = obj.updateCommon(updateBranch, column);
break;
case 5:
column = "Address";
up = obj.updateCommon(updateAddress, column);
break;
case 6:
column = "DOB";
up = obj.updateCommon(updateDOB, column);
break;
default:
System.out.println("Enter Valid Choice -_-'");
break;
}
System.out.println(up+" Row Updated");
break;
case 3:
System.out.println("Enter Id : ");
delete.setInt(1, obj.sc.nextInt());
int del = delete.executeUpdate();
System.out.println(del+" Row Deleted");
break;
case 4:
System.out.println("Enter Id : ");
view.setInt(1, obj.sc.nextInt());

12202040701081 Krishna Ghandi 5


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)
ResultSet rs = view.executeQuery();
obj.printTable(rs);
rs.close();
break;

case 5:
System.out.println();
ResultSet r = viewAll.executeQuery();
obj.printTable(r);
r.close();
break;

case 6:
flag = false;
break;

default:
System.out.println("Enter Valid Choice -_-'");
break;
}
}
}catch(Exception e){
System.out.println(e);
}
}
}

12202040701081 Krishna Ghandi 6


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)
Output :-
Enter 1 For Insert
Enter 2 For Update
Enter 3 For Delete
Enter 4 For View
Enter 5 For ViewAll
Enter 6 For Exit
Enter Your Choice :
4
Enter Id : 2

Id First Name Last Name Contact Branch Address DOB


6 Tony Stark 1234567890 CP Stark Tower 1990-05-25

Enter 1 For Insert


Enter 2 For Update
Enter 3 For Delete
Enter 4 For View
Enter 5 For ViewAll
Enter 6 For Exit
Enter Your Choice :
6

12202040701081 Krishna Ghandi 7


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)

PRACTICAL - 2
Aim :-
Write servlet which get data from html form and display all data intoservlet.

Index.html :-
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
label{
position: absolute;
float: left;
}
input[type="text"]{
margin-left: 8%;
}
</style>
</head>
<body>
<div style="text-align: center">
<form action="Form" method="get">
<label>Full Name : </label>
<input type="text" name="name"><br><br>
<label>Phone No. : </label>
<input type="text" maxlength="10" name="number"><br><br>
<label>Email Address : </label>
<input type="text" name="email"><br><br>
<label>Department : </label>

12202040701081 Krishna Ghandi 8


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)
<input type="text" name="dept"><br><br>
<input type="submit">
</form>
</div>
</body>
</html>

NewServlet :-
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Form extends HttpServlet {


public void init(ServletConfig config){
}
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></title>");
out.println("</head>");
out.println("<body>");

12202040701081 Krishna Ghandi 9


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)
out.println("<h4>Hello </h4><p>" + request.getParameter("name") + "</p>");
out.println("<h5>Phone No : </h5><p>"+request.getParameter("number")+"</p>");
out.println("<h5>Email Adderss : </h5><p>"+request.getParameter("email")+"</p>");
out.println("<h5>Department : </h5><p>"+request.getParameter("dept")+"</p>");
out.println("</body>");
out.println("</html>");
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}

12202040701081 Krishna Ghandi 10


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)

Output :-

12202040701081 Krishna Ghandi 11


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)

PRACTICAL - 3
Aim :-
Convert following servlets in MVC architecture. Write different servlets whichget data from
html form and perform following database operations.

1. Add Student. (Create)


2. Edit Student. (Update)
3. Delete Student. (Delete)
4. Search Student (Find student based on enrolment No)
5. View All Students

HTML :-
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
label{
position: absolute;
float: left;
}
input[type="text"]{
margin-left: 8%;
}
input[type="date"]{
margin-left: 8%;
}
</style>
</head>

12202040701081 Krishna Ghandi 12


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)
<body>
<form action="Process" method="get">
<center>
<h1>Select the operation to perform on student table</h1>
<label>Id : </label>
<input type="text" name="id" required><br><br>
<label>First Name : </label>
<input type="text" name="fname"><br><br>
<label>Last Name : </label>
<input type="text" name="lname"><br><br>
<label>Contact : </label>
<input type="text" name="contact"><br><br>
<label>Branch : </label>
<input type="text" name="branch"><br><br>
<label>Address : </label>
<input type="text" name="address"><br><br>
<label>DOB : </label>
<input type="date" name="dob"><br><br>
<input type="submit" name="submit" value="Add">
<input type="submit" name="submit" value="Update">
<input type="submit" name="submit" value="Delete">
<input type="submit" name="submit" value="Search">
<input type="submit" name="submit" value="Show All">
</center>
</form>
</body>
</html>

12202040701081 Krishna Ghandi 13


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)

Process.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.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns = {"/Process"})
public class Process extends HttpServlet {
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 Process</title>");
out.println("</head>");
out.println("<body>");
String btn = request.getParameter("submit");
out.println("<h1>You Are Click : " +btn+ "</h1>");
HttpSession session = request.getSession();
switch (btn) {
case "Add":
session.setAttribute("id", request.getParameter("id"));

12202040701081 Krishna Ghandi 14


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)
session.setAttribute("fname", request.getParameter("fname"));
session.setAttribute("lname", request.getParameter("lname"));
session.setAttribute("contact", request.getParameter("contact"));
session.setAttribute("branch", request.getParameter("branch"));
session.setAttribute("address", request.getParameter("address"));
session.setAttribute("dob", request.getParameter("dob"));
response.sendRedirect("Add_student");
break;
case "Update":
session.setAttribute("id", request.getParameter("id"));
session.setAttribute("fname", request.getParameter("fname"));
session.setAttribute("lname", request.getParameter("lname"));
session.setAttribute("contact", request.getParameter("contact"));
session.setAttribute("branch", request.getParameter("branch"));
session.setAttribute("address", request.getParameter("address"));
session.setAttribute("dob", request.getParameter("dob"));
response.sendRedirect("Update_student");
break;
case "Delete":
session.setAttribute("id", request.getParameter("id"));
response.sendRedirect("Delete_Student");
break;
case "Search":
session.setAttribute("id", request.getParameter("id"));
response.sendRedirect("Search_Student");
break;
case "Show All":
request.getRequestDispatcher("ShowAll_Student").forward(request, response);
break;
default:

12202040701081 Krishna Ghandi 15


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)
break;
}
out.println("</body>");
out.println("</html>");
}
}
}

Add_student.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;
import java.sql.*;
import javax.servlet.http.HttpSession;

@WebServlet(urlPatterns = {"/Add_student"})
public class Add_student extends HttpServlet {

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

12202040701081 Krishna Ghandi 16


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet Add_student</title>");
out.println("</head>");
out.println("<body>");
HttpSession session = request.getSession(false);
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","");
PreparedStatement stmt = con.prepareStatement("insert into student
values(?,?,?,?,?,?,?)");
stmt.setInt(1, Integer.parseInt((String) session.getAttribute("id")));
stmt.setString(2, (String) session.getAttribute("fname"));
stmt.setString(3, (String) session.getAttribute("lname"));
stmt.setString(4, (String) session.getAttribute("contact"));
stmt.setString(5, (String) session.getAttribute("branch"));
stmt.setString(6, (String) session.getAttribute("address"));
stmt.setString(7, (String) session.getAttribute("dob"));
int i = stmt.executeUpdate();
if(i==0){
out.println("<Center><p>Data Is Not Inserted</p></Center>");
}else{
out.println("<Center><p>Data Is Inserted</p></ Center>");
}
}catch(Exception e){
out.println("<p>"+e+"</p>");
}
out.println("</body>");
out.println("</html>");
}

12202040701081 Krishna Ghandi 17


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)
}
}

Update_student.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;
import java.sql.*;
import javax.servlet.http.HttpSession;

@WebServlet(urlPatterns = {"/Update_student"})
public class Update_student extends HttpServlet {

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 Update_student</title>");
out.println("</head>");
out.println("<body>");
HttpSession session = request.getSession(false);

12202040701081 Krishna Ghandi 18


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","");
PreparedStatement stmt = con.prepareStatement("update student set
First_name=?,Last_name=?,Contact_no=?,Branch=?,Address=?,DOB=? where Id=?");
stmt.setString(1, (String) session.getAttribute("fname"));
stmt.setString(2, (String) session.getAttribute("lname"));
stmt.setString(3, (String) session.getAttribute("contact"));
stmt.setString(4, (String) session.getAttribute("branch"));
stmt.setString(5, (String) session.getAttribute("address"));
stmt.setString(6, (String) session.getAttribute("dob"));
stmt.setInt(7, Integer.parseInt((String) session.getAttribute("id")));
int i = stmt.executeUpdate();
if(i!=0){
out.println("<Center><p>Data Is Updated</p></Center>");
}else{
out.println("<Center><p>Data Is Not Update</p></Center>");
}
}catch(Exception e){
out.println("<p>"+e+"</p>");
}
out.println("</body>");
out.println("</html>");
}
}
}

Delete_Student :-
import java.io.IOException;

12202040701081 Krishna Ghandi 19


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)
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;
import java.sql.*;
import javax.servlet.http.HttpSession;

@WebServlet(urlPatterns = {"/Delete_Student"})
public class Delete_Student extends HttpServlet {

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 Delete_Student</title>");
out.println("</head>");
out.println("<body>");
HttpSession session = request.getSession(false);
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","");
PreparedStatement stmt = con.prepareStatement("delete from student where id =
?");
stmt.setInt(1,Integer.parseInt((String) session.getAttribute("id")));

12202040701081 Krishna Ghandi 20


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)
int i = stmt.executeUpdate();
if(i!=0){
out.println("<Center><p>Data Is Deleted</p></Center>");
}else{
out.println("<Center><p>Data Is Not Deleted</p></Center>");
}
}catch(Exception e){
out.println("<p>"+e+"</p>");
}
out.println("</body>");
out.println("</html>");
}
}

Search_Student.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;
import java.sql.*;
import javax.servlet.http.HttpSession;

@WebServlet(urlPatterns = {"/Search_Student"})
public class Search_Student extends HttpServlet {

12202040701081 Krishna Ghandi 21


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)
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 Search_Student</title>");
out.println("</head>");
out.println("<body>");
out.println("<center>");
HttpSession session = request.getSession(false);
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","");
PreparedStatement stmt = con.prepareStatement("select * from student where id =
?");
stmt.setInt(1,Integer.parseInt((String) session.getAttribute("id")));
ResultSet rs = stmt.executeQuery();
if(rs!=null){
out.println("<table style='width:auto' border= '1px solid black'>");
out.println("<th>ID</th><th>First Name</th><th>Last Name</th><th>Contact
No</th><th>Branch</th><th>Address</th><th>DOB</th>");
while(rs.next()){
out.println("<tr>");

out.println("<td>"+rs.getInt(1)+"</td><td>"+rs.getString(2)+"</td><td>"+rs.getString(3)+"<
/td><td>"+rs.getString(4)+"</td><td>"+rs.getString(5)+"</td><td>"+rs.getString(6)+"</td>
<td>"+rs.getString(7)+"</td>");
out.println("</tr>");

12202040701081 Krishna Ghandi 22


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)
}
out.println("</table>");
}else{
out.println("<p>Data Is Not Found</p");
}
}catch(Exception e){
out.println("<p>"+e+"</p>");
}
out.println("</center>");
out.println("</body>");
out.println("</html>");
}
}
}

ShowAll_Student.Java :-

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
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(urlPatterns = {"/ShowAll_Student"})

12202040701081 Krishna Ghandi 23


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)
public class ShowAll_Student extends HttpServlet {

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 ShowAll_Student</title>");
out.println("</head>");
out.println("<body>");

out.println("<center>");
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","");
PreparedStatement stmt = con.prepareStatement("select * from student");
ResultSet rs = stmt.executeQuery();
if(rs!=null){
out.println("<table style='width:auto' border= '1px solid black'>");
out.println("<th>ID</th><th>First Name</th><th>Last Name</th><th>Contact
No</th><th>Branch</th><th>Address</th><th>DOB</th>");
while(rs.next()){
out.println("<tr>");

out.println("<td>"+rs.getInt(1)+"</td><td>"+rs.getString(2)+"</td><td>"+rs.getString(3)+"<
/td><td>"+rs.getString(4)+"</td><td>"+rs.getString(5)+"</td><td>"+rs.getString(6)+"</td>
<td>"+rs.getString(7)+"</td>");
out.println("</tr>");

12202040701081 Krishna Ghandi 24


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)
}
out.println("</table>");
}else{
out.println("<p>Data Is Not Found</p");
}
}catch(Exception e){
out.println("<p>"+e+"</p>");
}
out.println("</center>");
out.println("</body>");
out.println("</html>");
}
}
}

12202040701081 Krishna Ghandi 25


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)

Output :-

12202040701081 Krishna Ghandi 26


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)

PRACTICAL - 4
Aim :-
Create and maintain HttpSession in all servlets written in previous labs.

HTML :-
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
label{
position: absolute;
float: left;
}
input[type="text"]{
margin-left: 8%;
}
input[type="date"]{
margin-left: 8%;
}
</style>
</head>
<body>
<form action="Process" method="get">
<center>
<h1>Select the operation to perform on student table</h1>
<label>Id : </label>
<input type="text" name="id" required><br><br>
<label>First Name : </label>
<input type="text" name="fname"><br><br>

12202040701081 Krishna Ghandi 27


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)
<label>Last Name : </label>
<input type="text" name="lname"><br><br>
<label>Contact : </label>
<input type="text" name="contact"><br><br>
<label>Branch : </label>
<input type="text" name="branch"><br><br>
<label>Address : </label>
<input type="text" name="address"><br><br>
<label>DOB : </label>
<input type="date" name="dob"><br><br>
<input type="submit" name="submit" value="Add">
<input type="submit" name="submit" value="Update">
<input type="submit" name="submit" value="Delete">
<input type="submit" name="submit" value="Search">
<input type="submit" name="submit" value="Show All">
</center>
</form>
</body>
</html>

12202040701081 Krishna Ghandi 28


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)

Process.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(urlPatterns = {"/Process"})
public class Process extends HttpServlet {
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 Process</title>");
out.println("</head>");
out.println("<body>");
String btn = request.getParameter("submit");
out.println("<h1>You Are Click : " +btn+ "</h1>");
switch (btn) {
case "Add":
request.getRequestDispatcher("Add_student").forward(request, response);
break;
case "Update":

12202040701081 Krishna Ghandi 29


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)
request.getRequestDispatcher("Update_student").forward(request, response);
break;
case "Delete":
request.getRequestDispatcher("Delete_Student").forward(request, response);
break;
case "Search":
request.getRequestDispatcher("Search_Student").forward(request, response);
break;
case "Show All":
request.getRequestDispatcher("ShowAll_Student").forward(request, response);
break;
default:
break;
}
out.println("</body>");
out.println("</html>");
}
}
}

Add_student.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;
import java.sql.*;

12202040701081 Krishna Ghandi 30


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)
@WebServlet(urlPatterns = {"/Add_student"})
public class Add_student extends HttpServlet {
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 Add_student</title>");
out.println("</head>");
out.println("<body>");
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","");
PreparedStatement stmt = con.prepareStatement("insert into student
values(?,?,?,?,?,?,?)");
stmt.setInt(1,Integer.parseInt(request.getParameter("id")));
stmt.setString(2,request.getParameter("fname"));
stmt.setString(3,request.getParameter("lname"));
stmt.setString(4,request.getParameter("contact"));
stmt.setString(5,request.getParameter("branch"));
stmt.setString(6,request.getParameter("address"));
stmt.setString(7,request.getParameter("dob"));
int i = stmt.executeUpdate();
if(i==0){
out.println("<Center><p>Data Is Not Inserted</p></Center>");
}else{
out.println("<Center><p>Data Is Inserted</p></ Center>");

12202040701081 Krishna Ghandi 31


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)
}
}catch(Exception e){
out.println("<p>"+e+"</p>");
}
out.println("</body>");
out.println("</html>");
}
}
}

Update_student.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;
import java.sql.*;
@WebServlet(urlPatterns = {"/Update_student"})
public class Update_student extends HttpServlet {
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>");

12202040701081 Krishna Ghandi 32


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)
out.println("<head>");
out.println("<title>Servlet Update_student</title>");
out.println("</head>");
out.println("<body>");
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","");
PreparedStatement stmt = con.prepareStatement("update student set
First_name=?,Last_name=?,Contact_no=?,Branch=?,Address=?,DOB=? where Id=?");
stmt.setString(1,request.getParameter("fname"));
stmt.setString(2,request.getParameter("lname"));
stmt.setString(3,request.getParameter("contact"));
stmt.setString(4,request.getParameter("branch"));
stmt.setString(5,request.getParameter("address"));
stmt.setString(6,request.getParameter("dob"));
stmt.setInt(7,Integer.parseInt(request.getParameter("id")));
int i = stmt.executeUpdate();
if(i!=0){
out.println("<Center><p>Data Is Updated</p></Center>");
}else{
out.println("<Center><p>Data Is Not Update</p></Center>");
}
}catch(Exception e){
out.println("<p>"+e+"</p>");
}
out.println("</body>");
out.println("</html>");
}
}
}

12202040701081 Krishna Ghandi 33


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)

Delete_Student :-

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;
import java.sql.*;

@WebServlet(urlPatterns = {"/Delete_Student"})
public class Delete_Student extends HttpServlet {
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 Delete_Student</title>");
out.println("</head>");
out.println("<body>");
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","");
PreparedStatement stmt = con.prepareStatement("delete from student where id =
?");

12202040701081 Krishna Ghandi 34


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)
stmt.setInt(1,Integer.parseInt(request.getParameter("id")));
int i = stmt.executeUpdate();
if(i!=0){
out.println("<Center><p>Data Is Deleted</p></Center>");
}else{
out.println("<Center><p>Data Is Not Deleted</p></Center>");
}
}catch(Exception e){
out.println("<p>"+e+"</p>");
}
out.println("</body>");
out.println("</html>");
}
}
}

Search_Student.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;
import java.sql.*;

@WebServlet(urlPatterns = {"/Search_Student"})
public class Search_Student extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)

12202040701081 Krishna Ghandi 35


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)
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 Search_Student</title>");
out.println("</head>");
out.println("<body>");
out.println("<center>");
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","");
PreparedStatement stmt = con.prepareStatement("select * from student where id =
?");
stmt.setInt(1,Integer.parseInt(request.getParameter("id")));
ResultSet rs = stmt.executeQuery();
if(rs!=null){
out.println("<table style='width:auto' border= '1px solid black'>");
out.println("<th>ID</th><th>First Name</th><th>Last Name</th><th>Contact
No</th><th>Branch</th><th>Address</th><th>DOB</th>");
while(rs.next()){
out.println("<tr>");

out.println("<td>"+rs.getInt(1)+"</td><td>"+rs.getString(2)+"</td><td>"+rs.getString(3)+"<
/td><td>"+rs.getString(4)+"</td><td>"+rs.getString(5)+"</td><td>"+rs.getString(6)+"</td>
<td>"+rs.getString(7)+"</td>");
out.println("</tr>");
}
out.println("</table>");

12202040701081 Krishna Ghandi 36


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)
}else{
out.println("<p>Data Is Not Found</p");
}
}catch(Exception e){
out.println("<p>"+e+"</p>");
}
out.println("</center>");
out.println("</body>");
out.println("</html>");
}
}
}

ShowAll_Student.Java :-

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
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(urlPatterns = {"/ShowAll_Student"})
public class ShowAll_Student extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)

12202040701081 Krishna Ghandi 37


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)
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 ShowAll_Student</title>");
out.println("</head>");
out.println("<body>");

out.println("<center>");
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","");
PreparedStatement stmt = con.prepareStatement("select * from student");
ResultSet rs = stmt.executeQuery();
if(rs!=null){
out.println("<table style='width:auto' border= '1px solid black'>");
out.println("<th>ID</th><th>First Name</th><th>Last Name</th><th>Contact
No</th><th>Branch</th><th>Address</th><th>DOB</th>");
while(rs.next()){
out.println("<tr>");

out.println("<td>"+rs.getInt(1)+"</td><td>"+rs.getString(2)+"</td><td>"+rs.getString(3)+"<
/td><td>"+rs.getString(4)+"</td><td>"+rs.getString(5)+"</td><td>"+rs.getString(6)+"</td>
<td>"+rs.getString(7)+"</td>");
out.println("</tr>");
}
out.println("</table>");
}else{

12202040701081 Krishna Ghandi 38


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)
out.println("<p>Data Is Not Found</p");
}
}catch(Exception e){
out.println("<p>"+e+"</p>");
}
out.println("</center>");

out.println("</body>");
out.println("</html>");
}
}
}

12202040701081 Krishna Ghandi 39


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)

Output :-

12202040701081 Krishna Ghandi 40


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)

PRACTICAL - 5
Aim :-
Write simple web application in which display email address from servletinit
parameter and context init parameter. Write a Servlet which display no of hits
of 1. Particular servlet 2. Your web application.

Prac5.java :-
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
import javax.servlet.http.*;

public class Prac5 extends HttpServlet {

private int hitCounter;


static int ahitCounter = 1;

public void init() {


hitCounter = 0;
}

protected void processRequest(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
hitCounter++;
try ( PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
ServletContext scont = getServletContext();
String emailcont = scont.getInitParameter("email");
String n = String.valueOf(ahitCounter);
Cookie c = new Cookie("visit", n);

12202040701081 Krishna Ghandi 41


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)
response.addCookie(c);
int j = Integer.parseInt(c.getValue());
System.out.println(ahitCounter++);
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet Prac5</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet Context parameter " + emailcont + "</h1>");
out.println("<h1>Servlet Init parameter " + getInitParameter("email") + "</h1>");
out.println("<h1>Servlet hit count: " + hitCounter + "</h1>");
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);

12202040701081 Krishna Ghandi 42


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)
}

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

Web.xml :-
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

12202040701081 Krishna Ghandi 43


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<servlet>
<servlet-name>Prac5</servlet-name>
<servlet-class>Prac5</servlet-class>
<init-param>
<param-name>email</param-name>
<param-value>[email protected]</param-value>
</init-param>

</servlet>
<servlet-mapping>
<servlet-name>Prac5</servlet-name>
<url-pattern>/Prac5</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<context-param>
<param-name>email</param-name>
<param-value>[email protected]</param-value>
</context-param>

</web-app>

12202040701081 Krishna Ghandi 44


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)
Output :-

12202040701081 Krishna Ghandi 45


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)

PRACTICAL - 6
Aim :-
Write small web application with at least 2 servlets which share the common
object of Student class. Student class is having instance variable rollno,
assign the five rollnos and display all in both servlets.

Student.java :-
package demo;

public class Student


{
int roll[] = new int[5];
}

One.java
packagedemo;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class one extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try ( PrintWriter out = response.getWriter()) {
Student s = new Student();

12202040701081 Krishna Ghandi 46


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)
int n1 = s.roll[0] = 1;
int n2 = s.roll[1] = 2;
int n3 = s.roll[2] = 3;
int n4 = s.roll[3] = 4;
int n5 = s.roll[4] = 5;
HttpSession session = request.getSession();
session.setAttribute("rollno1", n1);
session.setAttribute("rollno2", n2);
session.setAttribute("rollno3", n3);
session.setAttribute("rollno4", n4);
session.setAttribute("rollno5", n5);

out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet one</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet one at " + n1 + "</h1>");
out.println("<h1>Servlet one at " + n2 + "</h1>");
out.println("<h1>Servlet one at " + n3 + "</h1>");
out.println("<h1>Servlet one at " + n4 + "</h1>");
out.println("<h1>Servlet one at " + n5 + "</h1>");
out.println("</body>");
out.println("</html>");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on
the left to edit the code.">
/**

12202040701081 Krishna Ghandi 47


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)
* 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.
*

12202040701081 Krishna Ghandi 48


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}

Two.java :-
package demo;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class two extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try ( PrintWriter out = response.getWriter()) {
HttpSession session = request.getSession(false);
int one = (int) session.getAttribute("rollno1");
int two = (int) session.getAttribute("rollno2");
int th = (int) session.getAttribute("rollno3");
int fo = (int) session.getAttribute("rollno4");

12202040701081 Krishna Ghandi 49


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)
int five = (int) session.getAttribute("rollno5");
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet two</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet two at " + one + "</h1>");
out.println("<h1>Servlet two at " + two + "</h1>");
out.println("<h1>Servlet two at " + th + "</h1>");
out.println("<h1>Servlet two at " + fo + "</h1>");
out.println("<h1>Servlet two at " + five + "</h1>");
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);

12202040701081 Krishna Ghandi 50


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)
}

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

12202040701081 Krishna Ghandi 51


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)
Output :-

12202040701081 Krishna Ghandi 52


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)

PRACTICAL -7
Aim :-
Develop User registration module using JSP 1. Create a User Page 4of 3
2. Update a User 3. Delete a User 4. Retrieve a User 5. List of all Users.

Index.html :-

<!DOCTYPE html>
<!--
Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this
license
Click nbfs://nbhost/SystemFileSystem/Templates/JSP_Servlet/Html.html to edit this template
-->
<html>
<head>
<title>User Registration</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<table style="min-height: 100vh;width: 100%;display: grid;justify-content: center;">
<form action="./userCreate.jsp" method="post">
<tr>
<td>
<label for="">Enter FirstName:</label>
</td>
<td>
<input type="text" name="fname">
</td>
</tr>
<tr>
<td>

12202040701081 Krishna Ghandi 53


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)
<label for="">Enter MiddleName:</label>
</td>
<td>
<input type="text" name="mname">
</td>
</tr>
<tr>
<td>
<label for="">Enter LastName:</label>
</td>
<td>
<input type="text" name="lname">
</td>
</tr>
<tr>
<td>
<label for="">Enter Email-id:</label>
</td>
<td>
<input type="email" name="email">
</td>
</tr>
<tr>
<td>
<label for="">Enter Address:</label>
</td>
<td>
<textarea name="address" id="" cols="30" rows="10"></textarea>
</td>
</tr>

12202040701081 Krishna Ghandi 54


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)
<tr>
<td>
<label for="">Gender:</label>
</td>
<td>
Male<input type="radio" name="gen" value="male" id="">
Female<input type="radio" name="gen" value="female" id="">
</td>
</tr>
<tr>
<td>
<button type="submit" name="register">Submit</button>
<a href="display.jsp"><button>Show-All</button></a>
</td>
</tr>
</form>
</table>
</body>
</html>

12202040701081 Krishna Ghandi 55


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)

userCreate.jsp
<%@page import="java.sql.*,java.io.*"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%--<%@page import="java.sql.*" %>--%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
String fname = request.getParameter("fname");
String mname = request.getParameter("mname");
String lname = request.getParameter("lname");
String email = request.getParameter("email");
String Addresss = request.getParameter("address");
String gender = request.getParameter("gen");
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/java_db",
"root",
""
);
if (request.getParameter("register") != null) {
PreparedStatement pst = con.prepareStatement("insert into user
values(?,?,?,?,?,?,?);");
pst.setString(1, fname);
pst.setString(2, mname);

12202040701081 Krishna Ghandi 56


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)
pst.setString(3, lname);
pst.setString(4, email);
pst.setString(5, Addresss);
pst.setString(6, gender);
pst.setInt(7, 0);
int x = pst.executeUpdate();
out.println("<h3>Data inserted success</h3>");
out.println("<a href='display.jsp'>Display</a>");
} else {
%>
<jsp:forward page="display.jsp"></jsp:forward>
<%
}

} catch (Exception e) {
out.print(e);
}
%>
</body>
</html>

12202040701081 Krishna Ghandi 57


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)

Display.jsp :-

<%@page import="java.sql.*,java.io.*"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/java_db",
"root",
""
);
Statement stm = con.createStatement();
ResultSet rs = stm.executeQuery("select * from user");
out.println("<table border='2'>");
out.println("<thead><tr><th>First-Name</th><th>Middle-Name</th><th>Last-
Name</th><th>Email</th><th>Address</th><th>Gender</th></tr></thead>");

while (rs.next()) {
out.println("<tr>");
out.println("<td>" + rs.getString(1) + "</td>"
);

12202040701081 Krishna Ghandi 58


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)
out.println("<td>" + rs.getString(2) + "</td>"
);
out.println("<td>" + rs.getString(3) + "</td>"
);
out.println("<td>" + rs.getString(4) + "</td>"
);
out.println("<td>" + rs.getString(5) + "</td>"
);
out.println("<td>" + rs.getString(6) + "</td>"
);
out.println("<td><a href='update.jsp?id=" + rs.getInt(7) + "'>update</td>"
);
out.println("<td><a href='delete.jsp?id=" + rs.getInt(7) + "'>delete</td>"
);
out.println("</tr>");
}
out.println("</table>");

out.println("<a href='index.html'>Insert Data</a>");

} catch (Exception e) {
out.println(e);
}

%>
</body>
</html>

12202040701081 Krishna Ghandi 59


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)

Output :-

Update.jsp :-

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<%@page import="java.sql.*,java.io.*"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
if (request.getParameter("Submit") != null) {
String fname = request.getParameter("fname");
String mname = request.getParameter("mname");
String lname = request.getParameter("lname");
String email = request.getParameter("email");
String Addresss = request.getParameter("address");
String gender = request.getParameter("gen");

12202040701081 Krishna Ghandi 60


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)
int id = Integer.parseInt(request.getParameter("id"));
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/java_db",
"root",
""
);
PreparedStatement pst = con.prepareCall("update user set first_name =
?,middle_name=?,last_name=?,email=?,Address=?,Gender=? where id=?");
pst.setString(1, fname);
pst.setString(2, mname);
pst.setString(3, lname);
pst.setString(4, email);
pst.setString(5, Addresss);
pst.setString(6, gender);
pst.setInt(7, id);
int x = pst.executeUpdate();
if (x == 1) {
%>
<script>
alert("Data updated");
</script>
<%
out.print("<a href='display.jsp'>Display Page</a>");
} else {
out.print("not updated");
}

} catch (Exception e) {
out.print(e);

12202040701081 Krishna Ghandi 61


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)
}
}
%>
<table style="min-height: 100vh;width: 100%;display: grid;justify-content: center;">
<form action="#" method="post">
<%
try {

Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/java_db",
"root",
""
);
int id1 = Integer.parseInt(request.getParameter("id"));
PreparedStatement pst = con.prepareStatement("select * from user where id =
?");
pst.setInt(1, id1);
ResultSet rs = pst.executeQuery();
while (rs.next()) {

%>
<tr>
<td>
<label for="">Enter FirstName:</label>
</td>
<td>
<input type="text" name="fname" value="<%= rs.getString(1)%>">
</td>
</tr>
<tr>

12202040701081 Krishna Ghandi 62


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)
<td>
<label for="">Enter MiddleName:</label>
</td>
<td>
<input type="text" name="mname" value="<%= rs.getString(2)%>">
</td>
</tr>
<tr>
<td>
<label for="">Enter LastName:</label>
</td>
<td>
<input type="text" name="lname" value="<%= rs.getString(3)%>">
</td>
</tr>
<tr>
<td>
<label for="">Enter Email-id:</label>
</td>
<td>
<input type="email" name="email" value="<%= rs.getString(4)%>">
</td>
</tr>
<tr>
<td>
<label for="">Enter Address:</label>
</td>
<td>
<textarea name="address" id="" cols="30" rows="10" ><%=
rs.getString(5)%></textarea>
</td>

12202040701081 Krishna Ghandi 63


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)
</tr>
<tr>
<td>
<label for="">Gender:</label>
</td>
<td>
Male<input type="radio" name="gen" value="male" id="" >
Female<input type="radio" name="gen" value="female" id="" >
</td>
</tr>
<tr>
<td>
<button type="submit" name="Submit">Update</button>
</td>
</tr>
<%}
} catch (Exception e) {
out.print(e);
}%>
</form>
</table>
</body>
</html>

12202040701081 Krishna Ghandi 64


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)

Output :-

12202040701081 Krishna Ghandi 65


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)

Delete.jsp :-

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<%@page import="java.sql.*,java.io.*"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
int id = Integer.parseInt(request.getParameter("id"));
out.print(id);
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/java_db",
"root",
""
);
PreparedStatement pstm = con.prepareStatement("delete from user where id = ?");
pstm.setInt(1, id);
int x = pstm.executeUpdate();
out.println("Deleted");

} catch (Exception e) {
out.print(e);
}
%>

12202040701081 Krishna Ghandi 66


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)
<jsp:forward page="display.jsp" ></jsp:forward>
</body>
</html>

Output :-

12202040701081 Krishna Ghandi 67


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)

PRACTICAL - 8
Aim :-
Reuse Student class as bean. Write JSP page to set and display all property.

Index.html :-
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>JSP CRUD Example</title>
</head>
<body>
<h1>JSP CRUD Example</h1>
<a href="adduserform.jsp">Add User</a>
<a href="viewusers.jsp">View Users</a>
</body>
</html>

adduserform.jsp :-
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Add User Form</title>
</head>
<body>
<jsp:include page="userform.html"></jsp:include>

</body>
</html>

userform.html :-
<a href="viewusers.jsp">View All Records</a><br/>

<h1>Add New User</h1>


<form action="adduser.jsp" method="post">
<table>
<tr><td>Name:</td><td><input type="text" name="name"/></td></tr>
<tr><td>Password:</td><td>
<input type="password" name="password"/></td></tr>
<tr><td>Email:</td><td><input type="email" name="email"/></td></tr>
<tr><td>Sex:</td><td>
<input type="radio" name="sex" value="male"/>Male
<input type="radio" name="sex" value="female"/>Female </td></tr>

12202040701081 Krishna Ghandi 68


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)

<tr><td>Country:</td><td>
<select name="country" style="width:155px">
<option>India</option>
<option>Pakistan</option>
<option>Afghanistan</option>
<option>Berma</option>
<option>Other</option>
</select>
</td></tr>
<tr><td colspan="2"><input type="submit" value="Add User"/></td></tr>
</table>
</form>

adduser.jsp :-

<%@page import="com.javatpoint.dao.UserDao"%>
<jsp:useBean id="u" class="com.javatpoint.bean.User"></jsp:useBean>
<jsp:setProperty property="*" name="u"/>

<%
int i=UserDao.save(u);
if(i>0){
response.sendRedirect("adduser-success.jsp");
}else{
response.sendRedirect("adduser-error.jsp");
}
%>

User.java :-

package com.javatpoint.bean;
public class User {
private int id;
private String name,password,email,sex,country;
//generate getters and setters
}

UserDao.java :-

package com.javatpoint.dao;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import com.javatpoint.bean.User;
public class UserDao {

public static Connection


getConnection(){Connection con=null;
try{

12202040701081 Krishna Ghandi 69


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)

Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","","");
}catch(Exception e){System.out.println(e);}
return con;
}
public static int save(User
u){int status=0;
try{
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement(
"insert into register(name,password,email,sex,country) values(?,?,?,?,?)");
ps.setString(1,u.getName());
ps.setString(2,u.getPassword());
ps.setString(3,u.getEmail());
ps.setString(4,u.getSex());
ps.setString(5,u.getCountry());
status=ps.executeUpdate();
}catch(Exception e){System.out.println(e);}
return status;
}
public static int update(User
u){int status=0;
try{
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement(
"update register set name=?,password=?,email=?,sex=?,country=? where id=?");
ps.setString(1,u.getName());
ps.setString(2,u.getPassword());
ps.setString(3,u.getEmail());
ps.setString(4,u.getSex());
ps.setString(5,u.getCountry());
ps.setInt(6,u.getId());
status=ps.executeUpdate();
}catch(Exception e){System.out.println(e);}
return status;
}
public static int delete(User
u){int status=0;
try{
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement("delete from register where id=?");
ps.setInt(1,u.getId());
status=ps.executeUpdate();
}catch(Exception e){System.out.println(e);}

return status;
}
public static List<User>
getAllRecords(){ List<User> list=new
ArrayList<User>();

12202040701081 Krishna Ghandi 70


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)

try{
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement("select * from register");
ResultSet rs=ps.executeQuery();
while(rs.next()){
User u=new User();
u.setId(rs.getInt("id"));
u.setName(rs.getString("name"));
u.setPassword(rs.getString("password"));
u.setEmail(rs.getString("email"));
u.setSex(rs.getString("sex"));
u.setCountry(rs.getString("country"));
list.add(u);
}
}catch(Exception e){System.out.println(e);}
return list;
}
public static User getRecordById(int
id){User u=null;
try{
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement("select * from register where id=?");
ps.setInt(1,id);
ResultSet rs=ps.executeQuery();
while(rs.next()){
u=new User();
u.setId(rs.getInt("id"));
u.setName(rs.getString("name"));
u.setPassword(rs.getString("password"));
u.setEmail(rs.getString("email"));
u.setSex(rs.getString("sex"));
u.setCountry(rs.getString("country"));
}
}catch(Exception e){System.out.println(e);}
return u;
}
}

adduser-success.jsp :-

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Add User Success</title>
</head>
<body>

12202040701081 Krishna Ghandi 71


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)

<p>Record successfully saved!</p>


<jsp:include page="userform.html"></jsp:include>

</body>
</html>

adduser-error.jsp :-

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Add User Error</title>
</head>
<body>

<p>Sorry, an error occurred!</p>


<jsp:include page="userform.html"></jsp:include>

</body>
</html>

viewusers.jsp :-

<!DOCTYPE html>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>View Users</title>
</head>
<body>

<%@page import="com.javatpoint.dao.UserDao,com.javatpoint.bean.*,java.util.*"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<h1>Users List</h1>

<%
List<User> list=UserDao.getAllRecords();
request.setAttribute("list",list);
%>

<table border="1" width="90%">


<tr><th>Id</th><th>Name</th><th>Password</th><th>Email</th>
<th>Sex</th><th>Country</th><th>Edit</th><th>Delete</th></tr>
<c:forEach items="${list}" var="u">
<tr><td>${u.getId()}</td><td>${u.getName()}</td><td>${u.getPassword()}</td>
<td>${u.getEmail()}</td><td>${u.getSex()}</td><td>${u.getCountry()}</td>

12202040701081 Krishna Ghandi 72


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)

<td><a href="editform.jsp?id=${u.getId()}">Edit</a></td>
<td><a href="deleteuser.jsp?id=${u.getId()}">Delete</a></td></tr>
</c:forEach>
</table>
<br/><a href="adduserform.jsp">Add New User</a>

</body>
</html>

editform.jsp :-
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Edit Form</title>
</head>
<body>
<%@page import="com.javatpoint.dao.UserDao,com.javatpoint.bean.User"%>

<%
String id=request.getParameter("id");
User u=UserDao.getRecordById(Integer.parseInt(id));
%>

<h1>Edit Form</h1>
<form action="edituser.jsp" method="post">
<input type="hidden" name="id" value="<%=u.getId() %>"/>
<table>
<tr><td>Name:</td><td>
<input type="text" name="name" value="<%= u.getName()%>"/></td></tr>
<tr><td>Password:</td><td>
<input type="password" name="password" value="<%= u.getPassword()%>"/></td></tr>
<tr><td>Email:</td><td>
<input type="email" name="email" value="<%= u.getEmail()%>"/></td></tr>
<tr><td>Sex:</td><td>
<input type="radio" name="sex" value="male"/>Male
<input type="radio" name="sex" value="female"/>Female </td></tr>
<tr><td>Country:</td><td>
<select name="country">
<option>India</option>
<option>Pakistan</option>
<option>Afghanistan</option>
<option>Berma</option>
<option>Other</option>
</select>
</td></tr>
<tr><td colspan="2"><input type="submit" value="Edit User"/></td></tr>
</table>
</form>

</body>

12202040701081 Krishna Ghandi 73


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)

</html>

edituser.jsp :-
<%@page import="com.javatpoint.dao.UserDao"%>
<jsp:useBean id="u" class="com.javatpoint.bean.User"></jsp:useBean>
<jsp:setProperty property="*" name="u"/>
<%
int i=UserDao.update(u);
response.sendRedirect("viewusers.js
p");
%>

deleteuser.jsp:-

<%@page import="com.javatpoint.dao.UserDao"%>
<jsp:useBean id="u" class="com.javatpoint.bean.User"></jsp:useBean>
<jsp:setProperty property="*" name="u"/>
<%
UserDao.delete(u);
response.sendRedirect("viewusers.js
p");
%>

12202040701081 Krishna Ghandi 74


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)

Output :-

12202040701081 Krishna Ghandi 75


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)

12202040701081 Krishna Ghandi 76


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)

12202040701081 Krishna Ghandi 77


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)

12202040701081 Krishna Ghandi 78


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)

PRACTICAL - 9

Aim :-
Rewrite all .jsp pages of previous labs using EL and JSTL.

Java Bean Class :-

package com.journaldev.model;

public class Employee {

private int id;


private String name;
private String role;
public Employee() {
}
public int getId() {
return id;
}
public void setId(int id)
{this.id = id;
}
public String getName()
{return name;
}
public void setName(String name)
{this.name = name;
}
public String getRole()
{return role;
}
public void setRole(String role)
{this.role = role;
}

Servlet Class :-
package com.journaldev.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

12202040701081 Krishna Ghandi 79


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)

import javax.servlet.http.HttpServletResponse;

import com.journaldev.model.Employee;

@WebServlet("/HomeServlet")
public class HomeServlet extends HttpServlet
{ private static final long serialVersionUID =
1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {
List<Employee> empList = new ArrayList<Employee>();
Employee emp1 = new Employee();
emp1.setId(1); emp1.setName("Pankaj");emp1.setRole("Developer");
Employee emp2 = new Employee();
emp2.setId(2); emp2.setName("Meghna");emp2.setRole("Manager");
empList.add(emp1);empList.add(emp2);
request.setAttribute("empList", empList);

request.setAttribute("htmlTagData", "<br/> creates a new line.");


request.setAttribute("url", "https://www.journaldev.com");
RequestDispatcher rd = getServletContext().getRequestDispatcher("/home.jsp");
rd.forward(request, response);
}

JSP Page :-

<%@ page language="java" contentType="text/html; charset=US-ASCII"


pageEncoding="US-ASCII"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Home Page</title>
<%@ taglib uri="https://java.sun.com/jsp/jstl/core" prefix="c" %>
<style>
table,th,td
{
border:1px solid black;
}
</style>
</head>
<body>
<%-- Using JSTL forEach and out to loop a list and display items in table --%>
<table>
<tbody>
<tr><th>ID</th><th>Name</th><th>Role</th></tr>

12202040701081 Krishna Ghandi 80


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)

<c:forEach items="${requestScope.empList}" var="emp">


<tr><td><c:out value="${emp.id}"></c:out></td>
<td><c:out value="${emp.name}"></c:out></td>
<td><c:out value="${emp.role}"></c:out></td></tr>
</c:forEach>
</tbody>
</table>
<br><br>
<%-- simple c:if and c:out example with HTML escaping --%>
<c:if test="${requestScope.htmlTagData ne null }">
<c:out value="${requestScope.htmlTagData}" escapeXml="true"></c:out>
</c:if>
<br><br>
<%-- c:set example to set variable value --%>
<c:set var="id" value="5" scope="request"></c:set>
<c:out value="${requestScope.id }" ></c:out>
<br><br>
<%-- c:catch example --%>
<c:catch var ="exception">
<% int x = 5/0;%>
</c:catch>

<c:if test = "${exception ne null}">


<p>Exception is : ${exception} <br>
Exception Message: ${exception.message}</p>
</c:if>
<br><br>
<%-- c:url example --%>
<a href="<c:url value="${requestScope.url }"></c:url>">JournalDev</a>
</body>
</html>

12202040701081 Krishna Ghandi 81


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)

Output :-

12202040701081 Krishna Ghandi 82


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)

Practical – 10

Aim :-
Write Hibernate application to store student records and retrieve the studentrecord
including name, enrolment no, sem, div, dept, sgpa, cgpa, etc.

Emp.java :-
package com.javatpoint.beans;

public class Emp {


private int id;
private String name;
private float salary;
private String designation;

public int getId()


{return id;
}
public void setId(int id)
{this.id = id;
}
public String getName()
{return name;
}
public void setName(String name)
{this.name = name;
}
public float getSalary()
{return salary;
}
public void setSalary(float salary)
{this.salary = salary;
}
public String getDesignation()
{return designation;
}
public void setDesignation(String designation)
{this.designation = designation;
}

EmpController.java :-
package com.javatpoint.controllers;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

12202040701081 Krishna Ghandi 83


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.javatpoint.beans.Emp;
import com.javatpoint.dao.EmpDao;
@Controller
public class EmpController
{@Autowired
EmpDao dao;//will inject dao from XML file

/*It displays a form to input data, here "command" is a reserved request attribute
*which is used to display object data into form
*/ @RequestMapping("/empform")
public String showform(Model m){
m.addAttribute("command", new Emp());
return "empform";
}
/*It saves object into database. The @ModelAttribute puts request data
* into model object. You need to mention RequestMethod.POST method
* because default request is GET*/
@RequestMapping(value="/save",method = RequestMethod.POST)
public String save(@ModelAttribute("emp") Emp emp){
dao.save(emp);
return "redirect:/viewemp";//will redirect to viewemp request mapping
}
/* It provides list of employees in model object */
@RequestMapping("/viewemp")
public String viewemp(Model
m){ List<Emp>
list=dao.getEmployees();
m.addAttribute("list",list);
return "viewemp";
}
/* It displays object data into form for the given id.
* The @PathVariable puts URL data into variable.*/
@RequestMapping(value="/editemp/{id}")
public String edit(@PathVariable int id, Model
m){Emp emp=dao.getEmpById(id);
m.addAttribute("command",emp);
return "empeditform";
}
/* It updates model object. */
@RequestMapping(value="/editsave",method = RequestMethod.POST)
public String editsave(@ModelAttribute("emp") Emp emp){
dao.update(emp);
return "redirect:/viewemp";
}

12202040701081 Krishna Ghandi 84


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)

/* It deletes record for the given id in URL and redirects to /viewemp */


@RequestMapping(value="/deleteemp/{id}",method = RequestMethod.GET)
public String delete(@PathVariable int id){
dao.delete(id);
return "redirect:/viewemp";
}
}

EmpDao.java :-
package com.javatpoint.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import com.javatpoint.beans.Emp;

public class EmpDao


{ JdbcTemplate
template;

public void setTemplate(JdbcTemplate template)


{this.template = template;
}
public int save(Emp p){
String sql="insert into Emp99(name,salary,designation)
values('"+p.getName()+"',"+p.getSalary()+",'"+p.getDesignation()+"')";
return template.update(sql);
}
public int update(Emp p){
String sql="update Emp99 set name='"+p.getName()+"',
salary="+p.getSalary()+",designation='"+p.getDesignation()+"' where id="+p.getId()+"";
return template.update(sql);
}
public int delete(int id){
String sql="delete from Emp99 where id="+id+"";
return template.update(sql);
}
public Emp getEmpById(int id){
String sql="select * from Emp99 where id=?";
return template.queryForObject(sql, new Object[]{id},new
BeanPropertyRowMapper<Emp>(Emp.class));
}
public List<Emp> getEmployees(){
return template.query("select * from Emp99",new
RowMapper<Emp>(){public Emp mapRow(ResultSet rs, int row)
throws SQLException {
Emp e=new Emp();

12202040701081 Krishna Ghandi 85


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)
e.setId(rs.getInt(1));
e.setName(rs.getString(2));
e.setSalary(rs.getFloat(3));
e.setDesignation(rs.getString(4));
return e;
}
});
}
}

web.xml :-
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>SpringMVC</display-name>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

spring-servlet.xml :-
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.javatpoint.controllers"></context:component-scan>

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>

<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">


12202040701081 Krishna Ghandi 86
Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)

<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>


<property name="url" value="jdbc:mysql://localhost:3306/test"></property>
<property name="username" value=""></property>
<property name="password" value=""></property>
</bean>

<bean id="jt" class="org.springframework.jdbc.core.JdbcTemplate">


<property name="dataSource" ref="ds"></property>
</bean>

<bean id="dao" class="com.javatpoint.dao.EmpDao">


<property name="template" ref="jt"></property>
</bean>
</beans>

index.jsp :-
<a href="empform">Add Employee</a>
<a href="viewemp">View Employees</a>

empform.jsp :-
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<h1>Add New Employee</h1>


<form:form method="post" action="save">
<table >
<tr>
<td>Name : </td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td>Salary :</td>
<td><form:input path="salary" /></td>
</tr>
<tr>
<td>Designation :</td>
<td><form:input path="designation" /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="Save" /></td>
</tr>
</table>
</form:form>

12202040701081 Krishna Ghandi 87


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)

empeditform.jsp :-
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<h1>Edit Employee</h1>
<form:form method="POST" action="/SpringMVCCRUDSimple/editsave">
<table >
<tr>
<td></td>
<td><form:hidden path="id" /></td>
</tr>
<tr>
<td>Name : </td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td>Salary :</td>
<td><form:input path="salary" /></td>
</tr>
<tr>
<td>Designation :</td>
<td><form:input path="designation" /></td>
</tr>

<tr>
<td> </td>
<td><input type="submit" value="Edit Save" /></td>
</tr>
</table>
</form:form>

viewemp.jsp :-
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<h1>Employees List</h1>
<table border="2" width="70%" cellpadding="2">
<tr><th>Id</th><th>Name</th><th>Salary</th><th>Designation</th><th>Edit</th><th>Delete</th
></tr>
<c:forEach var="emp" items="${list}">
<tr>
<td>${emp.id}</td>
<td>${emp.name}</td>
<td>${emp.salary}</td>
<td>${emp.designation}</td>
<td><a href="editemp/${emp.id}">Edit</a></td>
<td><a href="deleteemp/${emp.id}">Delete</a></td>

12202040701081 Krishna Ghandi 88


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)

</tr>
</c:forEach>
</table>
<br/>
<a href="empform">Add New Employee</a>

Output :-

12202040701081 Krishna Ghandi 89


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)

12202040701081 Krishna Ghandi 90


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)

12202040701081 Krishna Ghandi 91


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)

Practical – 11

Aim :-
Write an application to keep, update and retrieve record of student. The record includes
student name, enrollment no, semester, dept, percentage, etc. Use SPRING MVC
architecture

index.jsp :-
<form action="register.jsp" method="post">
Name:<input type="text" name="name"/><br><br/>
Password:<input type="password" name="password"/><br><br/>
Email ID:<input type="text" name="email"/><br><br/>
<input type="submit" value="register"/>"

</form>

register.jsp :-
<%@page import="com.javatpoint.mypack.UserDao"%>
<jsp:useBean id="obj" class="com.javatpoint.mypack.User">
</jsp:useBean>
<jsp:setProperty property="*" name="obj"/>

<%
int i=UserDao.register(obj);
if(i>0)
out.print("You are successfully registered");

%>

User.java :-
package com.javatpoint.mypack;

public class User {


private int id;
private String name,password,email;

//getters and setters

user.hbm.xml :-
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 5.3//EN"

12202040701081 Krishna Ghandi 92


Bachelor of Technology (Computer Engineering)
Advanced Java Programming (202045605)

"http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">

<hibernate-mapping>
<class name="com.javatpoint.mypack.User" table="u400">
<id name="id">
<generator class="increment"></generator>
</id>
<property name="name"></property>
<property name="password"></property>
<property name="email"></property>
</class>

</hibernate-mapping>

UserDao.java :-
package com.javatpoint.mypack;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

public class UserDao {

public static int register(User


u){int i=0;

StandardServiceRegistry ssr = new


StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
Metadata meta = new MetadataSources(ssr).getMetadataBuilder().build();

SessionFactory factory = meta.getSessionFactoryBuilder().build();


Session session = factory.openSession();
Transaction t = session.beginTransaction();

i=(Integer)session.save(u);

t.commit();
session.close();

return i;

}
}

12202040701081 Krishna Ghandi 93


102045605 Advanced Java Programming

hibernate.cfg.xml :-
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 5.3//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">

<hibernate-configuration>

<session-factory>
<property name="hbm2ddl.auto">create</property>
<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="connection.username">system</property>
<property name="connection.password">jtp</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>

<mapping resource="user.hbm.xml"/>
</session-factory>

</hibernate-configuration>

12202040701073 94

You might also like