0% found this document useful (0 votes)
338 views104 pages

A - 69 - 180770107233 - Apj Lab Manual

This document outlines the laboratory manual for the Advanced Java Programming course at Silver Oak College of Engineering and Technology. It provides instructions for students on lab protocols and assessments. The manual also lists several experiments involving TCP networking, cookies, databases, and web applications for students to complete in the course.

Uploaded by

Mihir Vaghela
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
338 views104 pages

A - 69 - 180770107233 - Apj Lab Manual

This document outlines the laboratory manual for the Advanced Java Programming course at Silver Oak College of Engineering and Technology. It provides instructions for students on lab protocols and assessments. The manual also lists several experiments involving TCP networking, cookies, databases, and web applications for students to complete in the course.

Uploaded by

Mihir Vaghela
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 104

Silver Oak College of Engineering & Technology

GUJARAT TECHNOLOGICAL UNIVERSITY


BACHELOR OF ENGINEERING

ADVANCED JAVA PROGRAMMING


(3160707)
6thSEMESTER

COMPUTER ENGINEERING

Laboratory Manual

1
VISION
To create competent professionals in the field of Computer Engineering and promote research
with a motive to serve as a valuable resource for the IT industry and society.

MISSION

1. To produce technically competent and ethically sound Computer Engineering


professionals by imparting quality education, training, hands on experience and value
based education.
2. To inculcate ethical attitude, sense of responsibility towards society and leadership ability
required for a responsible professional computer engineer.
3. To pursue creative research, adapt to rapidly changing technologies and promote self-
learning approach in Computer Engineering and across disciplines to serve the dynamic
needs of industry, government and society.

Program Educational Objectives (PEO):

PEO1: To provide the fundamentals of science, mathematics, electronics and computer science and
engineering and skills necessary for a successful IT professional.

PEO2: To provide scope to learn, apply skills, techniques and competency to use modern
engineering tools to solve computational problems.

PEO3: To enable young graduates to adapt to the challenges of evolving career opportunities in their
chosen fields of career including higher studies, research avenues, entrepreneurial activities
etc.

PEO4: To inculcate life-long learning aptitude, leadership qualities and teamwork ability with sense
of ethics for a successful professional career in their chosen field.

2
PROGRAM OUTCOMES (POs) Engineering Graduates will be able to:

1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering
problems.
2. Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.
3. Design/development of solutions: Design solutions for complex engineering problems and
design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.
4. Conduct investigations of complex problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis
of the information to provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modelling to complex
engineering activities with an understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant
to the professional engineering practice.
7. Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and
need for sustainable development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or leader
in diverse teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and
write effective reports and design documentation, make effective presentations, and give
and receive clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member
and leader in a team, to manage projects and in multidisciplinary environments.
12. Life-long learning: Recognize the need for, and have the preparation and ability to engage
in independent and life-long learning in the broadest context of technological change

3
ADVANCED JAVA PROGRAMMING PRACTICAL BOOK

DEPARTMENT OF COMPUTER ENGINEERINGPREFACE

It gives us immense pleasure to present the first edition of Advanced Java Practical Book
for the B.E. 3rd year students of Silver Oak Group of Institutes.

The theory and laboratory course of Advanced Java, at Silver Oak Group of Institutes,
Ahmedabad, is designed in such a manner that students can develop the basic
understanding of the subject during theory classes and gain the hands-on practical
experience during their laboratory sessions. Java being one of the most prominent
languages opens the door to many application developments involving naïves of
Input/output, Networking, the standard utilities, Applets, Frameworks, GUI-based
controls and much more. Many of these concepts were detailed in our first part in Object
Oriented Programming using Java. In this second part of java, Advanced Java, we will
look into networking concepts using TCP/UDP, Java Database Connectivity, web
application development with Servlet, JSP and JSF, frameworks like Hibernate and
Spring.

The Laboratory Manual presented here takes you onto the learning journey of advanced
concepts of Java. In this you will be exploring the wide range of topics like creating a
network application with help of TCP/UDP connection, linking & communication a
database with java application using JDBC, creating a dynamic server side web
application using Servlet, Java Server Pages and Java Server Faces. We will also look into
the hibernate Object Relational Mapping (ORM) framework and application
frameworkSpring.

Lab Manual Revised by: Prof. Viren Patel, Silver Oak College of Engineering and Technology

Lab Manual Revision No.: SOCET_3160707_LM_2021_1

4
INSTRUCTIONS TO STUDENTS

1. Be prompt in arriving to the laboratory and always come well prepared for the
experiment.
2. Students need to maintain a proper decorum in the computer lab. Students must use
the equipment with care. Any damage is caused is punishable.
3. Students are instructed to come to lab in formal dresses only.
4. Students are supposed to occupy the systems allotted to them and are not supposed to
talk or make noise in the lab.
5. Students are required to carry their observation book and lab records with completed
exercises while entering the lab.
6. Lab records need to be submitted every week.
7. Students are not supposed to use pen drives in the lab.
8. The grades for the Advanced Java Practical course work will be awarded based on
your performance in the laboratory, regularity, recording of experiments in the
Advanced Java practical Final Notebook, lab quiz, regular viva-voce and end-term
examination.
9. Find the answers of all the questions mentioned under the section, Post Practical
Questions‟ at the end of each experiment in the Advanced Java Practical Book.

5
CERTIFICATE

This is to certify that

Mr./Ms. Dharmraj Sorathiya with enrolment no. 180770107233 from

Semester 6th ,Div-A has successfully completed his/her laboratory

experiments in the ADVANCED JAVA PROGRAMMING (3160707)from

the department of Computer Engineering during the academic year 2020

-2021

Date of Submission: 25-04-2021 Staff In charge: ...........................

Head of Department: Dr. Satvik Khara

6
TABLE OF CONTENT

Page No
Marks
Date of Date of
Experiment Title Sign (out of
Sr. Start Completion
10)
No To From

Implement TCP Server for


transferring files using Socket
1 and ServerSocket.
Implement TCP Server
programming in which more
than one client can connect and
communicate with Server for
2
sending the string and server
returns the reverse of string to
each of client.
Implement cookies to store
3 firstname and lastname using
Java server pages.
Implement the shopping cart
for users for the online
4
shopping. Apply the concept of
session.
Implement student registration
form with enrollment number,
first name, last name, semester,
contact number. Store the
5
details in database. Also
implement search, delete and
modify facility for student
records.
Write a Servlet program to
6 print system date and time.
Write a Servlet to create a
Login form with help of
request-dispatcher. If the login
7 fails, it should redirect back to
loginpage, else to the next
page.

7
Design a web page that takes
the Username from user and if
it is a valid username prints
8
“Welcome Username”. Use
JSF to implement.
Write Hibernate application to
store customer records and
9 retrieve the customer record
including name, contact
number, address.
Write an application to keep
record and retrieve record of
student. The record includes
10 student id, enrollment number,
semester, SPI. Use MVC
architecture.

8
PRACTICAL SET – 1
The java.net package of the J2SE APIs contains a collection of classes and interfaces that provide
the low-level communication details, allowing you to write programs that focus on solving the
problem athand.
The java.net package provides support for the two common network protocols

TCP − TCP stands for Transmission Control Protocol, which allows


for reliable communication between two applications. TCP is
typically used over the Internet Protocol, which is referred to
asTCP/IP.

UDP − UDP stands for User Datagram Protocol, a connection-less


protocol that allows for packets of data to be transmitted
betweenapplications.

The two key classes from the java.net package used in creation of server and client programs are:
ServerSocket
Socket
A server program creates a specific type of socket that is used to listen for client requests (server
socket), In the case of a connection request, the program creates a new socket through which it
will exchange data with the client using input and output streams. The socket abstraction is very
like the file concept: developers must open a socket, perform I/O, and close it. Figure illustrates
key steps involved in creating socket-based server and client programs.
Socket-based client and server programming
TCP/IP SOCKET PROGRAMMING

