Aiyyan EJ Final
Aiyyan EJ Final
Aiyyan EJ Final
- 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
CERTIFICATE
COLLEGE SEAL
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
INDEX
OUTPUT: -
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
DATE – 28/06/23
1.b) Create a servlet for login page.If username and password are correct then it say
message”HELLO <Username>” Else a message “Login Failed”.
Login.html
<html><body>
<form method="get" action="HelloServlet">
USERNAME : <input type="text" name="username"> <br>
PASSWORD : <input type="password" name="password"> <br>
<input type="submit" value="ENTER">
</form></body></html>
HelloServlet.java
package p1;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloServlet extends HttpServlet {
OUTPUT: -
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
DATE – 28/06/23
1.c)Create a Registration servlet in Java Using JDBC.accept the details such as user name,
password, email and country from the user using HTML form and store the registration details
in the database.
Mysql Queries
OUTPUT: -
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
PRACTICAL - 02
DATE – 03/07/23
AIM: Implement the following Servlet applications with Cookies and Sessions.
2.a) Using Request Dispatcher Interface create a Servlet which will validate the password entered
by the user, if the user has entered "Servlet" as password, then he will be forwarded to Welcome
Servlet else the user will stay on the index.html page and an error message will be displayed.
Index.html
<html>
<body>
<form method="get" action="RequestDispatcherServlet">
USERNAME :<input type="text" name="userName"><br>
PASSWORD :<input type="password" name="password"><br>
<input type="submit" value="ENTER">
</form></body></html>
RequestDispatcherServlet.java
package p1;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n); } }
OUTPUT: -
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
DATE – 03/07/23
2.b) Create a servlet that uses cookies to store the number of times a user has visited servlet.
DemoCookieServlet.java
package p1;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DemoCookieServlet extends HttpServlet
{
static int i=1;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String k=String.valueOf(i);
Cookie c = new Cookie("visit",k);
response.addCookie(c);
int j=Integer.parseInt(c.getValue());
if(j==1)
{
out.println("Welcome");
}
else
{
out.println("You visited "+i+" times");
}
i++;
}
}
OUTPUT: -
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
DATE – 03/07/23
2.c) Create a servlet demonstrating the use of session creation and destruction. Also check
whether the user has visited this page the first time or has earlier also using sessions.
Index.html
<html> <head><title>Servlet Login Example</title>
</head><body>
<h1>Login App using HttpSession</h1>
<a href="Login.html">Login</a>
<a href="LogoutServlet">Logout</a>
<a href="ProfileServlet">Profile</a>
</body></html>
Login.html
<html><head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head><body>
<form action="LoginServlet" method="post">
Name : <input type="text" name="name"><br>
Password: <input type="password" name="password"><br>
<input type="submit" value="login">
</form>
</body></html>
LoginServlet.java
package p1;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class LoginServlet extends HttpServlet
{
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
request.getRequestDispatcher("index.html").include(request, response);
String name=request.getParameter("name");
String password=request.getParameter("password");
if(password.equals("ZAYA304")){
out.print("Welcome, "+name);
HttpSession session=request.getSession();
session.setAttribute("name",name);
}
else{
out.print("Sorry, username or password error!");
request.getRequestDispatcher("Login.html").include(request, response);
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
}
out.close();
} }
LogoutServlet.java
package p1;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
OUTPUT: -
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
PRACTICAL – 03
DATE –
AIM: Implement the Servlet IO and File applications.
3.a)Create a servlet application for to upload and download a file.
SOFTWARE USED: NETBEANS 18 IDE
Upload.html
<html>
<body>
<form action="FileUploadServlet" method="post" enctype="multipart/form-data">
Select File:<input type="file" name="fname"/><br/>
<input type="submit" value="upload"/>
</form> </body> </html>
FileUploadServlet.java
package p1;
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class FileUploadServlet extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("successfully uploaded");
}
}
OUTPUT: -
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
Class MultipartRequest:
A utility class to handle multipart/form-data requests, the kind of requests that support file uploads.
This class emulates the interface of HttpServletRequest, making it familiar to use. It uses a "push"
model where any incoming files are read and saved directly to disk in the constructor.
PROCESS OF FILE UPLOAD:
1. File upload works by a mechanism where the client-side file is opened by the client application
(browser) and its data is MIME-encoded and copied into the request data stream that is sent to
the server.
2. Once the server receives that request, the file data is parsed out of it, but that doesn't make it a
"file". The server can hold the data anywhere it wants to, including in memory.
3. The file upload API allows you to take that data and - using your own code - process it.
4. Relative paths are dangerous in web applications, because a relative path is relative to the
current working directory and there is no such thing in J2EE.
5. An absolute path should ALWAYS start with a "/".
Download.html
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div>TODO write content</div>
<a href="FileDownloadServlet">DOWNLOAD THE FILE</a>
</body>
</html>
FileDownloadServlet.java
package p1;
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
OUTPUT: -
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
DATE –
3.b) Develop Simple Servlet Question Answer Application using Database.
Quiz.html
<html> <head><title>QUIZ</title></head>
<body>
<h1>QUIZ</h1>
<form method = "get" action = "QuizServlet">
<label>What is the full form of JSP?</label><br/>
<input type = "radio" name="q1" value="a">Java Server Pages<br/>
<input type = "radio" name="q1" value="b">Java Server Page<br/>
<input type = "radio" name="q1" value="c">Java Servlet Pages<br/>
<input type = "radio" name="q1" value="d">Java Sun Pages<br/>
<br><br/>
<label>Life Cycle methods of JSP is/are?</label><br/>
<input type = "radio" name="q2" value="a">jspinit()<br/>
<input type = "radio" name="q2" value="b">_jspService()<br/>
<input type = "radio" name="q2" value="c">jspDestroy<br/>
<input type = "radio" name="q2" value="d">All of the above<br/>
<br><br/>
<label>What JSTL stands for?</label><br/>
<input type = "radio" name="q3" value="a">JavaServer Pages Standard Tag Library<br/>
<input type = "radio" name="q3" value="b">JSP Tag Library<br/>
<input type = "radio" name="q3" value="c">Java Standard Tag Library<br/>
<input type = "radio" name="q3" value="d">None of the above<br/>
<br><br/>
<input type="submit" value="SUBMIT"/>
</form>
</body>
</html>
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
QuizServlet.java
package p1;
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.sql.*;
import java.util.*;
public class QuizServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{ response.setContentType("text/html");
PrintWriter out = response.getWriter();
String paramName, paramValue [];
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
int cnt =0;
String ans = "";
Enumeration paramNames = request.getParameterNames();
try
{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/TYIT","root","hello");
out.println("connection done successfully...");
stmt = con.createStatement();
rs = stmt.executeQuery("select ans from info");
while (rs.next()&& paramNames.hasMoreElements())
{
String un = rs.getString(1);
paramName = (String)paramNames.nextElement();
paramValue = request.getParameterValues(paramName);
for(int i=0;i<paramValue.length;i++)
ans=paramValue[i];
if(un.equals(ans))
cnt++;
}
out.println("<h1>YOU HAVE SCORED " + cnt + " POINTS OUT OF 3.</h1>");
}
catch(Exception e)
{
out.println("SORRY!! TRY AGAIN");
}
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
}
}
OUTPUT: -
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
DATE –
3.c) Create simple Servlet application to demonstrate Non-Blocking Read Operation.
Upload.html
<html><body>
<form action="NonBlockingFileUploadServlet" method="post" enctype="multipart/form-data">
Select File:<input type="file" name="fname"/><br/>
<input type="submit" value="upload"/>
</form></body></html>
NonBlockingFileUploadServlet.java
package p1;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class NonBlockingFileUploadServlet extends HttpServlet
{
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html;charset-UTF-8");
final AsyncContext content = request.startAsync();
final ServletInputStream sis = request.getInputStream();
System.out.println(getServletContext().getRealPath("/")+"TYIT syllabus (1)");
final File filetoupload = new File(getServletContext().getRealPath("/")+"TYIT syllabus (1)");
final FileOutputStream fos = new FileOutputStream(filetoupload);
sis.setReadListener(new ReadListener(){
byte [] buffer = new byte[1024*4];
@Override
public void onDataAvailable() throws IOException
{
do{
int length = sis.read(buffer) ;
System.out.println("DATA READ-------"+ length);
fos.write(buffer,0,length);
}while(sis.isReady()); }
@Override
public void onAllDataRead() throws IOException
{
content.complete();
fos.close();
System.out.println("UPLOAD COMPLETED-----");
}
@Override
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
public void onError(Throwable t)
{
System.out.println("onError()"+t.getMessage());
}
});
}
}
Web.xml
<servlet>
<servlet-name>NonBlockingFileUploadServlet</servlet-name>
<servlet-class>p1.NonBlockingFileUploadServlet</servlet-class>
<async-supported>true</async-supported>
</servlet>
OUTPUT: -
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
PRACTICAL – 04
DATE –
AIM: Implement the following JSP application
4.a) Develop a simple JSP application to display values obtained from the use of intrinsic objects
of various types.
IntrinsicObjects.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html><head><title>JSP Page</title></head>
<body>
<h1>Use of Intrinsic Objects in JSP</h1>
<h1>Request Object </h1>
Query String <%=request.getQueryString() %><br>
Context Path <%=request.getContextPath() %><br>
Remote Host <%=request.getRemoteHost() %><br>
<h1>Response Object </h1>
Character Encoding Type <%=response.getCharacterEncoding() %><br>
Content Type <%=response.getContentType() %><br>
Locale <%=response.getLocale() %><br>
<h1>Session Object </h1>
ID <%=session.getId() %><br>
Creation Time <%=new java.util.Date(session.getCreationTime()) %><br>
Last Access Time<%=new java.util.Date(session.getLastAccessedTime()) %><br>
</body>
</html>
OUTPUT: -
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
DATE: 21-08-2023
4.b) Develop a simple JSP application to pass values from one page to another with validations.
(Name-txt, age-txt, hobbies-checkbox, email-txt, gender-radio button.
ValidationJSP.jsp
<%@page language="java" contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head>
<title>JSP Page</title>
</head>
<body>
<%
String err="";
out.println("inside scriplet");
if(request.getParameter("send")!= null)
{
out.println("inside first if");
if(request.getParameter("fullname").equals(""))
{
out.println("NAME CANNOT BE BLANK----<br>");
}
if(request.getParameter("age").equals(""))
{
err += "AGE CANNOT BE BLANK----<br>";
}
if(request.getParameter("email").equals(""))
{
err += "EMAIL CANNOT BE BLANK----<br>";
}
if(request.getParameter("gender").equals(""))
{
err += "GENDER CANNOT BE BLANK----<br>";
}
if(request.getParameter("hb").equals(""))
{
err += "HOBBIES CANNOT BE BLANK----<br>";
}
}
if(err.length() >0)
{
out.print(err);
}
else
{
response.sendRedirect("Display.jsp?"+request.getQueryString());
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
//request.getRequestDispatcher("/Display.jsp"+request.getQueryString());
}
%>
</body>
</html>
DataApplication.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head><title>JSP Page</title></head>
<body>
<h1>REGISTRATION FORM</h1>
<form action="ValidationJSP.jsp" method="get">
<table style ="width:50%">
<tr>
<td>Full Name</td>
<td><input type="text" name="fullname" /></td>
</tr><tr>
<td>Age</td>
<td><input type="text" name="age" /></td>
</tr><tr>
<td>E-Mail</td>
<td><input type="text" name="email" sixe="20"/></td>
</tr><tr>
<tr><td>Gender</td>
<td><input type="radio" name="gender" value="Male">Male
<input type="radio" name="gender" value="Female">Female
</td></tr>
<tr><td>Hobbies</td>
<td>
<input type="checkbox" name="hb" value="Singing" />Singing
<input type="checkbox" name="hb" value="Drawing" />Drawing
<input type="checkbox" name="hb" value="Listening Music" />Listening Music
</td></tr>
</table>
<input type="submit" value="REGISTER" name="send" />
</form>
</body>
</html>
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
Display.jsp
<%--
Document : Display
Created on : 19 Aug, 2022, 6:58:40 PM
Author : aarya
--%>
<%@page contentType="text/html" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head><title>DISPLAY INFORMATION</title></head>
<body>
<%
out.print(request.getParameter("fullname")+"<br>");
out.print(request.getParameter("age")+"<br>");
out.print(request.getParameter("gender")+"<br>");
out.print(request.getParameter("email")+"<br>");
out.print(request.getParameter("hb")+"<br>");
%>
</body>
</html>
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<welcome-file-list>
<welcome-file>DataApplication.jsp</welcome-file>
</welcome-file-list>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
OUPUT:
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
DATE –
4.c) Create a registration and login JSP application to register and authenticate the user based on
username and password using JDBC.
Register.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html><head><title>JSP Page</title></head>
<body>
<form action="Login.jsp" >
Enter User Name <input type="text" name="txtName"><br>
Enter Password <input type="password" name="txtPass"><br>
<input type="submit" value="Submit"/>
</body>
</html>
Login.jsp
<%@page contentType="text/html" import="java.sql.*"%>
<html><body>
<h1>LOGIN PAGE</h1>
<%
String uname=request.getParameter("txtName");
String pass = request.getParameter("txtPass");
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/Zaya","root","hello");
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
PreparedStatement stmt = con.prepareStatement("select password from user where
username=?");
stmt.setString(1, uname);
ResultSet rs = stmt.executeQuery();
if(rs.next()){
if(pass.equals(rs.getString(1)))
{
out.println("<h1>~~~ LOGIN SUCCESSFULL ~~~ </h1>");
}
}
else
{
out.println("<h1>User Name not exist !!!!!</h1>");
%>
<jsp:include page="Register.jsp" ></jsp:include>
<%
}
}catch(Exception e){out.println(e);}
%>
</body></html>
OUTPUT: -
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
PRACTICAL – 05
DATE – 28/08/23
AIM: Implement the following JSP JSTL and EL Applications.
5.a) Create an html page with fields, eno, name, age, desg, salary. Now on submit this data to a
JSP page which will update the employee table of database with matching eno.
EmployeeDetails.html
<html>
<body>
<form action="UpdateEmp.jsp" >
Enter Employee Number: <input type="text" name="txtEno" ><br>
Enter Name: <input type="text" name="txtName" ><br>
Enter Age: <input type="text" name="txtAge" ><br>
Enter Designation: <input type="text" name="txtDesignation" ><br>
Enter Salary: <input type="text" name="txtSal" ><br>
<input type="reset" ><input type="submit">
</form>
</body>
</html>
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
UpdateEmp.jsp
<%@page contentType="text/html" import="java.sql.*" %>
<html><body>
<h1>Employee Record Update</h1>
<%
String eno=request.getParameter("txtEno");
String name=request.getParameter("txtName");
String age = request.getParameter("txtAge");
String designation = request.getParameter("txtDesignation");
String sal = request.getParameter("txtSal");
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/Zaya","root","HELLO");
PreparedStatement stmt = con.prepareStatement("select * from employee where eno=?");
stmt.setString(1, eno);
ResultSet rs = stmt.executeQuery();
if(rs.next())
{
out.println("<h1> Employee "+name+" Exist </h1>");
PreparedStatement pst1= con.prepareStatement("update employee set sal=? where eno=?");
PreparedStatement pst2= con.prepareStatement("update employee set age=? where eno=?");
pst1.setString(1, sal); pst1.setString(2, eno);
pst2.setString(1, age); pst2.setString(2, eno);
pst1.executeUpdate(); pst2.executeUpdate();
}
else
{
out.println("<h1>Employee Record not exist !!!!!</h1>");
}
}
catch(Exception e)
{
out.println(e);
}
%></body></html>
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
OUTPUT: -
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
DATE – 28/08/23
5b) Create a JSP page to demonstrate the use of Expression language.
ELDemo.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%
application.setAttribute("author","Zaya");
session.setAttribute("country", "India");
%>
<html>
<head><title>EXPRESSION LANGUAGE DEMO</title></head>
<body>
<form action ="show.jsp">
FIRST NAME :<input type="text" name="fname"/><br>
LAST NAME :<input type="text" name="lname"/><br>
<input type="submit" value="CHECK EL USE"/><br>
</body></html>
Show.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<% pageContext.setAttribute("color","pink");%>
<!DOCTYPE html>
<html><head><title>Display Page</title></head>
<body bgcolor="${pageScope.color}">
<b> Welcome!!!! ${param.fname} ${param.lname} </b>
Below we are accessing Application object:
<p>
Author Name: <b> ${applicationScope.author} </b>
</p>
Below we are accessing Session object:
<p>
Author Country: <b> ${sessionScope.country} </b>
</p>
Below we are showing some basic comparisons using EXPRESSION LANGUAGE:
<p>
Is 1 less than 2 ? $ {1<2} <br>
Does 5 equal 5 ? $ {5 == 5} <br>
Is 6 greater than 7 ? ${6 gt 7}<br>
</p>
Below we are showing some basic Arithmetic Operators using EXPRESSION LANGUAGE:
<p>
6 + 7 = ${6+7} <br>
8 * 9 = ${8*9} <br>
</p>
<hr> CURRENTLY THE BROWSER USED IS:
${header["user-agent"]}
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
</body>
</html>
OUTPUT: -
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
DATE – 28/08/23
5.c) Create a JSP application to demonstrate the use of JSTL.
DemoJSTL.jsp
<%--
Document : DemoJSTL
Created on : 28 Aug, 2023, 12:03:16 PM
Author : Western
--%>
jstlTest.jsp
<%--
Document : jstlTest
Created on : 28 Aug, 2023, 12:05:00 PM
Author : Western
--%>
OUTPUT: -
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
PRACTICAL – 06
DATE – 28/08/23
AIM: Implement the following EJB application
6.a) Create a Currency Converter application using EJB.
CurrencyConversion.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Currency Converter</title>
</head>
<body>
<h1>Currency Converter</h1>
<hr>
<p>Enter an amount to convert:</p>
<form method="post" action="ConvertCurrencyServlet">
<table style="width: 100%; padding: 0px; border-spacing: 0px; border: 0px;">
<tr>
<td> Convert: <br />
<input type="text" name="amount" value="1" size="10" tabindex="1" />
<div>Enter an amount</div>
</td>
</tr>
<tr>
<td> From this currency:<br />
<select name="From" size="3" tabindex="2">
<option value="USD">America (United States), Dollar (USD)</option>
<option value="INR">India, Rupee (INR)</option>
</select>
</td>
</tr>
<tr>
<td> To this currency:<br />
<select name="To" size="3" tabindex="3">
<option value="USD">America (United States), Dollar (USD)</option>
<option value="INR">India, Rupee (INR)</option>
</select>
</td>
</tr>
<tr>
<td>
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
<input name="cmdSubmit" type="submit" value="Submit" tabindex="4" />
</td>
</tr>
</table>
</form>
</body>
</html>
CurrencyConverterBean.java
package p1;
import java.math.BigDecimal;
import javax.ejb.Staateless;
@Stateless
public class CurrencyConverterBean {
final private BigDecimal USD = new BigDecimal("0.0229137");
final private BigDecimal INR = new BigDecimal("46.589100");
ConvertCurrencyServlet.java
package p1;
import p1.CurrencyConverterBean;
import java.io.*;
import java.math.BigDecimal;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
String amount = request.getParameter("amount");
if (amount != null && amount.length() > 0) {
BigDecimal d = new BigDecimal(amount);
BigDecimal convertedAmount = converterBean.convert(request.getParameter("From"),
request.getParameter("To"), d);
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Converted Currency</title>");
out.println("</head>");
out.println("<body>");
out.println(amount + " " + request.getParameter("From") + " = ");
out.println(convertedAmount + " " + request.getParameter("To"));
out.println("<br/>Click <a href='index.jsp'>here</a> to go back");
out.println("</body>");
out.println("</html>");
}
}
}
}
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
OUTPUT:
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
DATE: 04-09-2023
6.b) Develop a Simple Room Reservation System Application Using EJB.
RoomReservation.html
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="RoomReservation" method="get">
USERNAME :<input type="text" name="uname"><br>
SELECT DATE :<input type="date" name="rdate"><br>
SELECT ROOM :<select name="roomno">
<option value ="1">Room 1</option>
<option value ="2">Room 2</option>
<option value ="3">Room 3</option>
</select><br>
<input type="submit" value="BOOK">
</form>
</body>
</html>
RoomReservation.java
package p1;
import java.io.*;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.*;
import javax.servlet.http.*;
public class RoomReservation extends HttpServlet {
RmRegLocal rmReg = lookupRmRegLocal();
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = null;
try
{
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
out = response.getWriter();
String user = request.getParameter("uname");
String dt = request.getParameter("rdate");
String rn = request.getParameter("roomno");
String [] dtpart = dt.split("-"); //yy-mm-dd
Date date = new
Date(Integer.parseInt(dtpart[0]),Integer.parseInt(dtpart[1]),Integer.parseInt(dtpart[2]));
out.print(rmReg.addRoomReg(user, date,Integer.parseInt(rn)));
}
catch(Exception e)
{
e.printStackTrace();
}
}
private RmRegLocal lookupRmRegLocal() {
try {
Context c = new InitialContext();
return (RmRegLocal) c.lookup("java:global/Practica"
+ "l6/RmReg!p1.RmRegLocal");
} catch (NamingException ne) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
throw new RuntimeException(ne);
}
}
}
RmReg.java
package p1;
import java.util.*;
import javax.ejb.Stateful;
@Stateful
public class RmReg implements RmRegLocal
{
private Vector<Reg> regs = new Vector<Reg>();
@Override
public String addRoomReg(String uname, Date dt, int roomno)
{
for(Reg reg :regs)
{
if(reg.getRdate().equals(dt) && reg.getRoomno()==roomno)
{
return "ROOM NOT AVALIABLE FOR SELECTED DATE";
}
}
Reg r1 = new Reg(uname,dt,roomno);
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
regs.add(r1);
return "ROOM BOOKED FOR SELECTED DATE";
}
}
class Reg
{
private String uname;
private Date rdate;
private int roomno;
RmRegLocal.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package p1;
import java.util.Date;
/**
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
*
* @author western
*/
interface RmRegLocal {
public String addRoomReg(String uname, Date dt, int roomno);
}
OUTPUT:
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
DATE:
6.c) Develop simple shopping cart application using EJB [Stateful Session Bean].
shopping.html
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<a href="Cart?show=show">SHOW CART</a>
<table border>
<tr><th>PID</th><th>NAME</th><th>PRICE</th></tr>
<form action="Cart"><tr><td>1</td><td>FRIDGE</td><td>30000</td><td><input
type="hidden" name="pr" value="1:FRIDGE:30000"><input type="submit"
value="AddtoCart"></td></tr></form>
<form action="Cart"><tr><td>2</td><td>LAPTOP</td><td>65000</td><td><input
type="hidden" name="pr" value="2:LAPTOP:65000"><input type="submit"
value="AddtoCart"></td></tr></form>>
<form action="Cart"><tr><td>3</td><td>AC</td><td>20000</td><td><input type="hidden"
name="pr" value="3:AC:20000"><input type="submit" value="AddtoCart"></td></tr></form>>
<form action="Cart"><tr><td>4</td><td>SMART TV</td><td>30000</td><td><input
type="hidden" name="pr" value="4:SMART TV:30000"><input type="submit"
value="AddtoCart"></td></tr></form>>
</table>
</body>
</html>
cartBean.java
package p1;
import javax.ejb.Stateful;
import java.util.*;
@Stateful
public class cartBean implements cartBeanLocal {
public Vector<Product> cart = new Vector<Product>();
@Override
public String addToCart(String pid, String name, String price) {
for(Product product : cart)
{
if(product.getPid().equals(pid))
{
return "Product is already in cart";
}
}
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
Product pr = new Product(pid,name,price);
cart.add(pr);
return "Product added";
}
@Override
public String showCart() {
String allProductInCart = "";
for(Product product : cart)
{
allProductInCart += product.getPid()+":"+product.getName()+":"+product.getPrice()+";";
}
return allProductInCart;
}
}
class Product
{
String pid;
String name;
String price;
public Product(String pid, String name, String price) {
this.pid = pid;
this.name = name;
this.price = price;
}
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
Cart.java
package p1;
import java.io.IOException;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.*;
import javax.servlet.http.*;
public class Cart extends HttpServlet {
cartBeanLocal cartBean = lookupcartBeanLocal();
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter())
{
if(request.getParameter("pr")!= null)
{
//ADDING IN CART
String[] det = request.getParameter("pr").split(":");
out.print(cartBean.addToCart(det[0],det[1],det[2]));
}
else if (request.getParameter("show")!= null)
{
//DISPLAYING CART
String allrows = cartBean.showCart();
allrows = allrows.substring(0,allrows.length()-1);
//out.print(allrows);
String [] irow = allrows.split(";");
out.print("<table>");
for(int i =0;i<irow.length;i++)
{ out.print("<tr><td>"+irow[i].split(":")[0]+"</td><td>"+irow[i].split(":")[1]+"</
td><td>"+irow[i].split(":")[2]+"</td></tr>");
}
out.print("</table>");
}
}
}
private cartBeanLocal lookupcartBeanLocal() {
try {
Context c = new InitialContext();
return (cartBeanLocal) c.lookup("java:global/Pratical_6/cartBean!p1.cartBeanLocal");
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
} catch (NamingException ne) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
throw new RuntimeException(ne);
}
}
}
OUTPUT:
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
Practical 7
A] AIM : Develop simple EJB application to demonstrate Servlet Hit count using
Singleton Session Beans.
Program =
index.html
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>SERVLET CLIENT</title>
<meta charset="UTF-8">
<meta http-equiv="Refresh" content="0; URL=ServletClient">
</head>
<body>
<div>TODO write content</div>
</body>
</html>
CountServletHitsBean.java
package p1;
import javax.ejb.Singleton;
@Singleton
public class CountServletHitsBean {
private int hitCount;
ServletClient.java
package p1;
import p1.CountServletHitsBean;
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
import java.io.IOException;
import java.io.PrintWriter;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet ServletClient</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Number of times this servlet is accessed: " +
counterBean.incrementAndGetHitCount() + "</h1>");
out.println("</body>");
out.println("</html>");
}
}
}
OUTPUT =
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
B] AIM : Develop simple visitor Statistics application using Message Driven Bean
[Stateless Session Bean].
Database =
Program =
index.jsp
<%@page import="javax.jms.JMSException, javax.naming.InitialContext, javax.jms.TextMessage,
javax.jms.MessageProducer, javax.jms.Session, javax.jms.Connection, javax.jms.Queue,
javax.jms.ConnectionFactory" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%!
private static ConnectionFactory connectionFactory;
private static Queue queue;
Connection connection = null;
Session mysession = null;
MessageProducer messageProducer = null;
TextMessage message = null;
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Welcome To Prajwal Home Page</title>
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
</head>
<body style="background-color: pink;">
<h1>Welcome To Prajwal Adhav Home page</h1>
<%
try {
InitialContext ctx = new InitialContext();
queue = (Queue) ctx.lookup("jms/Queue");
connectionFactory = (ConnectionFactory) ctx.lookup("jms/QueueFactory");
connection = connectionFactory.createConnection();
mysession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
messageProducer = mysession.createProducer(queue);
message = mysession.createTextMessage();
message.setText(request.getRemoteAddr());
messageProducer.send(message);
} catch (JMSException e) {
System.out.println("Exception occurred: " + e.toString());
}
%>
</body>
</html>
VisitorStatBean.java
package p1;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.annotation.PostConstruct;
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
import javax.annotation.PreDestroy;
import javax.ejb.Stateless;
@Stateless
public class VisitorStatBean {
private Connection conn = null;
private ResultSet rs;
private Statement stmt = null;
private String query = null;
@PostConstruct
public void connect() {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/TYIT?
useTimeZone=true&serverTimezone=UTC&autoReconnect=true&useSSL=false","root","221001");
System.out.println("Database connection established successfully.");
} catch(ClassNotFoundException | InstantiationException | IllegalAccessException |
SQLException e) {
System.err.println("Sorry failed to connect to the Database.");
}
}
@PreDestroy
public void disconnect() {
try {
conn.close();
System.out.println("Database connection closed successfully.");
} catch(SQLException e) {
System.err.println("Cannot close the database connection: " + e.getMessage());
}
}
public void addVisitor(String host) {
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
try {
stmt = conn.createStatement();
query = "INSERT INTO UserStat (hostname, visits) VALUES('" + host + "','1')";
stmt.executeUpdate(query);
} catch(SQLException e) {
try {
stmt = conn.createStatement();
query = "UPDATE UserStat SET visits = visits + 1 WHERE hostname = '" + host + "'";
stmt.executeUpdate(query);
} catch(SQLException ex) {
System.err.println("Cannot update: " + ex.getMessage());
}
}
}
}
BasicMessageBean.java
package p1;
import javax.annotation.Resource;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.EJB;
import javax.ejb.MessageDriven;
import javax.ejb.MessageDrivenContext;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
@MessageDriven(activationConfig = {
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
@ActivationConfigProperty(propertyName = "destinationType", propertyValue =
"javax.jms.Queue"),
@ActivationConfigProperty(propertyName = "destinationLookup", propertyValue = "jms/Queue")
})
public class BasicMessageBean implements MessageListener {
@EJB
VisitorStatBean vs;
@Resource
private MessageDrivenContext mdc;
public BasicMessageBean() {
}
@Override
public void onMessage(Message message) {
try {
if (message instanceof TextMessage) {
TextMessage msg = (TextMessage) message;
vs.addVisitor(msg.getText());
}
} catch (JMSException e) {
mdc.setRollbackOnly();
}
}
}
OUTPUT =
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
Date = 5/10/2023
C] AIM: Develop simple Marks Entry Application to demonstrate accessing Database
using EJB.
Database =
Program =
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">
</head>
<body>
<center>
<form method="post" action="insert.jsp">
Student Id: <Input type="text" name="t1">
Student Name : <input type="text" name="t2"><br><br>
Subjects:<br>
Java: <input type="number" name="m1"><br>
Linux: <input type="number" name="m2"><br>
AWP: <input type="number" name="m3"><br><br>
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
<input type="submit" value="Submit">
</form>
</center>
</body>
</html>
insert.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="p1.DatabaseOperations"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
try{
int sid=Integer.parseInt(request.getParameter("t1"));
String sname=request.getParameter("t2");
int EJ=Integer.parseInt(request.getParameter("m1"));
int LSA=Integer.parseInt(request.getParameter("m2"));
int AWP=Integer.parseInt(request.getParameter("m3"));
DatabaseOperation d1=new DatabaseOperations();
d1.AddMarks(sid, sname, EJ, LSA, AWP);
out.println("<h1>Record is added successfully</h1>");
}catch(Exception ex){
out.println(ex.getMessage());
}
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
%>
</body>
</html>
DatabaseOperations.java
package p1;
import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
import jakarta.ejb.Stateless;
@Stateless
public class DatabaseOperations implements DatabaseOperationsLocal {
public void AddMarks(int sid, String sname, int EJ, int LSA, int AWP)throws Exception
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/TYIT?
useTimeZone=true&serverTimezone=UTC&autoReconnect=true&useSSL=false","root","221001");
PreparedStatement ps=con.prepareStatement("Insert into student values (?,?,?,?,?)");
ps.setInt(1, sid);
ps.setString(2, sname);
ps.setInt(3, EJ);
ps.setInt(4, LSA);
ps.setInt(5, AWP);
ps.executeUpdate();
}
}
DatabaseOperationsLocal.java
package p1;
import jakarta.ejb.Local;
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
@Local
public interface DatabaseOperationsLocal {
}
OUTPUT =
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
Program =
Inventory.jsp
<%@page import="javax.persistence.Persistence"%>
<%@page import="javax.persistence.EntityTransaction"%>
<%@page import="javax.persistence.EntityManager"%>
<%@page import="javax.persistence.EntityManagerFactory"%>
<%@page import="p1.Product"%>
<%@page import="java.util.*" %>%
<%@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>
<%!
private EntityManagerFactory emf;
private EntityManager em;
private EntityTransaction et;
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
private List<Product> allprods;
%>
<%
emf = Persistence.createEntityManagerFactory("InventoryJPAPU");
em = emf.createEntityManager();
Product product = new Product();
product.setPname("Board");
product.setPprice(150);
product.setPqty(200);
product.setPname("Chair");
product.setPprice(350);
product.setPqty(50);
et = em.getTransaction();
et.begin();
em.persist(product);
et.commit();
em.close();
%>
</body>
</html>
Persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="InventoryJPAPU" transaction-type="JTA">
<jta-data-source>java:app/product</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.schema-generation.database.action" value="create"/>
</properties>
</persistence-unit>
</persistence>
Product.java
package p1;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
@Entity
@Table(name = "product")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Product.findAll", query = "SELECT p FROM Product p"),
@NamedQuery(name = "Product.findByPid", query = "SELECT p FROM Product p WHERE p.pid
= :pid"),
@NamedQuery(name = "Product.findByPname", query = "SELECT p FROM Product p WHERE
p.pname = :pname"),
@NamedQuery(name = "Product.findByPprice", query = "SELECT p FROM Product p WHERE
p.pprice = :pprice"),
@NamedQuery(name = "Product.findByPqty", query = "SELECT p FROM Product p WHERE
p.pqty = :pqty")})
public class Product implements Serializable {
public Product() {
}
@Override
public int hashCode() {
int hash = 0;
hash += (pid != null ? pid.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Product)) {
return false;
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
}
Product other = (Product) object;
if ((this.pid == null && other.pid != null) || (this.pid != null && !this.pid.equals(other.pid))) {
return false;
}
return true;
}
@Override
public String toString() {
return "p1.Product[ pid=" + pid + " ]";
}
OUTPUT =
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
B] AIM : Develop a Guestbook Application Using JPA.
Database =
Program =
Index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Guest Book</title>
</head>
<body style="background-color: pink;">
<table style="width: 100%; alignment-adjust: central; border: 0px;">
<tr>
<td>
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
<table style="width: 100%; border: 0px;">
<tr>
<td style="text-align: left; vertical-align: middle; padding-right:0px; padding-left:0px;
padding-bottom:0px; font:24px/30px Georgia; width:228px; color:#786e4e; padding-top:0px;
height:37px;">
Sign the Guest Book
</td>
</tr>
</table>
</td>
</tr>
<tr style="text-align: left; vertical-align: top;">
<td style="height: 20px;"><hr /></td>
</tr>
<tr>
<td>
<form action="GuestBookView.jsp" method="post">
<table style="border-spacing: 2px; border: 0px;">
<tr>
<td style="text-align: right; font-size:15px; font-family:Arial,Times,serif; font-
weight:bold;">
Visitor Name:
</td>
<td>
<input name="guest" maxlength="25" size="50" />
</td>
</tr>
<tr>
<td style="text-align: right; font-size:15px; font-family:Arial,Times,serif; font-
weight:bold;">
Message:
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
</td>
<td>
<textarea rows="5" cols="36" name="message"></textarea>
</td>
</tr>
<tr>
<td colspan="2" style="text-align: right;">
<input type="submit" name="btnSubmit" value="Submit" />
</td>
</tr>
</table>
</form>
</td>
</tr>
</table>
</body>
</html>
GuestBookView.jsp
<%@page
import="java.util.Iterator,javax.persistence.Persistence,java.util.List,p1.GuestBook,javax.persistence.E
ntityTransaction,javax.persistence.EntityManager,javax.persistence.EntityManagerFactory" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%!
private EntityManagerFactory entityManagerFactory;
private EntityManager entityManager;
private EntityTransaction entityTransaction;
List<GuestBook> guestbook;
%>
<%
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
entityManagerFactory = Persistence.createEntityManagerFactory("GuestBookJPAPU");
entityManager = entityManagerFactory.createEntityManager();
String submit = request.getParameter("btnSubmit");
if(submit != null && ("Submit").equals(submit)) {
try {
String guest = request.getParameter("guest");
String message = request.getParameter("message");
String messageDate = new java.util.Date().toString();
GuestBook gb = new GuestBook();
gb.setVisitorName(guest);
gb.setMessage(message);
gb.setMessageDate(messageDate);
entityTransaction = entityManager.getTransaction();
entityTransaction.begin();
entityManager.persist(gb);
entityTransaction.commit();
} catch (RuntimeException e) {
if(entityTransaction != null) entityTransaction.rollback();
throw e;
}
response.sendRedirect("GuestBookView.jsp");
}
try {
guestbook = entityManager.createQuery("SELECT g from GuestBook g").getResultList();
} catch (RuntimeException e) {
throw e;
}
entityManager.close();
%>
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Guest Book</title>
</head>
<body style="background-color: pink;">
<table style="alignment-adjust: central; width: 100%; border: 0px;">
<tr>
<td>
<table style="width: 100%; border: 0px;">
<tr>
<td style="width: 60%; vertical-align: middle; text-align: left; padding-right:0px;
padding-left:0px; padding-bottom:0px; font:24px/30px Georgia; width:228px; color:#786e4e; padding-
top:0px; height:37px;">
View the Guest Book
</td>
<td style="vertical-align: bottom; text-align: right; font:12px/16px Georgia, serif;
color:#786e4e;">
<b>Click <a href="index.jsp"> here</a> to sign the guestbook.</b>
</td>
</tr>
</table>
</td>
</tr>
<tr style="text-align: left; vertical-align: top;">
<td style="height: 20px;"><hr /></td>
</tr>
<tr>
<td>
<table style="text-align: left; width: 100%; border: 0px;">
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
<%
Iterator iterator = guestbook.iterator();
while (iterator.hasNext()) {
GuestBook objGb = (GuestBook) iterator.next();
%>
<tr>
<td style="font:12px/16px Georgia; color:#786e4e;">
On <%=objGb.getMessageDate()%>,<br />
<b><%=objGb.getVisitorName()%>:</b>
<%=objGb.getMessage()%>
<br /><br />
</td>
</tr>
<%
}
%>
</table>
</td>
</tr>
</table>
</body>
</html>
GuestBook.java
package p1;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="GuestBook")
public class GuestBook {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="VisitorNo", unique=true, updatable=false)
private Integer visitorNo;
@Column(name="VisitorName")
private String visitorName;
@Column(name="Message")
private String message;
@Column(name="MessageDate")
private String messageDate;
public GuestBook() {
}
public Integer getVisitorNo() {
return visitorNo;
}
public void setVisitorNo(Integer visitorNo) {
this.visitorNo = visitorNo;
}
public String getVisitorName() {
return visitorName;
}
public void setVisitorName(String visitorName) {
this.visitorName = visitorName;
}
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getMessageDate() {
return messageDate;
}
public void setMessageDate(String messageDate) {
this.messageDate = messageDate;
}}
Persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="GuestBookJPAPU" transaction-type="RESOURCE_LOCAL">
<non-jta-data-source>java:app/tyit/GuestBook</non-jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties/>
</persistence-unit>
</persistence>
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
OUTPUT =
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
Practical 9B
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
B] AIM : Develop a Hibernate application to store Feedback of Website Visitor in
MySQL Database.
Database =
Program =
GuestBook.java
package p1;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="GuestBook")
public class GuestBook implements java.io.Serializable {
@Id
@GeneratedValue
@Column(name="VisitorNo")
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
private Integer visitorNo;
@Column(name="VisitorName")
private String visitorName;
@Column(name="Message")
private String message;
@Column(name="MessageDate")
private String messageDate;
public GuestBook() {
}
public GuestBook(String visitorName, String message, String messageDate) {
this.visitorName = visitorName;
this.message = message;
this.messageDate = messageDate;
}
public Integer getVisitorNo() {
return visitorNo;
}
public void setVisitorNo(Integer visitorNo) {
this.visitorNo = visitorNo;
}
public String getVisitorName() {
return visitorName;
}
public void setVisitorName(String visitorName) {
this.visitorName = visitorName;
}
public String getMessage() {
return message;
}
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
public void setMessage(String message) {
this.message = message;
}
public String getMessageDate() {
return messageDate;
}
public void setMessageDate(String messageDate) {
this.messageDate = messageDate;
}
}
Hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/GuestBook?
zeroDateTimeBehavior=convertToNull</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">hello</property>
<mapping class="myApp.GuestBook"/>
</session-factory>
</hibernate-configuration>
Index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Guest Book</title>
</head>
<body style="background-color: pink;">
<table style="width: 100%; alignment-adjust: central; border: 0px;">
<tr>
<td>
<table style="width: 100%; border: 0px;">
<tr>
<td style="text-align: left; vertical-align: middle; padding-right:0px; padding-left:0px;
padding-bottom:0px; font:24px/30px Georgia; width:228px; color:#786e4e; padding-top:0px;
height:37px;">
Sign the Guest Book
</td>
</tr>
</table>
</td>
</tr>
<tr style="text-align: left; vertical-align: top;">
<td style="height: 20px;"><hr /></td>
</tr>
<tr>
<td>
<form action="GuestBookView.jsp" method="post">
<table style="border-spacing: 2px; border: 0px;">
<tr>
<td style="text-align: right; font-size:15px; font-family:Arial,Times,serif; font-
weight:bold;">
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
Visitor Name:
</td>
<td>
<input name="guest" maxlength="25" size="50" />
</td>
</tr>
<tr>
<td style="text-align: right; font-size:15px; font-family:Arial,Times,serif; font-
weight:bold;">
Message:
</td>
<td>
<textarea rows="5" cols="36" name="message"></textarea>
</td>
</tr>
<tr>
<td colspan="2" style="text-align: right;">
<input type="submit" name="btnSubmit" value="Submit" />
</td>
</tr>
</table>
</form>
</td>
</tr>
</table>
</body>
</html>
GuestBookView.jsp
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
<%@page
import="java.util.Iterator,org.hibernate.Transaction,org.hibernate.service.ServiceRegistryBuilder,org.hi
bernate.cfg.Configuration,org.hibernate.service.ServiceRegistry,java.util.List,myApp.GuestBook,org.hi
bernate.SessionFactory"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%!
SessionFactory sessionFactory;
ServiceRegistry serviceRegistry;
org.hibernate.Session hibernateSession;
List<GuestBook> guestbook;
%>
<%
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new
ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
hibernateSession = sessionFactory.openSession();
Transaction transaction = null;
hibernateSession.save(gb);
transaction.commit();
} catch (RuntimeException e) {
if(transaction != null) transaction.rollback();
throw e;
}
response.sendRedirect("GuestBookView.jsp");
}
try {
hibernateSession.beginTransaction();
guestbook = hibernateSession.createQuery("from GuestBook").list();
} catch (RuntimeException e) {
throw e;
}
hibernateSession.close();
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Guest Book</title>
</head>
<body style="background-color: pink;">
<table style="alignment-adjust: central; width: 100%; border: 0px;">
<tr>
<td>
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
<table style="width: 100%; border: 0px;">
<tr>
<td style="width: 60%; vertical-align: middle; text-align: left; padding-right:0px;
padding-left:0px; padding-bottom:0px; font:24px/30px Georgia; width:228px; color:#786e4e; padding-
top:0px; height:37px;">
View the Guest Book
</td>
<td style="vertical-align: bottom; text-align: right; font:12px/16px Georgia, serif;
color:#786e4e;">
<b>Click <a href="index.jsp"> here</a> to sign the guestbook.</b>
</td>
</tr>
</table>
</td>
</tr>
<tr style="text-align: left; vertical-align: top;">
<td style="height: 20px;"><hr /></td>
</tr>
<tr>
<td>
<table style="text-align: left; width: 100%; border: 0px;">
<%
Iterator iterator = guestbook.iterator();
while (iterator.hasNext()) {
GuestBook objGb = (GuestBook) iterator.next();
%>
<tr>
<td style="font:12px/16px Georgia; color:#786e4e;">
On <%=objGb.getMessageDate()%>,<br />
<b><%=objGb.getVisitorName()%>:</b>
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)
<%=objGb.getMessage()%>
<br /><br />
</td>
</tr>
<%
}
%>
</table>
</td>
</tr>
</table>
</body>
</html>
OUTPUT:-
NAME – MD ZAYA KHALDI ROLL NO. - 222304
SEM – 5, CLASS – TY.B.Sc(IT) SUB – EJ(ENTERPRISES JAVA)