Practical - 1 Aim:-: 1 Krishna Ghandi 12202040701081
Practical - 1 Aim:-: 1 Krishna Ghandi 12202040701081
Practical - 1 Aim:-: 1 Krishna Ghandi 12202040701081
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;
while(flag){
System.out.println("\nEnter 1 For Insert");
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");
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:
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);
}
}
}
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>
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;
Output :-
PRACTICAL - 3
Aim :-
Convert following servlets in MVC architecture. Write different servlets whichget data from
html form and perform following database operations.
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>
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"));
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 {
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 {
Delete_Student :-
import java.io.IOException;
@WebServlet(urlPatterns = {"/Delete_Student"})
public class Delete_Student extends HttpServlet {
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 {
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>");
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"})
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>");
Output :-
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>
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":
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.*;
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>");
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 =
?");
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)
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>");
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)
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{
out.println("</body>");
out.println("</html>");
}
}
}
Output :-
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.*;
/**
* 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"
</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>
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;
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;
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.">
/**
/**
* 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.
*
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 {
/**
* 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>
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>
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);
} catch (Exception e) {
out.print(e);
}
%>
</body>
</html>
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>"
);
} catch (Exception e) {
out.println(e);
}
%>
</body>
</html>
Output :-
Update.jsp :-
<%@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");
} catch (Exception e) {
out.print(e);
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>
Output :-
Delete.jsp :-
<%@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);
}
%>
Output :-
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/>
<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 {
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>();
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>
</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>
</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);
%>
<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>
</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");
%>
Output :-
PRACTICAL - 9
Aim :-
Rewrite all .jsp pages of previous labs using EL and JSTL.
package com.journaldev.model;
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;
import javax.servlet.http.HttpServletResponse;
import com.journaldev.model.Employee;
@WebServlet("/HomeServlet")
public class HomeServlet extends HttpServlet
{ private static final long serialVersionUID =
1L;
JSP Page :-
Output :-
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;
EmpController.java :-
package com.javatpoint.controllers;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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";
}
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;
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>
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"%>
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>
</tr>
</c:forEach>
</table>
<br/>
<a href="empform">Add New Employee</a>
Output :-
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;
user.hbm.xml :-
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 5.3//EN"
"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;
i=(Integer)session.save(u);
t.commit();
session.close();
return i;
}
}
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