A simple Server Program in Java The steps for creating a simple server program are:
1. Open the ServerSocket:
ServerSocket server = new ServerSocket (PORT );
2. Wait for the Client Request:
Socket client =server.accept();
3. Create I/O streams for communicating to theclient
DataInputStream is = new DataInputStream(client.getInputStream());
DataOutputStream os = new DataOutputStream(client.getOutputStream());
4. Perform communication withclient
Receive from client: String line = is.readLine();
Send to client: os.writeBytes(“Hello\n”);
5. Close socket:
client.close()
;

A simple Client Program in Java The steps for creating a simple client program are:
1. Create a SocketObject:
Socket client = new Socket (server, port_id);
2. Create I/O streams for communicating with the server.
is = newDataInputStream(client.getInputStream());
os = new DataOutputStream(client.getOutputStream());
3. Perform I/O or communication with theserver:
Receive data from the server: String line = is.readLine();
Send data to the server: os.writeBytes(“Hello\n”);
4. Close the socket when done:
client.close();

References:

[1] http://www.buyya.com/java/Chapter13.pdf
[2] Complete Reference J2EE Publisher :McGrawpublication
Aim : Implement TCP Server for transferring files using Socket and ServerSocket.

Code:

Server Code:

import java.io.*;

import java.net.*;

class Server

public static void main(String args[]) throws Exception

ServerSocketss=new ServerSocket(7777);

Socket s=ss.accept();

System.out.println("connected..........");

FileInputStream fin=new FileInputStream("Send.txt");

DataOutputStreamdout=new DataOutputStream(s.getOutputStream());

int r;

while((r=fin.read())!=-1)

dout.write(r);

System.out.println("\nFiletranfer Completed");

s.close();

ss.close();

}
Client Code:

import java.io.*;

import java.net.*;

public class Client {

public static void main(String[] args) throws Exception

Socket s=new Socket("127.0.0.1",7777);

if(s.isConnected())

System.out.println("Connected to server");

FileOutputStreamfout= new FileOutputStream("received.txt");

DataInputStream din=new DataInputStream(s.getInputStream());

int r;

while((r=din.read())!=-1)

fout.write((char)r);

s.close();

}
Output:
Conclusion: : From this practical, we learned about how socket programming works and how to transfer any data
using socket programming.
PRACTICAL SET – 2
java.io.DataInputStream.readUTF() Method

Description : The java.io.DataInputStream.readUTF() method reads in a string that has been


encoded using a modified UTF-8 format. The string of character is decoded from the UTF and
returned as String.
Declaration : public final String readUTF()

Parameters: NA

Return Value: This method returns a unicode string.

Exception:
IOException − If the stream is closed or the or

any I/O error occurs. EOFException − If the input

stream has reached the ends.

UTFDataFormatException − If the bytes do not represent a valid modified


UTF-8 encoding.

java.io.DataOutputStream.writeUTF() Method
Description: The java.io.DataOuputStream.writeUTF(String str) method writes a string to the
underlying output stream using modified UTF-8 encoding.
Declaration: public final void writeUTF(String str)
Parameters: str − a string to be written to

the output stream. Return Value : This method

does not return any value.

Exception:
IOException − If an I/O error occurs.

Datagrams:
TCP guarantees the delivery of packets and preserves their order on destination. Sometimes these
features are not required and since they do not come without performance costs, it would be better
to use a lighter transport protocol. This kind of service is accomplished by the UDP protocol which
conveys datagram packets.
Datagram packets are used to implement a connectionless packet delivery service supported by the
UDP protocol. Each message is transferred from source machine to destination based on
information contained within that packet. That means, each packet needs to have destination
address and each packet might be routed differently, and might arrive in any order. Packet delivery
is not guaranteed.
The format of datagram packet is:
| Msg | length | Host | serverPort |
Java supports datagram communication through the following classes:
● DatagramPacket
● DatagramSocket

The class DatagramPacket contains several constructors that can be used for creating packet
object.
One of them is:
DatagramPacket(byte[] buf, int length, InetAddress address, int port);
This constructor is used for creating a datagram packet for sending packets of length length to the
specified port number on the specified host. The message to be transmitted is indicated in the
firstargument.
The key methods of DatagramPacket class are:
byte[]getData(): Returns the data buffer.
intgetLength(): Returns the length of the data to be sent or the length of the data received.
void setData(byte[]buf): Sets the data buffer for thispacket.
void setLength(intlength) : Sets the length for thispacket.

The class DatagramSocket supports various methods that can be used for transmitting or
receiving data a datagram over the network.

References:

[1] https://www.tutorialspoint.com/java/io/dataoutputstream_writeutf.htm
[2] Complete Reference J2EE Publisher :McGraw publication
Aim - Implement TCP Server programming in which more than one client can connect and
communicate with Server for sending the string and server returns the reverse of string to each of
client.

Code:

Server Code:
import java.net.*;

import java.io.*;

public class Server


{

public static void main(String[] args)throws Exception


{
int count=1;
System.out.println("Server is running...................");
ServerSocket ss=new ServerSocket(7878);

while(true)
{
new RevThread(ss.accept(),count).start();
System.out.println(count+" client connected");
count++;

}
}
}

class RevThread extends Thread

{
Socket s=null;
int n;

public RevThread(Socket socket,int count)


{
s=socket;
n=count;
}

public void run()


{
try
{
while(true)

{
System.out.println("receiving from client "+n);
DataInputStream din=new DataInputStream(s.getInputStream());
String str=din.readUTF();
System.out.println("processing data of Client "+n);

StringBuffer rev=new StringBuffer();


rev=rev.append(str);
rev=rev.reverse();
String revStr=new String(rev);
System.out.println("sending to client "+n);

DataOutputStream dout=new DataOutputStream(s.getOutputStream());


dout.writeUTF(revStr);
}
}
catch(IOException e)

{
System.out.println(e);
}
}

}
Client Code:
import java.io.*;
import java.net.*;
public class Client

{
public static void main(String[] args) throws Exception
{
Socket s=new Socket("127.0.0.1",7878);
if(s.isConnected())

{
System.out.println("Connected to Server....");
}
while(true)
{

System.out.println("Enter String to reverse:");


DataInputStream in=new DataInputStream(System.in);
String str=in.readLine();
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
dout.writeUTF(str);

DataInputStream din=new DataInputStream(s.getInputStream());


String rev=din.readUTF();
System.out.println("Reversed String:\t"+rev);
}

}
}
Output:
Conclusion:
From this practical, we learned about how socket programming works and how to transfer any data using socket
programming.
PRACTICAL SET – 3

In a web application, server may be responding to several clients at a time so session tracking is a
way by which a server can identify the client. As we know HTTP protocol is stateless which means
client needs to open a separate connection every time it interacts with server and server treats each
request as a newrequest.
Now to identify the client, server needs to maintain the state and to do so , there are several session
tracking techniques.
a) Cookies
b) HiddenFields
c) URLRewriting
d) SessionObject
Cookie

Cookie is a key value pair of information, sent by the server to the browser and then browser
sends back this identifier to the server with every request there on.
There are two types of cookies:
Session cookies - are temporary cookies and are deleted as soon as user closes the browser. The
next time user visits the same website, server will treat it as a new client as cookies are already
deleted.
Persistent cookies - remains on hard drive until we delete them or they expire.
URL Rewriting
URL Rewriting is the approach in which a session (unique) identifier gets appended with each
request URL so server can identify the user session.

For example if we apply URL rewriting on http://localhost:8080/jsp-tutorial/home.jsp , it will


become something like ?jSessionId=XYZ where jSessionId=XYZ is the attached session identifier
and value XYZ will be used by server to identify the user session.
References:
[1] https://www.javatpoint.com/jsp-implicit-objects
[2] Professional Java Server Prog by Subrahmanyam Allamaraju, Cedric Buest WileyPub.
Aim -Implement cookies to store firstname and lastname using Java server pages.
Code

Main.jsp file
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>

</head>
<body>
<%
// Create cookies for first and last names.
Cookie firstName = new Cookie("first_name", request.getParameter("first_name"));

Cookie lastName = new Cookie("last_name", request.getParameter("last_name"));


%>
<html>
<head>
<title>Setting Cookies</title>

</head>
<body>
<center>
<h1>Setting Cookies</h1>
</center>

<ul>
<li><p><b>First Name:</b>
<%= request.getParameter("first_name")%>

</p></li>
<li><p><b>Last Name:</b>
<%= request.getParameter("last_name")%>
</p></li>
</ul>

</body>
</html>
</body>
</html>

hello.jsp file

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>

</head>
<body>
<form action = "main.jsp" method = "GET">
First Name: <input type = "text" name = "first_name">
<br />

Last Name: <input type = "text" name = "last_name" />


<br />
<input type = "submit" value = "Submit" />
</form>

</body>
Output:

Conclusion: From this practical we learned how to set particular cookies. This above practical will display the
first name and the last name on your screen and will also set two cookies firstName and lastName. These cookies
will be passed back to the server the next time you click the Submit button
PRACTICAL SET – 4

Action Tags: JSP provides various action tags or elements. Each JSP action tag is used to perform
some specific tasks. The action tags are used to control the flow between pages and to use Java
Bean. A Java Bean is a java class that should follow following conventions: It should have a no-
arg constructor. It should be Serializable. It should provide methods to set and get the values of
the properties, known as getter and setter methods. A bean encapsulates many objects into one
object, so we can access this object from multiple places. Here, are mentioned action tags used
with Bean Class:
The <jsp:useBean> action tag is used to locate or instantiate a bean class. If bean object of the
Bean class is already created, it doesn't create the bean depending on the scope. But if object of
bean is not created, it instantiates the bean.
<jsp:useBean id = "students" class = "Bean.StudentBean">

The setProperty and getProperty action tags are used for developing web application with Java
Bean. In web devlopment, bean class is mostly used because it is a reusable software component
that represents data.
The jsp:setProperty action tag sets a property value or values in a bean using the setter method.
<jsp:setProperty name="bean" property="username" value="abc" />
The jsp:getProperty action tag returns the value of the property.
<jsp:getProperty name="obj" property="name" />

JSP implicit objects are created by servlet container while translating JSP page to Servlet source
to help developers. We can use implicit objects in JSP directly in scriptlets that goes in service -
method. However we can‟t use
jsp implicit objects in JSP
declaration because that code
will go at class level.

We have 9 jsp implicit objects


that we can directly use in JSP
page. Seven of them are
declared as local variable at the
start of _jspService() method
whereas two of them are part of
_jspService() method argument
that we can use.
Request Object : It is also an implicit object of class HttpServletRequest class and using this
object request parameters can be accessed.

Syntax:
request.getParameters(“Name”); ( where “Name” is the formelement)
Session Object : Session object is of class HttpSession and used to maintain the session
information. It stores the information in Name-Value pair.
Syntax:
session.setAttribute(“Name”,”Id”); | session.getAttribute("Name");
References:
[1] https://www.javatpoint.com/jsp-implicit-objects
[2] https://www.tutorialspoint.com/jsp/jsp_implicit_objects.htm
Aim: Implement the shopping cart for users for the online shopping. Apply the concept of session.

Code :

CartItemBean:

package in.techfreaks.shoppingcart.beans;

public class CartItemBean {


private String strPartNumber;
private String strModelDescription;
private double dblUnitCost;

private int iQuantity;


private double dblTotalCost;

public String getPartNumber() {


return strPartNumber;

}
public void setPartNumber(String strPartNumber) {
this.strPartNumber = strPartNumber;
}
public String getModelDescription() {

return strModelDescription;
}
public void setModelDescription(String strModelDescription) {
this.strModelDescription = strModelDescription;
}
public double getUnitCost() {
return dblUnitCost;

}
public void setUnitCost(double dblUnitCost) {
this.dblUnitCost = dblUnitCost;
}
public int getQuantity() {

return iQuantity;
}
public void setQuantity(int quantity) {
iQuantity = quantity;
}

public double getTotalCost() {


return dblTotalCost;
}
public void setTotalCost(double dblTotalCost) {
this.dblTotalCost = dblTotalCost;

}
}

CartBean:

package in.techfreaks.shoppingcart.beans;

import java.util.ArrayList;
public class CartBean {
private ArrayList alCartItems = new ArrayList();

private double dblOrderTotal ;

public int getLineItemCount() {


return alCartItems.size();
}

public void deleteCartItem(String strItemIndex) {


int iItemIndex = 0;
try {
iItemIndex = Integer.parseInt(strItemIndex);

alCartItems.remove(iItemIndex - 1);
calculateOrderTotal();
} catch(NumberFormatException nfe) {
System.out.println("Error while deleting cart item: "+nfe.getMessage());
nfe.printStackTrace();

}
}

public void updateCartItem(String strItemIndex, String strQuantity) {


double dblTotalCost = 0.0;

double dblUnitCost = 0.0;


int iQuantity = 0;
int iItemIndex = 0;
CartItemBean cartItem = null;
try {

iItemIndex = Integer.parseInt(strItemIndex);
iQuantity = Integer.parseInt(strQuantity);
if(iQuantity>0) {
cartItem = (CartItemBean)alCartItems.get(iItemIndex-1);

dblUnitCost = cartItem.getUnitCost();
dblTotalCost = dblUnitCost*iQuantity;
cartItem.setQuantity(iQuantity);
cartItem.setTotalCost(dblTotalCost);
calculateOrderTotal();

}
} catch (NumberFormatException nfe) {
System.out.println("Error while updating cart: "+nfe.getMessage());
nfe.printStackTrace();
}

public void addCartItem(String strModelNo, String strDescription,


String strUnitCost, String strQuantity) {

double dblTotalCost = 0.0;


double dblUnitCost = 0.0;
int iQuantity = 0;
CartItemBean cartItem = new CartItemBean();
try {

dblUnitCost = Double.parseDouble(strUnitCost);
iQuantity = Integer.parseInt(strQuantity);
if(iQuantity>0) {
dblTotalCost = dblUnitCost*iQuantity;
cartItem.setPartNumber(strModelNo);

cartItem.setModelDescription(strDescription);
cartItem.setUnitCost(dblUnitCost);
cartItem.setQuantity(iQuantity);
cartItem.setTotalCost(dblTotalCost);

alCartItems.add(cartItem);
calculateOrderTotal();
}

} catch (NumberFormatException nfe) {

System.out.println("Error while parsing from String to primitive types: "+nfe.getMessage());


nfe.printStackTrace();
}
}

public void addCartItem(CartItemBean cartItem) {


alCartItems.add(cartItem);
}

public CartItemBean getCartItem(int iItemIndex) {

CartItemBean cartItem = null;


if(alCartItems.size()>iItemIndex) {
cartItem = (CartItemBean) alCartItems.get(iItemIndex);
}
return cartItem;

public ArrayList getCartItems() {


return alCartItems;
}

public void setCartItems(ArrayList alCartItems) {


this.alCartItems = alCartItems;
}
public double getOrderTotal() {

return dblOrderTotal;
}
public void setOrderTotal(double dblOrderTotal) {
this.dblOrderTotal = dblOrderTotal;
}

protected void calculateOrderTotal() {


double dblTotal = 0;
for(int counter=0;counter<alCartItems.size();counter++) {
CartItemBean cartItem = (CartItemBean) alCartItems.get(counter);

dblTotal+=cartItem.getTotalCost();

}
setOrderTotal(dblTotal);
}

CartController:

package in.techfreaks.shoppingcart.servlet;

import in.techfreaks.shoppingcart.beans.CartBean;

import java.io.IOException;

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 CartController extends HttpServlet {

//public static final String addToCart

public void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

String strAction = request.getParameter("action");

if(strAction!=null && !strAction.equals("")) {


if(strAction.equals("add")) {

addToCart(request);
} else if (strAction.equals("Update")) {
updateCart(request);
} else if (strAction.equals("Delete")) {
deleteCart(request);

}
}
response.sendRedirect("../ShoppingCart.jsp");
}

protected void deleteCart(HttpServletRequest request) {


HttpSession session = request.getSession();
String strItemIndex = request.getParameter("itemIndex");
CartBean cartBean = null;

Object objCartBean = session.getAttribute("cart");


if(objCartBean!=null) {
cartBean = (CartBean) objCartBean ;
} else {

cartBean = new CartBean();


}
cartBean.deleteCartItem(strItemIndex);
}

protected void updateCart(HttpServletRequest request) {


HttpSession session = request.getSession();
String strQuantity = request.getParameter("quantity");
String strItemIndex = request.getParameter("itemIndex");

CartBean cartBean = null;

Object objCartBean = session.getAttribute("cart");


if(objCartBean!=null) {
cartBean = (CartBean) objCartBean ;

} else {
cartBean = new CartBean();
}
cartBean.updateCartItem(strItemIndex, strQuantity);
}

protected void addToCart(HttpServletRequest request) {


HttpSession session = request.getSession();
String strModelNo = request.getParameter("modelNo");

String strDescription = request.getParameter("description");


String strPrice = request.getParameter("price");
String strQuantity = request.getParameter("quantity");

CartBean cartBean = null;

Object objCartBean = session.getAttribute("cart");

if(objCartBean!=null) {
cartBean = (CartBean) objCartBean ;

} else {
cartBean = new CartBean();
session.setAttribute("cart", cartBean);
}

cartBean.addCartItem(strModelNo, strDescription, strPrice, strQuantity);


}

ShoppingCart.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>www.tech-freaks.in - Shopping Cart</title>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">


</head>
<body>

<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>


<p><font face="Verdana, Arial, Helvetica, sans-serif"><strong>Shopping Cart</strong></font></p>
<p><a href="/ModelList.jsp" mce_href="ModelList.jsp">Model List</a> </p>
<table width="75%" border="1">
<tr bgcolor="#CCCCCC">

<td><strong><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Model


Description</font></strong></td>
<td><strong><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Quantity</font></strong></td>
<td><strong><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Unit
Price</font></strong></td>

<td><strong><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Total</font></strong></td>


</tr>
<jsp:useBean id="cart" scope="session" class="in.techfreaks.shoppingcart.beans.CartBean" />
<c:if test="${cart.lineItemCount==0}">
<tr>

<td colspan="4"><font size="2" face="Verdana, Arial, Helvetica, sans-serif">- Cart is currently empty -<br/>
</tr>
</c:if>
<c:forEach var="cartItem" items="${cart.cartItems}" varStatus="counter">
<form name="item" method="POST" action="servlet/CartController">

<tr>
<td><font size="2" face="Verdana, Arial, Helvetica, sans-serif"><b><c:out
value="${cartItem.partNumber}"/></b><br/>
<c:out value="${cartItem.modelDescription}"/></font></td>
<td><font size="2" face="Verdana, Arial, Helvetica, sans-serif"><input type='hidden' name='itemIndex'
value='<c:out value="${counter.count}"/>'><input type='text' name="quantity" value='<c:out
value="${cartItem.quantity}"/>' size='2'> <input type="submit" name="action" value="Update">
<br/> <input type="submit" name="action" value="Delete"></font></td>
<td><font size="2" face="Verdana, Arial, Helvetica, sans-serif">$<c:out
value="${cartItem.unitCost}"/></font></td>
<td><font size="2" face="Verdana, Arial, Helvetica, sans-serif">$<c:out
value="${cartItem.totalCost}"/></font></td>
</tr>

</form>
</c:forEach>
<tr>
<td colspan="2"> </td>
<td> </td>

<td><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Subtotal: $<c:out


value="${cart.orderTotal}"/></font></td>

</tr>
</table>
</body>
</html>
Output:

Conclusion: In this practical, implementation of shopping cart for users for online shopping using concept of
session is described .
PRACTICAL SET – 5
JDBC stands for Java Database Connectivity, which is a standard Java API for database-
independent connectivity between the Java programming language and a wide range of databases.

The JDBC library includes APIs for each of the tasks mentioned below that are commonly
associated with database usage.

● Making a connection to adatabase.


● Creating SQL or MySQLstatements.
● Executing SQL or MySQL queries in thedatabase.
● Viewing & Modifying the resultingrecords.
Fundamentally, JDBC is a specification that provides a complete set of
interfaces that allows for portable access to an underlying database.
Java can be used to write different types of executables, such as −

● JavaApplications
● JavaApplets
● JavaServlets
● Java ServerPages(JSPs)
● Enterprise JavaBeans(EJBs).
These different executables can use a JDBC driver to access a database, and take advantage of
the storeddata.

The Statement Interface


The Statement interface provides methods to execute queries with the database. The statement
interface is a factory of ResultSet i.e. it provides factory method to get the object of ResultSet.
Commonly used methods of Statement interface:

1) public ResultSet execute Query(String sql): is used to execute SELECT query. It returns the
object of ResultSet.

2) public int executeUpdate(String sql): is used to execute specified query, it may be create,
drop, insert, update, delete etc.

3) public boolean execute(String sql): is used to execute queries that may return multiple
results.

4) public int[] executeBatch(): is used to execute batch of commands.

PreparedStatement
The PreparedStatement interface is a sub interface of Statement. It is used to execute
parameterizedquery.
Let's see the example of parameterized query:
1. String sql="insert into emp values(?,?,?)";

As you can see, we are passing parameter (?) for the values. Its value will be set by calling the
setter methods of PreparedStatement.

Why use PreparedStatement?


Improves performance:
The performance of the application will be faster if you use PreparedStatement interface because
query is compiled only once.

How to get the instance of PreparedStatement?


The prepareStatement() method of Connection interface is used to return the object of
PreparedStatement.
Syntax:
public PreparedStatement prepareStatement(String query) throws SQLException{}

Method Description

public void setInt(int paramIndex, int value) sets the integer value to the given
parameterindex.

public void setString(int paramIndex, String sets the String value to the given parameter
value) index.

public void setFloat(int paramIndex, float sets the float value to the given parameter
value) index.

public void setDouble(int paramIndex, double sets the double value to the given
value) parameterindex.

public int executeUpdate() executes the query. It is used for create,


drop, insert, update, delete etc.

public ResultSet executeQuery() executes the select query. It returns an


instance of ResultSet.

CallableStatement

CallableStatement interface is used to call the stored procedures and functions.

We can have business logic on the database using stored procedures and functions that will make
the performance better because these are precompiled.
Suppose you need the get the age of the employee based on the date of birth, you may create a
function that receives date as the input and returns age of the employee as the output.

What is the difference between stored procedures and functions?


The differences between stored procedures and functions are given below:

Stored Procedure Function

is used to perform business logic. is used to perform calculation.

must not have the return type. must have the return type.

may return 0 or more values. may return only one values.


We can call functions from the procedure. Procedure cannot be called from function.

Procedure supports input and output Function supports only input parameter.
parameters.

Exception handling using try/catch block can Exception handling using try/catch can't be used
be used in stored procedures. in user defined functions.

The prepareCall() method of Connection interface returns the instance of CallableStatement.


Syntax is given below:
1. public CallableStatement prepareCall("{ call procedurename(?,?...?)}");

The example to get the instance of CallableStatement is given below:

1. CallableStatement stmt=con.prepareCall("{call myprocedure(?,?)}");

It calls the procedure my procedure that receives 2 arguments.

References:

[1] https://www.tutorialspoint.com/jdbc/jdbc-sample-code.htm
Aim : Implement student registration form with enrollment number, first name, last name,
semester, contact number. Store the details in database. Also implement search, delete and modify
facility for student records.
Code:

Form.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="Insert.jsp">
<table border="1px solid black">
<tr>
<td>ENROLLMENT_NUMBER: </td>
<td><input type="text" name="en"></td>
</tr>
<tr>
<td>FIRSTNAME: </td>
<td><input type="text" name="fn"></td>
</tr>
<tr>
<td>LASTNAME: </td>
<td><input type="text" name="ln"></td>
</tr>
<tr>
<td>SEMESTER: </td>
<td><input type="text" name="se"></td>
</tr>
<tr>
<td>CONTACT_NUMBER: </td>
<td><input type="text" name="no"></td>
</tr>
<tr>
<td><input type="submit" value="Save"></td>
</tr>
</table>
</form>
<a href="Search.jsp">Search</a>
</body>
</html>

Insert.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1" import="java.sql.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String en = request.getParameter("en");
String fn = request.getParameter("fn");
String ln = request.getParameter("ln");
String se = request.getParameter("se");
String no = request.getParameter("no");
Class.forName("com.mysql.jdbc.Driver");
Connection
c=DriverManager.getConnection("jdbc:mysql://localhost:3306/manual","root","root");
Statement s2 = c.createStatement();
s2.executeUpdate("insert into Prac5(Enrollment,Firstname,Lastname,Semester,Contactno)
values('"+en+"','"+fn+"','"+ln+"','"+se+"','"+no+"')");
s2.close();
c.close();
response.sendRedirect("Form.jsp");
%>
</body>
</html>

Search.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" import="java.sql.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
Class.forName("com.mysql.jdbc.Driver");
Connection
c=DriverManager.getConnection("jdbc:mysql://localhost:3306/manual","root","root");
Statement st = c.createStatement();
ResultSet rs = st.executeQuery("select* from Prac5");
%>
<table border="1px solid black">
<tr>
<th>ID</th>
<th>ENROLLMENT_NUMBER</th>
<th>FIRSTNAME</th>
<th>LASTNAME</th>
<th>SEMESTER</th>
<th>CONTACT_NUMBER</th>
<th>Action</th>
</tr>
<%
while(rs.next())
{
int id = rs.getInt("id");
String en = rs.getString("Enrollment");
String fn = rs.getString("Firstname");
String ln = rs.getString("Lastname");
String se = rs.getString("Semester");
String no = rs.getString("Contactno");
%>
<tr>
<td><% out.println(id);%></td>
<td><% out.println(en);%></td>
<td><% out.println(fn);%></td>
<td><% out.println(ln);%></td>
<td><% out.println(se);%></td>
<td><% out.println(no);%></td>
<td><a href="Delete.jsp?x=<%=id%>">Delete</a></td>
<td><a href="Edit.jsp?y=<%=id%>">Edit</a></td>
</tr>
<%
}
%>
</body>
</html>

Edit.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" import="java.sql.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
int id = Integer.parseInt(request.getParameter("y"));
int i=0;
Class.forName("com.mysql.jdbc.Driver");
Connection c = DriverManager.getConnection("jdbc:mysql://localhost/manual","root","root");
Statement st = c.createStatement();
ResultSet rs =st.executeQuery("select * from Prac5 where id = "+ id);
%>
<%
while(rs.next())
{
int id1 = rs.getInt("id");
String en = rs.getString("Enrollment");
String fn = rs.getString("Firstname");
String ln = rs.getString("Lastname");
String se = rs.getString("Semester");
String no = rs.getString("Contactno");
%>
<form action="Update.jsp">
<table border="1px solid black">
<tr>
<td><input type="hidden" name="id1" value='<%=id1%>'></td>
</tr>
<tr>
<td>ENROLLMENT_NUMBER: </td>
<td><input type="text" name="en" value="<%=en%>"></td>
</tr>
<tr>
<td>FIRSTNAME: </td>
<td><input type="text" name="fn" value="<%=fn%>"></td>
</tr>
<tr>
<td>LASTNAME: </td>
<td><input type="text" name="ln" value="<%=ln%>"></td>
</tr>
<tr>
<td>SEMESTER: </td>
<td><input type="text" name="se" value="<%=se%>"></td>
</tr>
<tr>
<td>CONTACT_NUMBER: </td>
<td><input type="text" name="no" value="<%=no%>"></td>
</tr>
<tr>
<td><input type="submit" value="Update"></td>
</tr>
</table>
</form>
<%
}
c.close();
st.close();
%>
</body>
</html>

Update.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" import="java.sql.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
int id =Integer.parseInt( request.getParameter("id1"));
String en = request.getParameter("en");
String fn = request.getParameter("fn");
String ln = request.getParameter("ln");
String se = request.getParameter("se");
String no = request.getParameter("no");
Class.forName("com.mysql.jdbc.Driver");
Connection c = DriverManager.getConnection("jdbc:mysql://localhost/manual","root","root");
Statement st =c.createStatement();
st.executeUpdate("update Prac5 set Enrollment='"+en+"', Firstname='"+fn+"',
Lastname='"+ln+"',
Semester='"+se+"', Contactno='"+no+"' where id='"+id+"'");
st.close();
c.close();
response.sendRedirect("Search.jsp");
%>
</body>
</html>

Delete.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" import="java.sql.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
int id = Integer.parseInt(request.getParameter("x"));
Class.forName("com.mysql.jdbc.Driver");
Connection
c=DriverManager.getConnection("jdbc:mysql://localhost:3306/manual","root","root");
Statement st = c.createStatement();
st.executeUpdate("delete from Prac5 where id="+id);
st.close();
c.close();
response.sendRedirect("Search.jsp");
%>
</body>
</html>
Output
Conclusion:
In this practical, student registration form is displayed with its all functionalities .
PRACTICAL SET – 6

Servlets: Servlets are small programs that execute on the server side of a web connection, it
dynamically extends the functionality of a web server. It is used to create a web application that
reside on the server side and generate a dynamic web page.

The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing our
own servlets. The javax.servlet package contains many interfaces and classes that are used by the
servlet or web container. These are not specific to any protocol. The
javax.servlet.http package contains interfaces and classes that are responsible for http requests
only. All servlets must implement the javax.servlet.Servlet interface, which defines servlet
lifecycle methods. When implementing a generic service, we can extend the GenericServlet class
provided with the Java Servlet API. The HttpServlet class provides methods, such as doGet() and
doPost(), for handling HTTP-specificservices.

The servlet life-cycle includes three major functions of a Servlet interface :


1. Initializing a Servlet ( Servlet.init(ServletConfig) ) : init() method is used to initialize a
servlet object. ServletConfig object allows to access name-value configured initialization
parameters & containerdetails.
2. Handling a request ( Servlet.service(ServletRequest, ServletResponse) ) : This stage is
heart of servlet lifecycle, actual request processing is carried out here. ServletRequest
object allows to access client‟s request. ServletResponse object assist servlet to send
response to client. The actual program is handled in thissection.
3. Destroying a Servlet ( Servlet.destroy() ) : It is used to release to all servlet instances and
resources. It allows all thread to complete their work and releaseitself.

The major interfaces of Servletare:


ServletRequest Interface: It is used to encapsulate client request. It provide important
information about client toServlet.
ServletResponse Interface: It is used to encapsulate client‟s response. It always listens to a
Servlet object.
ServletConfig Interface: It allows a servlet container to pass information to a servlet. It is used to
initialize a parameter.
ServletContext Interface: ServletContext defines a set of method that a servlet use to
communicate with Servlet Container. It allows parameter to be accessed by all servlets in an
application.
References:
[1] Java-2, The Complete Reference, by HerbertSchildt
[2] https://www.journaldev.com/1877/servlet-tutorial-java
Aim : Write a Servlet program to print system date and time.

Code:

import java.io.*;
import javax.servlet.*;

public class DateSrv extends GenericServlet


{
public void service(ServletRequest req, ServletResponse res) throws IOException, ServletException
{
//set response content type

res.setContentType("text/html");
//get stream obj
PrintWriter pw = res.getWriter();
//write req processing logic
java.util.Date date = new java.util.Date();

pw.println("<h2>"+"Current Date & Time: " +date.toString()+"</h2>");


//close stream object
pw.close();
}
}
Output:

CURRENT DATE & TIME: SUNDAY APRIL 25, 2021 13:16:46

Conclusion:
In this practical, current system date and time is displayed using servlet
PRACTICAL SET – 7

Web.xml : The most important file of a Servlet application is web.xml file. The web.xml file is the
standard deployment descriptor for the Web application that the Web service is a part of. It declares
the filters and servlets used by the service. The general format of the web.xml is as given below.
It includes the servlet which are part of your application and its mapping to the appropriate url-
pattern, through which it can be accessed. All the Servlet used in application are mentioned in the
web.xmlfile.
<web-app …>
<?xml version="1.0" encoding="UTF-8"?>
<servlet>
<servlet-name>Demo1</servlet-name>
<servlet-class>Demo1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Demo1</servlet-name>
<url-pattern>Demo1</servlet-class>
</servlet-mapping>
</web-app>

Apart from the Servlets, filters, listeners, configuration/initialization parameters, error pages,
welcome files, security and session management concepts can be included in web.xml file. The
initialization parameters can be included either for a specific servlet or for all the servlet in a
application, with help of init-param and context-param tags respectively. They can be accessed
with help of methods of ServletConfig and ServletContext interface, alongwith
getinitparameter(name) method. To add a initialization parameter to a particular servlet, it can
written as below, within the servlet tag:

<servlet>….

<init-param>
<param-name> semester </param-name>
<param-value> 6 </param-value>
</init-param>
</servlet>

RequestDispatcher : Defines an object that receives requests from the client and sends them to
any resource (such as a servlet, HTML file, or JSP file) on the server. The servlet container creates
the RequestDispatcher object, which is used as a wrapper around a server resource located at a
particular path or given by a particular name. This interface is intended to wrap servlets, but a
servlet container can create RequestDispatcher objects to wrap any type of resource. The
RequestDispatcher interface provides two important methods. Theyare:
1. public void forward(ServletRequest request, ServletResponse response) throws
ServletException, java.io.IOException: Forwards a request from a servlet to another
resource (servlet, JSP file, or HTML file) on theserver.

2. public void include(ServletRequest request, ServletResponse response) throws


ServletException,java.io.IOException: Includes the content of a resource (servlet, JSP
page, or HTML file) in theresponse.

References:
[1] Java-2, The Complete Reference, by HerbertSchildt
[2] https://docs.oracle.com/
Aim : Write a Servlet to create a Login form with help of request dispatcher. If the login fails, it
should redirect back to loginpage, else to the next page.

Code:

index.html

<form action="loginPage" method="post">


User Name:<input type="text" name="uname"/><br/>

Password:<input type="password" name="upass"/><br/>


<input type="submit" value="SUBMIT"/>
</form>

Validation.java

import java.io.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Validation extends HttpServlet


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

{
response.setContentType("text/html");
PrintWriter pwriter = response.getWriter();
String name=request.getParameter("uname");
String pass=request.getParameter("upass");
if(name.equals("Chaitanya") &&
pass.equals("beginnersbook"))

{
RequestDispatcher dis=request.getRequestDispatcher("welcome");
dis.forward(request, response);
}
else

{
pwriter.print("User name or password is incorrect!");
RequestDispatcher dis=request.getRequestDispatcher("index.html");
dis.include(request, response);
}

}
}

WelcomeUser.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class WelcomeUser extends HttpServlet {

public void doPost(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException
{

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

String name=request.getParameter("uname");
pwriter.print("Hello "+name+"!");
pwriter.print(" Welcome to Beginnersbook.com");
}

web.xml

<web-app>

<display-name>BeginnersBookDemo</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>

<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>Validation</servlet-class>
</servlet>
<servlet>

<servlet-name>Welcome</servlet-name>
<servlet-class>WelcomeUser</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>

<url-pattern>/loginPage</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Welcome</servlet-name>

<url-pattern>/welcome</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>

</web-app>
Output:

Entering wrong credentials:

Error screen:
Conclusion: we learned how to set the condition for checking a particular string and redirect the page if the string
match and show some pages on the browser using servlet.
PRACTICAL SET – 8

JavaServer Faces (JSF) is a MVC web framework that simplifies the construction of User Interfaces (UI) for server-
based applications using reusable UI components in a page. JSF provides a facility to connect UI widgets with data
sources and to server-side event handlers. The JSF specification defines a set of standard UI components and
provides an Application Programming Interface (API) for developing components. JSF enables the reuse and
extension of the existing standard UI components.

MVC Design Pattern


⚫ Model - Carries Data and login
⚫ View - Shows User Interface
⚫ Controller - Handles processing of an application
⚫ The purpose of MVC design pattern is to separate model and presentation enabling developers to focus on
their core skills and collaborate more clearly.
⚫ Web designers have to concentrate only on view layer rather than model and controller layer. Developers can
change the code for model and typically need not change view layer. Controllers are used to process user
actions. In this process, layer model and views may be changed.

Object Class Scope

Out javax.servlet.jsp.JspWriter Page

Request javax.servlet.ServletRequest Request

Response javax.servlet.ServletResponse Page

Session javax.servlet.http.HttpSession Session

Application javax.servlet.ServletContext Application

exception java.lang.Throwable Page

Config javax.servlet.ServletConfig Page


Page java.lang.Object Page

PageContext javax.servlet.jsp.PageContext Page

JSF application life cycle consists of 6 phases which are as follows

Phase 1: Restore view


⚫ JSF begins the restore view phase as soon as a link or a button is clicked and JSF receives a request.
⚫ During this phase, JSF builds the view, wires event handlers and validators to UI components and saves the
view in the FacesContext instance. The FacesContext instance will now contain all the information required
to process a request.

Phase 2: Apply request values


⚫ After the component tree is created/restored, each component in the component tree uses the decode method
to extract its new value from the request parameters. Component stores this value. If the conversion fails, an
error message is generated and queued on FacesContext. This message will be displayed during the render
response phase, along with any validation errors.
⚫ If any decode methods event listeners called renderResponse on the current FacesContext instance, the JSF
moves to the render response phase.

Phase 3: Process validation


⚫ During this phase, JSF processes all validators registered on the component tree. It examines the component
attribute rules for the validation and compares these rules to the local value stored for the component.
⚫ If the local value is invalid, JSF adds an error message to the FacesContext instance, and the life cycle
advances to the render response phase and displays the same page again with the error message.

Phase 4: Update model values


⚫ After the JSF checks that the data is valid, it walks over the component tree and sets the corresponding server-
side object properties to the components' local values. JSF will update the bean properties corresponding to
the input component's value attribute.
⚫ If any updateModels methods called renderResponse on the current FacesContext instance, JSF moves to the
render response phase.

Phase 5: Invoke application


⚫ During this phase, JSF handles any application-level events, such as submitting a form/linking to another
page.

Phase 6: Render response


⚫ During this phase, JSF asks container/application server to render the page if the application is using JSP
pages. For initial request, the components represented on the page will be added to the component tree as JSP
container executes the page. If this is not an initial request, the component tree is already built so components
need not be added again. In either case, the components will render themselves as the JSP
container/Application server traverses the tags in the page.
⚫ After the content of the view is rendered, the response state is saved so that subsequent requests can access it
and it is available to the restore view phase.
References:
[1] Java-2, The Complete Reference, by HerbertSchildt
[2] https://www.oracle.com/java/technologies/javaserverfaces.html
Aim :Design a web page that takes the Username from user and if it is a valid username prints “Welcome
Username”. Use JSF to implement.

Code:

index.html
<!DOCTYPE html>
<html>

<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<form action="loginPage" method="Post">


User Name:<input type="text" name="uname"/><br/><br>
Password:<input type="password" name="upass"/><br/><br>
<input type="submit" value="SUBMIT"/>
</form>

</body>
</html>

Login.java

import java.io.IOException;
import java.io.PrintWriter;
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;
@WebServlet("/loginPage")
public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;
public Login() {

super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
//response.getWriter().append("Served at: ").append(request.getContextPath());

}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
doGet(request, response);
response.setContentType("text/html");

PrintWriter pwriter = response.getWriter();


String name=request.getParameter("uname");
String pass=request.getParameter("upass");
if(name.equals("Admin") &&
pass.equals("root"))

{
RequestDispatcher dis=request.getRequestDispatcher("welcome");
dis.forward(request, response);
}
else

{
pwriter.print("Username or password is incorrect!");
RequestDispatcher dis=request.getRequestDispatcher("index.html");
dis.include(request, response);

}
}
}

Welcome.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("/welcome")
public class Welcome extends HttpServlet {

private static final long serialVersionUID = 1L;


public Welcome() {
super();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws

ServletException, IOException {
doGet(request, response);
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
String name=request.getParameter("uname");

pw.print("Hello "+name+"!<br>");
pw.print(" Welcome to this site!");
}
}

Web.xml
<web-app>
<welcome-file-list>

<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>Login</servlet-class>

</servlet>
<servlet>
<servlet-name>Welcome</servlet-name>
<servlet-class>Welcome</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/loginPage</url-pattern>
</servlet-mapping>
<servlet-mapping>

<servlet-name>Welcome</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>

</welcome-file-list>
</web-app>
Output:
Conclusion: In this practical, login form with its functionalities is created in Servlet.
PRACTICAL SET – 9

It was started in 2001 by Gavin King as an alternative to EJB2 style entity bean. Hibernate is a
pure Java object-relational mapping (ORM) and persistence framework that allows you to map
plain old Java objects to relational database tables. The main goal of hibernate is to relieve the
developer from the common data persistence related tasks. It maps the objects in the java with the
tables in the database very efficiently and also you can get maximum using its data query and
retrieval facilities. Mainly by using Hibernate in your projects you can save incredible time and
effort. Hibernate framework simplifies the development of java application to interact with the
database. Hibernate is an open source, lightweight, ORM (Object Relational Mapping)tool.
Advantages of Hibernate
Opensource and Lightweight: Hibernate framework is
opensource under the LGPL license and lightweight.
Fast performance: The performance of hibernate
framework is fast because cache is internally used in
hibernate framework. There are two types of cache in
hibernate framework first level cache and second level
cache. First level cache is enabled by default.
Database Independent query: HQL (Hibernate Query
Language) is the object-oriented version of SQL. It
generates the database independent queries. So you don't
need to write database specific queries.
Automatic table creation: Hibernate framework provides
the facility to create the tables of the database
automatically. So there is no need to create tables in the
database manually. Directory Structure
Simplifies complex join: To fetch data from multiple tables is easy in hibernate framework.
References:
[1] https://www.javatpoint.com/jsp-implicit-objects
[2] Hibernate 2nd edition, Jeff Linwood and Dave Minter, Beginning Aprèspublication
Aim: Write Hibernate application to store customer records and retrieve the customer record including
name, contact number, address.

Code:

RegController.java File
package com.controller;
import java.io.IOException;
import java.util.List;

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 javax.servlet.http.HttpSession;
import com.dao.RegDAO;
import com.vo.RegVO;
/**
* Servlet implementation class RegController

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

* @see HttpServlet#HttpServlet()
*/
public RegController() {
super();
// TODO Auto-generated constructor stub
}

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {

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


if(flag.equals("Search"))
{
Search(request,response);
}

if(flag.equals("Delete"))
{
Delete(request,response);
Search(request,response);
}

if(flag.equals("Edit"))
{
Edit(request,response);
}
if(flag.equals("Update"))

{
Update(request,response);
Search(request,response);
}
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws

ServletException, IOException {
String flag = request.getParameter("flag");
if(flag.equals("Insert")){
Insert(request,response);
response.sendRedirect("form.jsp");

}
}
protected void Insert(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
String fn = request.getParameter("fn");

String ln = request.getParameter("ln");
String cn = request.getParameter("cn");
String add = request.getParameter("add");
RegVO regVO = new RegVO();
regVO.setFn(fn);

regVO.setLn(ln);
regVO.setCn(cn);
regVO.setAdd(add);
RegDAO regDAO = new RegDAO();
regDAO.Insert(regVO);

}
protected void Search(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
RegDAO regDAO = new RegDAO();
List searchList = regDAO.Search();

HttpSession session = request.getSession();


session.setAttribute("data", searchList);
response.sendRedirect("search.jsp");
}

protected void Delete(HttpServletRequest request, HttpServletResponse response) throws ServletException,


IOException {
int id = Integer.parseInt(request.getParameter("x"));
RegVO regVO1=new RegVO();
regVO1.setId(id);

RegDAO regDAO=new RegDAO();


regDAO.Delete(regVO1);
}
protected void Edit(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {

int id1 = Integer.parseInt(request.getParameter("y"));


RegVO regVO2 = new RegVO();
regVO2.setId(id1);
RegDAO regDAO = new RegDAO();
List ls1 = regDAO.Edit(regVO2);

HttpSession session = request.getSession();


session.setAttribute("data1", ls1);
response.sendRedirect("edit.jsp");
}
protected void Update(HttpServletRequest request, HttpServletResponse response) throws

ServletException, IOException {
int idu = Integer.parseInt(request.getParameter("idupdate"));
String fn1 = request.getParameter("fn");
String ln1 = request.getParameter("ln");
String cn1 = request.getParameter("cn");

String add1 = request.getParameter("add");


RegVO regVO3 = new RegVO();
regVO3.setId(idu);
regVO3.setFn(fn1);

regVO3.setLn(ln1);
regVO3.setCn(cn1);
regVO3.setAdd(add1);
RegDAO regDAO = new RegDAO();
regDAO.Update(regVO3);

}
}
RegDAO.java File
package com.dao;
import java.util.ArrayList;

import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import com.vo.RegVO;
public class RegDAO {
public void Insert(RegVO regVO) {

SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();


Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
session.save(regVO);
transaction.commit();

session.close();
}
public List Search() {
SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();

Session session = sessionFactory.openSession();


Transaction transaction = session.beginTransaction();
Query q = session.createQuery("from RegVO");
List searchList = q.list();
transaction.commit();

session.close();
return searchList;
}
public void Delete(RegVO regVO1)
{

try
{
SessionFactory sessionFactory = new
AnnotationConfiguration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();

Transaction transaction=session.beginTransaction();
session.delete(regVO1);
transaction.commit();
session.close();
}

catch(Exception ex)
{
ex.printStackTrace();
}
}

public List Edit(RegVO regVO2)


{
List ls1 = new ArrayList();
try

{
SessionFactory sessionFactory = new
AnnotationConfiguration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction=session.beginTransaction();

Query q = session.createQuery("From RegVO where id='"+regVO2.getId()+"'");


ls1 = q.list();
((RegDAO) session).Edit(regVO2);
transaction.commit();
session.close();

}
catch(Exception ex)
{
ex.printStackTrace();
}

return ls1;
}
public void Update(RegVO regVO3) {
try
{

SessionFactory sessionFactory = new


AnnotationConfiguration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction=session.beginTransaction();
session.update(regVO3);

transaction.commit();
session.close();
}
catch(Exception ex)

{
ex.printStackTrace();
}
}
}

RegVO.java File
package com.vo;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="hibernate_tbl")

public class RegVO {


@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="id")
private int id;

@Column(name="FirstName")
private String fn;
@Column(name="LastName")
private String ln;
@Column(name="Contact_Number")

private String cn;


@Column(name="Address")
private String add;
public int getId() {

return id;
}
public void setId(int id) {
this.id = id;
}

public String getFn() {


return fn;
}
public void setFn(String fn) {
this.fn = fn;

}
public String getLn() {
return ln;
}
public void setLn(String ln) {

this.ln = ln;
}
public String getCn() {
return cn;
}

public void setCn(String cn) {


this.cn = cn;
}
public String getAdd() {
return add;

}
public void setAdd(String add) {
this.add = add;
}

hibernate.cfg.xml File
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-configuration PUBLIC


"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>

<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/manual</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.pool_size">10</property>

<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping class="com.vo.RegVO"/>
</session-factory>

</hibernate-configuration>
form.jsp File
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>

<body>
<form action="RegController" method="post">
<table border="1px solid black">
<tr>
<td>First_Name: </td>

<td><input type="text" name="fn"></td>


</tr>
<tr>
<td>Last_Name: </td>
<td><input type="text" name="ln"></td>

</tr>
<tr>
<td>Contact_Number: </td>
<td><input type="text" name="cn"></td>
</tr>

<tr>
<td>Address: </td>
<td><input type="text" name="add"></td>
<td><input type="hidden" name="flag" value="Insert"></td>
</tr>

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

<a href="RegController?flag=Search">Search</a>
</body>
</html>
edit.jsp File

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<%@taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>

<body>
<form action="RegController" method="get">
<table border="1px solid black">
<c:forEach var="i" items = "${sessionScope.data1}">
<input type=hidden name=idupdate value="${i.id}">

<tr>
<td>First_Name: </td>
<td><input type="text" name="fn" value="${i.fn}"></td>
</tr>
<tr>

<td>Last_Name: </td>
<td><input type="text" name="ln" value="${i.ln}"></td>
</tr>
<tr>
<td>Contact_Number: </td>

<td><input type="text" name="cn" value="${i.cn}"></td>


</tr>
<tr>
<td>Address: </td>

<td><input type="text" name="add" value="${i.add}"></td>


<td><input type="hidden" name="flag" value="Update"></td>
</tr>
<tr>
<td><input type="submit" value="Update"></td>

</tr>
</c:forEach>
</table>
</form>
</body>

</html>
search.jsp File
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>

</head>
<%@taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<body>
<table border="1px solid black">
<tr>

<th>Number</th>
<th>First Name</th>
<th>Last Name</th>
<th>Contact Number</th>

<th>Address</th>
<th>Action</th>
</tr>
<c:forEach items="${sessionScope.data}" var="i" varStatus="j">
<tr>

<td>${j.count}</td>
<td>${i.fn}</td>
<td>${i.ln}</td>
<td>${i.cn}</td>
<td>${i.add}</td>

<td><a href="RegController?flag=Delete&x=${i.id}">Delete</td>
<td><a href="RegController?flag=Edit&y=${i.id}">Edit</a></td>
</tr>
</c:forEach>
</table>

</body>
</html>
Output:

Conclusion: In this practical, customers records is stored and retrieved using hibernate application.
PRACTICAL SET – 10
It was developed by Rod Johnson in 2003. Spring framework makes the easy development of
JavaEE application. It is helpful for beginners and experienced persons. Spring is a
lightweight framework. It can be thought of as a framework of frameworks because it provides
support to various frameworks such as Struts, Hibernate, EJB, JSF etc. The framework, in broader
sense, can be defined as a structure where we find solution of the various technical problems.
Spring is lightweight when it comes to size and transparency. Spring framework targets to make
J2EE development easier to use and promote good programming practice by enabling a POJO-
based programmingmodel.

Advantages of Spring

⚫ Predefined Templates, Loose Coupling, Easy to test,


Lightweight, Fast Development, Powerful
abstraction, Declarativesupport.

Directory Structure
Spring Framework

References:
[1] https://www.javatpoint.com/jsp-implicit-objects
[2] Spring in Action 3rd edition , Craig walls, ManningPublication
Aim: Write an application to keep record and retrieve record of student. The record includes student id,
enrollment number, semester, SPI. Use MVC architecture.

Code:

Index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>

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

<a href="load.html">INSERT</a>
<br />
<a href="search.html">SEARCH</a>
<br />
</body>

</html>

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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"

xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com"/><!-- base package name which contains con,dao,vo packages -->

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" /><!--exclude index page all other jsp pages are
include in WEB-INF folder-->
<property name="suffix" value=".jsp" /><!--extension of those pages-->
</bean>

<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">


<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost/prac10"/>
<property name="username" value="root"/>
<property name="password" value="root"/>

</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="annotatedClasses">
<list>

<value>com.model.RegVO</value><!--vo file destination-->


</list>
</property>
<property name="hibernateProperties">
<props>

<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>

</property>
</bean>
</beans>
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_2_5.xsd"
version="2.5">

<servlet>
<servlet-name>spring</servlet-name><!--servlet name should be same as per file name-->
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>

<servlet-name>spring</servlet-name><!--servlet name should be same as above-->


<url-pattern>*.html</url-pattern><!--we can add mutliple url pattern-->
</servlet-mapping>
</web-app>

Registration.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<title>REGISTRATION PAGE</title>
</head>
<%@taglib prefix="f" uri="http://www.springframework.org/tags/form"%>
<body>
<f:form action="insert.html" post="Post" modelAttribute="RegVO">

<table border="1px solid black">


<tr>
<td>STUDENT_ID:</td>
<td><f:input path="studentID" /></td>
</tr>

<tr>
<td>ENROLLMENT_NUMBER:</td>
<td> <f:input path="enrollment" /></td>
</tr>
<tr>

<td>SEMESTER:</td>
<td><f:input path="semester" /></td>
</tr>
<tr>
<td>SPI:</td>

<td> <f:input path="SPI" /></td>


</tr>
<tr>
<td> <f:hidden path="id" /></td>
</tr>

<tr>
<td> <input type="submit" value="Submit"></td>
</tr>
</table>

</f:form>
</body>
</html>
Search.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">


<title>Insert title here</title>
</head>
<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %>
<body>

<table border="1px solid black">


<tr>
<th>Id</th>
<th>STUDENT_ID</th>
<th>ENROLLMENT_NUMBER</th>

<th>SEMESTER</th>
<th>SPI</th>
<th>ACTION</th>
</tr>
<c:forEach items="${SearchList}" var="p">

<tr>
<td>${p.id}</td>
<td>${p.studentID}</td>
<td>${p.enrollment}</td>

<td>${p.semester}</td>
<td>${p.SPI}</td>
<td colspan="2"><a href="delete.html?id=${p.id}">Delete</a>&nbsp;&nbsp;<a
href="edit.html?id=${p.id}">Edit</a></td>
</tr>

</c:forEach>
</table>
</body>
</html>

RegController.java
package com.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.dao.RegDAO;
import com.model.RegVO;
@Controller

public class RegController {


@Autowired
RegDAO regDAO;
@RequestMapping(value = "load.html", method = RequestMethod.GET)

public ModelAndView Load() {


return new ModelAndView("Registration", "RegVO", new RegVO());
}
@RequestMapping(value = "insert.html", method = RequestMethod.POST)
public ModelAndView Insert(@ModelAttribute RegVO regVo) {

regDAO.insert(regVo);
return new ModelAndView("redirect:/search.html");
}
@RequestMapping(value = "search.html", method = RequestMethod.GET)
public ModelAndView Search() {

List searchList = regDAO.search();


return new ModelAndView("Search", "SearchList", searchList);
}
@RequestMapping(value = "delete.html", method = RequestMethod.GET)
public ModelAndView Delete(HttpServletRequest request, @ModelAttribute RegVO regVO,

@RequestParam int id) {


regVO.setId(id);
regDAO.delete(regVO);
return new ModelAndView("redirect:/search.html");
}

@RequestMapping(value = "edit.html", method = RequestMethod.GET)


public ModelAndView Edit(HttpServletRequest request, @ModelAttribute RegVO regVO,
@RequestParam int id) {
regVO.setId(id);
List editList = regDAO.edit(regVO);

return new ModelAndView("Registration", "RegVO", editList.get(0));


}
}

RegDAO.java
package com.dao;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;

import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.model.RegVO;

@Repository
public class RegDAO {
@Autowired
SessionFactory sessionFactory;
public void insert(RegVO regVO) {

try {
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
session.saveOrUpdate(regVO);
transaction.commit();

session.close();
} catch (Exception e) {
e.printStackTrace();
}
}

public List search() {


Session session = sessionFactory.openSession();
Query q = session.createQuery("from RegVO");
List ls = q.list();

session.close();
return ls;
}
public void delete(RegVO regVO) {
Session session = sessionFactory.openSession();

Transaction transaction = session.beginTransaction();


session.delete(regVO);
transaction.commit();
session.close();
}

public List edit(RegVO regVO) {


Session session = sessionFactory.openSession();
Query q = session.createQuery("from RegVO where id=" + regVO.getId());
List ls = q.list();
session.close();

return ls;
}
}

RegVO.java

package com.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;

import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="Spring")

public class RegVO


{
@Id
@Column(name="Id")
@GeneratedValue(strategy=GenerationType.AUTO)

private int id;


@Column(name="StudentID")
private String studentID;
@Column(name="Enrollment")
private String enrollment;

@Column(name="Semester")
private String semester;
@Column(name="SPI")
private String spi;
public int getId() {

return id;
}
public void setId(int id) {
this.id = id;
}

public String getStudentID() {


return studentID;
}
public void setStudentID(String studentID) {
this.studentID = studentID;

}
public String getEnrollment() {
return enrollment;
}

public void setEnrollment(String enrollment) {


this.enrollment = enrollment;
}
public String getSemester() {
return semester;

}
public void setSemester(String semester) {
this.semester = semester;
}
public String getSPI() {

return spi;
}
public void setSPI(String spi) {
this.spi = spi;
}

}
Output:
Conclusion: From this practical we learned about spring mvc framework and its implementation with CRUD
operation

You might also like