Java 17
Java 17
Java 17
2024-2025
ROLL NO : 17
Class: TY Bsc.IT
1A. Create a simple calculator application using servlet.
Steps to be followed:-
index.html
<html><head>
<title>Calculator App</title></head><body>
<form action="CalculatorServlet" >
Enter First Number <input type="text" name="txtN1"><br>
Enter Second Number <input type="text" name="txtN2" ><br>
Select an Operation<input type="radio" name="opr" value="+">
ADDTION <input type="radio" name="opr" value="-">
SUBSTRACTION <input type="radio" name="opr" value="*">
MULTIPLY <input type="radio" name="opr" value="/">
DIVIDE <br><input type="reset">
<input type="submit" value="Calculate" >
</form></body></html>
1|Page
CalculatorServlet.java
packagemypack;
import java.io.*;
importjavax.servlet.*;
importjavax.servlet.http.*;
public class CalculatorServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throwsServletException, IOException { response.setContentType("text/
html;charset=UTF- 8");
PrintWriter out = response.getWriter();
out.println("<html><head><title>Servlet
CalculatorServlet</title></head><body>");
double n1 = Double.parseDouble(request.getParameter("txtN1"));
double n2 = Double.parseDouble(request.getParameter("txtN2"));
double result =0;
String opr=request.getParameter("opr");
if(opr.equals("+"))
result=n1+n2;
if(opr.equals("*"))
result=n1*n2;
out.println("<h1> Result = "+result);
if(opr.equals("-"))
result=n1-n2;
if(opr.equals("/"))
result=n1/n2;
out.println("</body></html>");
} }
Output:-
2|Page
1B. Create a servlet for a login page. If the username and password are
correct then it says message “Hello <username>” else a message “login
failed”
Follow the same steps for creating project as defined in Practical 1A.
index.html
<html><head><title>Login Form</title></head>
<form action="LoginServlet" >
Enter User ID<input type="text" name="txtId"><br>
Enter Password<input type="password" name="txtPass"><br>
<input type="reset">
LoginServlet.java
packagemypack;
import java.io.*;
importjavax.servlet.ServletException;
importjavax.servlet.http.*;
public class LoginServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throwsServletException, IOException
{ response.setContentType("text/
html;charset=UTF-8"); PrintWriter out =
response.getWriter();
out.println("<html><head><title>Servlet LoginServlet</title></head>");
String uname = request.getParameter("txtId");
String upass = request.getParameter("txtPass");
if(uname.equals("admin") &&upass.equals("12345"))
{
out.println("<body bgcolor=blue >");
out.println("<h1> Welcome !!! "+uname+"</
h1>"); }
else
{
out.println("<body bgcolor=red >");
out.println("<h1> Login Fail !!! </h1>");
3|Page
}
out.println("</body></html>");}}
Output:-
4|Page
1C. Create a registration Servlet in Java using JDBC. Accept the details such
as Username, Password, Email, and Country from the user using HTML Form
and store the registration details in the database.
Follow the same steps for creating project as defined in Practical 1A.
3. To Add JAR/Folder
Go to Libraries->Right Click->Select Add/Folder->Browse for MySql Connector.
index.html
<html><head><title>Registration Page</title></head><body>
<form action="RegisterServlet" >
<H1>Welcome to Registration page</H1>
Enter User Name<input type="text" name="txtUid"><br>
Enter Password<input type="password" name="txtPass"><br>
Enter Email <input type="text" name="txtEmail" ><br>
Enter Country<input type="text" name="txtCon" ><br>
<input type="reset" ><input type="submit" value="REGISTER" >
</form></body></html>
RegisterServlet.java
package mypack;
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class RegisterServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
5|Page
throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String id = request.getParameter("txtUid");
String ps = request.getParameter("txtPass");
String em = request.getParameter("txtEmail");
String co = request.getParameter("txtCon");
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con =DriverManager.getConnection ("jdbc:mysql://
localhost:3306/sr", “root”,”admin123”); PreparedStatement pst =
con.prepareStatement("insert into user values (?,?,?,?)");
pst.setString(1,id);
pst.setString(2,ps);
pst.setString(3,em);
pst.setString(4,co);
int row = pst.executeUpdate();
out.println("<h1>"+row+ " Inserted Succesfullyyyyy"); }catch(Exception e)
{ out.println(e);
}}
}
6|Page
2a. 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.
Follow the same steps for creating project as defined in Practical 1A.
Files Required:
1. index.html
2. LoginServlet.java
3. WelcomeServlet.java
index.html
<html><head><title>Login Form</title></head>
<form action="LoginServlet" >
Enter User ID<input type="text" name="txtId"><br>
Enter Password<input type="password" name="txtPass"><br>
<input type="reset">
<input type="submit" value=" Click to Login " >
</form>
</html>
LoginServlet.java
package mypack;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class LoginServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{ response.setContentType("text/
html;charset=UTF-8"); PrintWriter out =
response.getWriter(); out.println("<html><head>");
out.println("<title>Servlet LoginServlet</title></head>");
String uname = request.getParameter("txtId");
String upass = request.getParameter("txtPass");
7|Page
if(uname.equals("admin") && upass.equals("servlet"))
{
RequestDispatcher rd = request.getRequestDispatcher("WelcomeServlet");
rd.forward(request, response);
}
else
{
out.println("<body bgcolor=red >");
out.println("<h1> Login Fail !!! </h1>");
RequestDispatcher rd = request.getRequestDispatcher("index.html");
rd.include(request, response);
} out.println("</
body>"); out.println("</
html>"); }}
WelcomeServlet.java
package mypack;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class LoginServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{ response.setContentType("text/
html;charset=UTF-8"); PrintWriter out =
response.getWriter(); out.println("<html><head>");
out.println("<title>Servlet LoginServlet</title></head>");
String uname = request.getParameter("txtId");
String upass = request.getParameter("txtPass");
if(uname.equals("admin") && upass.equals("servlet"))
{
RequestDispatcher rd = request.getRequestDispatcher("WelcomeServlet");
rd.forward(request, response);
}
else
{
8|Page
out.println("<body bgcolor=red >");
out.println("<h1> Login Fail !!! </h1>");
RequestDispatcher rd = request.getRequestDispatcher("index.html");
rd.include(request, response);
} out.println("</
body>"); out.println("</
html>"); } }
Output:-
9|Page
2B. Create a Servlet that uses Cookies to store the number of times a user has
visited Servlet.
Follow the same steps for creating project as defined in Practical 1A.
Files Required:
1. index.html
2. Create five Servlet files(Page1.java, Page2.java, Page3.java, Page4.java,
Page5.java)
index.html
<html>
<head><title>Cookie Demo</title></head>
<body>
<form action="Page1" >
Enter Your Name <input type="text" name="txtName"><br>
<input type="submit" value="~~~ Click to Enter ~~~"> </form>
</body>
</html>
Page1.java
package mypack;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Page1 extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF- 8");
PrintWriter out = response.getWriter();
out.println("<html><head><title>Page1</title></head>");
out.println("<body bgcolor=pink >");
String uname = request.getParameter("txtName");
out.println("<h1>~~~ Welcome "+uname+"</h1>");
Cookie ck1 = new Cookie("username", uname);
10 | P a g e
Cookie ck2 = new Cookie("visit","1");
response.addCookie(ck1); response.addCookie(ck2);
out.println("<h1><a href=Page2 >Click to visit Page 2 </a></h1>");
out.println("</body>");
out.println("</html>");
}
}
Page2.java
package mypack;
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class Page2 extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{ response.setContentType("text/
html;charset=UTF-8"); PrintWriter out =
response.getWriter();
out.println("<html><head><title>Page2</title></head>");
out.println("<body bgcolor=yellow >");
Cookie [] ck = request.getCookies();
for(int i=0;i<ck.length;i++)
{ if(ck[i].getName().equals("visit")
){
int count = Integer.parseInt(ck[i].getValue())+1;
out.println("<h1>Visit No : "+count+"</h1>");
ck[i] = new Cookie("visit",count+"");
response.addCookie(ck[i]);
}
else
{
out.println(ck[i].getName()+ " =
"+ck[i].getValue()); }
out.println("<h1><a href=Page3 >Click to visit Page 3 </a></h1>");
out.println("<h1><a href=Page4 >Click to visit Page 4 </a></h1>");
11 | P a g e
out.println("<h1><a href=Page5 >Click to visit Page 5 </a></h1>");
out.println("</body>");
out.println("</html>");
}}
Repeat the code from Page2.java for Page3.java, Page4.java and Page5.java
with relevant changes.
12 | P a g e
2c. Create a Servlet demonstrating the use of session creation and
destruction. Also check whether the user has visited this page first time or
has visited earlier also using Sessions.
Follow the same steps for creating project as defined in Practical 1A.
Files Required:
1. index.html
2. Create six Servlet files(Page1.java, Page2.java, Page3.java, Page4.java,
Page5.java,LogServlet.java)
index.html
<html>
<head><title>Session Demo</title></head>
<form action="Page1" method="get" >
Enter User ID <input type="text" name="txtName"><br>
<input type="reset" ><input type="submit" > </form>
</html>
Page1.java
package mypack;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Page1 extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html><head><title>Servlet Page1</title></head>");
HttpSession hs = request.getSession(true);
if(hs.isNew())
{
out.println("<body bgcolor=yellow>");
String name = request.getParameter("txtName");
hs.setAttribute("uname", name);
13 | P a g e
hs.setAttribute("visit", "1");
out.println("<h1>Welcome First Time</
h1>"); }
else
{
out.println("<h1>Welcome Again</h1>");
int visit = Integer.parseInt((String)
hs.getAttribute("visit"))+1;
out.println("<h1>You Visited "+visit+"Times</h1>");
hs.setAttribute("visit", ""+visit);
}
out.println("<h1>Your Session ID "+hs.getId()+"</h1>");
out.println("<h1>You Logged in at "+new
java.util.Date(hs.getCreationTime())+"</h1>");
out.println("<h1><a href=Page2>Click for Page 2 </a></h1>");
out.println("<h1><a href=Page3>Click for Page 3 </a></h1>");
out.println("<h1><a href=Page4>Click for Page 4 </a></h1>");
out.println("<h1><a href=LogoutServlet>Click to Terminate Session
</a></h1>");
out.println("</body>");
out.println("</
html>"); } }
Page2.java
package mypack;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Page2 extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{ response.setContentType("text/
html;charset=UTF-8"); PrintWriter out =
response.getWriter();
out.println("<html><head><title>Servlet Page2</title></head>");
HttpSession hs = request.getSession(false);
out.println("<h1>Welcome Again on Page No. 2</h1>");
int visit = Integer.parseInt((String)
14 | P a g e
hs.getAttribute("visit"))+1;
out.println("<h1>You Visited "+visit+"Times</h1>");
hs.setAttribute("visit", ""+visit);
out.println("<h1>Your Session ID "+hs.getId()+"</h1>");
out.println("<h1>You Logged in at "+new
java.util.Date(hs.getCreationTime())+"</h1>");
out.println("<h1><a href=Page1>Click for Page 1 </a></h1>");
out.println("<h1><a href=Page3>Click for Page 3 </a></h1>");
out.println("<h1><a href=Page4>Click for Page 4 </a></h1>");
out.println("<h1><a href=LogoutServlet>Click for Terminate Session
</a></h1>");
out.println("</body>");
out.println("</
html>"); }}
Repeat the code from Page2.java in Page3.java and Page4.java with relevant
changes.
LogoutServlet.java
package mypack;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class LogoutServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{ response.setContentType("text/
html;charset=UTF-8"); PrintWriter out =
response.getWriter();
out.println("<html><head><title>Servlet LogoutServlet</title></head>");
out.println("<body>");
javax.servlet.http.HttpSession hs = request.getSession();
if(hs != null)
hs.invalidate();
out.println("<h1>You are Logged out now........</h1>");
out.println("</body>");
out.println("</html>");
}}
15 | P a g e
16 | P a g e
3A. Create a Servlet application to upload a file.
Follow the same steps for creating project as defined in Practical 1A.
Required Files:
1. index.html
2. FileUploadServlet.java
index.html
<html>
<body>
<form action="FileUploadServlet" method="post" enctype="multipart/form-
data">
Select File to Upload:<input type="file" name="file" id="file">
Destination <input type="text" value="/tmp" name="destination"> <br>
<input type="submit" value="Upload file" name="upload" id="upload">
</form></body></html>
FileUploadServlet.java
package mypack;
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.*;
@MultipartConfig
public class FileUploadServlet extends HttpServlet
{
public void doPost(HttpServletRequest req,HttpServletResponse res) throws
ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String path=req.getParameter("destination");
Part filePart=req.getPart("file");
String filename=filePart.getSubmittedFileName().toString();
out.print("<br><br><hr> file name: "+filename);
OutputStream os=null;
InputStream is=null;
17 | P a g e
try
{
os=new FileOutputStream(new File(path+File.separator+filename));
is=filePart.getInputStream();
int read=0;
while ((read = is.read()) != -1)
{
os.write(read);
}
out.println("<br>file uploaded
sucessfully...!!!"); }
catch(FileNotFoundException e)
{ out.print(e);
} }}
Output:-
18 | P a g e
3A1. Create a Servlet application to download a file.
Follow the same steps for creating project as defined in Practical 1A.
Required Files:
1. index.html
2. FileDownloadServlet.java
index.html
<html><head>
<title>File Download Page</title>
</head><body>
<h1>File Download Application</h1>
Click <a href="DownloadServlet?filename=Book Details.txt">
Sample Chapter</a> <br/><br/>
Click <a href="DownloadServlet?filename=circular queue.txt">Table Of
Contents</a> </body></html>
DownloadServlet.java
package mypack;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
19 | P a g e
public class DownloadServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{ response.setContentType("APPLICATION/OCTET-STREAM");
String filename = request.getParameter("filename");
ServletContext context = getServletContext();
InputStream is = context.getResourceAsStream("/" + filename);
//ServletOutputStream out =
response.getOutputStream(); // any of the two works
PrintWriter out=response.getWriter(); response.setHeader("Content-
Disposition","attachment; filename=\"" + filename + "\"");
int i;
while ((i=is.read()) != -1)
{ out.write(i
); }
is.close();
out.close();
}}
Output:-
20 | P a g e
3B. Develop Simple Servlet Question Answer Application using Database.
Follow the same steps for creating project as defined in Practical 1A.
Required Files:
1. index.html
2. QuizServlet.java
3. ShowServlet.java
use qabd;
create table quiz (qno varchar(5) PRIMARY KEY, question varchar(100), op1
varchar(50), op2 varchar(50), op3 varchar(50), op4 varchar(50), ans
varchar(50));
21 | P a g e
index.html
QuizServlet.java
package mypack;
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class QuizServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{ response.setContentType("text/html;charset=UTF- 8");
PrintWriter out = response.getWriter();
out.println("<form action=ShowResult >");
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con DriverManager.getConnection
("jdbc:mysql://localhost:3306/qadb","root","root");
Statement stmt = con.createStatement();
ResultSet res = stmt.executeQuery("select * from quiz");
out.println("<table border=1 >");
int qno=0;
while(res.next())
{ qno++;
out.println("<tr><td>"+res.getString(1)+"</td>");
out.println("<td>"+res.getString(2)+"</td></tr>");
out.println("<tr><td><input type=radio name="+qno+"
value="+res.getString(3)+"></td><td>"+res.getString(3)+"</td></tr>");
out.println("<tr><td><input type=radio name="+qno+"
value="+res.getString(4)+"></td><td>"+res.getString(4)+"</td></tr>");
out.println("<tr><td><input type=radio name="+qno+"
value="+res.getString(5)+"></td><td>"+res.getString(5)+"</td></tr>");
22 | P a g e
out.println("<tr><td><input type=radio name="+qno+"
value="+res.getString(6)+"></td><td>"+res.getString(6)+"</td></tr>"); }
}catch(Exception e){out.println(e);
}
out.println("</table>");
out.println("<input type=reset >");
out.println("<input type=submit value=SUBMIT >");
out.println("</form>"); } }
ShowResult.java
package mypack;
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ShowResult extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection
("jdbc:mysql://localhost:3306/qadb","root","admin123");
Statement stmt = con.createStatement();
ResultSet res = stmt.executeQuery("select ans from quiz");
int count =0, qno=0;
while(res.next())
{ if(res.getString(1).equals(request.getParameter(""+(+
+qno)))) {
count++; out.println("<h1>Correct </h1>");
}else
{
out.println("<h1>Incorrect </h1>");
}}
23 | P a g e
out.println("<h1>Your Score is "+count+" </
h1>"); }
catch(Exception e)
{
out.println(e);
}}}
Output:-
24 | P a g e
3c. Create simple Servlet application to demonstrate Non-Blocking Read
Operation.
Follow the same steps for creating project as defined in Practical 1A.
Required Files:
1. index.java(Servlet File)
2. testin.txt(Write some contents into the file)
3. testout.txt(keep it blank)
index.java
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
public class index
{
public static void main(String args[]) throws IOException
{
FileInputStream input = new FileInputStream ("D:\
\testin.txt"); // Path of Input text file
ReadableByteChannel source = input.getChannel();
FileOutputStream output = new FileOutputStream ("D:\\testout.txt");
// Path of Output text file
WritableByteChannel destination = output.getChannel();
copyData(source, destination);
source.close();
destination.close();
}
private static void copyData(ReadableByteChannel src, WritableByteChannel d
est) throws IOException
{
ByteBuffer buffer = ByteBuffer.allocateDirect(20 * 1024);
while (src.read(buffer) != -1)
{
// The buffer is used to drained
buffer.flip();
// keep sure that buffer was fully drained
while (buffer.hasRemaining())
{
25 | P a g e
dest.write(buffer);
}
buffer.clear(); // Now the buffer is empty, ready for the filling
} }}
Output:-
26 | P a g e
4a. Develop a simple JSP application to display values obtained from the
use of intrinsic objects of various types.
Index.jsp
Output:-
27 | P a g e
4b. Develop a simple JSP application to pass values from one page to another
with validations.
Follow the same steps for creating project as defined in Practical 1A.
Required Files:
1. index.html
2. Validate.jsp
3. CheckerBean.java
index.html
Validate.jsp
28 | P a g e
<jsp:forward page="successful.jsp"/>
<%
}
else {%>
<jsp:include page="index.html"/>
<%
}%>
<%=obj.getError() %>
</body></html>
CheckerBean.java
package mypack;
public class CheckerBean
{
private String name, age, hob, email, gender, error;
public CheckerBean()
{ error="
"; }
public void setName(String n)
{
name=n;
}
public void setAge(String a)
{ age=
a; }
public void setHob(String h)
{ hob=
h; }
public void setEmail(String e)
{
email=e;
}
public void setGender(String g)
{
gender=g;
}
public void setError(String e)
29 | P a g e
{ error=e
;}
public String getName()
{
return name;
}
public String getAge()
{
return age;
}
public String getHob()
{
return hob;
}
public String getEmail()
{
return email;
}
public String getGender()
{
return gender;
}
public String getError()
{
return error;
}
public boolean validate()
{
boolean res=true;
if(name.trim().equals(""))
{
error+="<br>Enter First Name";res=false;
}
if(age.length() > 2 )
{
error+="<br>Age Invalid";res=false;
}
return res;
}}
30 | P a g e
Output:-
31 | P a g e
4c. Create a registration and login JSP application to register and
authenticate the user based on username and password using JDBC.
Register.html
Register.jsp
32 | P a g e
PreparedStatement stmt = con.prepareStatement("insert into user values
(?,?,?,?)");
stmt.setString(1, uname); stmt.setString(2, pass1); stmt.setString(3, email);
stmt.setString(4, ctry); int row = stmt.executeUpdate();
if(row==1) { out.println("Registration
Successful"); }
else
{
out.println("Registration FFFFFAAAIIILLLL !!!!"); %><jsp:include
page="Register.html" ></jsp:include>
<%
}
}catch(Exception e){out.println(e);}
}
else
{
out.println("<h1>Password Mismatch</h1>");
%>
<jsp:include page="Register.html" ></jsp:include>
<%
}
%>
</body> </html>
Login.html
<html><body>
<h1>Login Page</h1>
<form action="Login.jsp" >
Enter User Name <input type="text" name="txtName" ><br>
Enter Password <input type="password" name="txtPass" ><br>
<input type="reset" ><input type="submit" value="~~~LOGIN~~" >
</form></body></html>
Login.jsp
33 | P a g e
<%
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/logindb");
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 SUCCESSFULLL ~~~ </
h1>"); }}
else{
out.println("<h1>User Name not exist !!!!!</h1>");
%>
<jsp:include page="Register.html" ></jsp:include>
<%
}
}
catch(Exception e)
{ out.println(e)
;}
%>
</body></html>
Output:-
34 | P a g e
35 | P a g e
5a. Create an html page with fields, eno, name, age, desg, salary. Now on
submit this data to a JSP page which will update the employee table of
database with matching eno.
index.html
UpdateEmp.java
36 | P a g e
PreparedStatement stmt = con.prepareStatement("select * from emp where
empid=?");
stmt.setString(1, eno);
ResultSet rs = stmt.executeQuery();
if(rs.next())
{
out.println("<h1>~~~ Employee "+name+" Exist ~~~ </h1>");
PreparedStatement pst1= con.prepareStatement("update emp set salary=?
where empid=?");
PreparedStatement pst2= con.prepareStatement("update emp set age=?
where empid=?");
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>
37 | P a g e
5b. Create a JSP page to demonstrate the use of Expression language.
Arithmetic Operation
index.jsp
Looping
38 | P a g e
for(int i=0;i<num;i++){
out.println(i);
}%>
</body>
</html>
39 | P a g e
5c. Create a JSP application to demonstrate the use of JSTL. Basic insert,
update and delete example using core and sql tag libraries in JSTL.
Required Files:
index.jsp
Output:-
Example 2:
Output:-
Step 1
Login to the database in MYSQL
Step 2
Create the Employee table in the TEST database as follows − −
mysql> use pracc;
mysql> create table Employees
(
id int not null,
age int not null,
first varchar (255),
last varchar (255)
);
mysql> INSERT INTO Employees VALUES (100, 18, 'Zara', 'Ali');
mysql> INSERT INTO Employees VALUES (101, 25, 'Mahnaz', 'Fatma');
mysql> INSERT INTO Employees VALUES (102, 30, 'Zaid', 'Khan');
mysql> INSERT INTO Employees VALUES (103, 28, 'Sumit', 'Mittal');
41 | P a g e
index.jsp
Output:-
42 | P a g e
6a. Create a Currency Converter application using EJB.
Follow the same steps for creating project as defined in Practical 1A.
Required Files:
1. index.html
2. CCServlet.java(Servlet File)
3. CCBean.java(Stateless Session Bean File)
43 | P a g e
index.html
CCServlet.java
package mypack;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.ejb.EJB;
import mybeans.CCBean;
public class CCServlet extends HttpServlet
{
@EJB CCBean obj; public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
double amt = Double.parseDouble(request.getParameter("amt"));
if(request.getParameter("type").equals("r2d"))
{
out.println("<h1>"+amt+ " Rupees = "+obj.r2Dollor(amt)+" Dollors</h1>");
}
if(request.getParameter("type").equals("d2r"))
{
out.println("<h1>"+amt+ " Dollors = "+obj.d2Rupees(amt)+" Rupees</
h1>"); } }}
44 | P a g e
CCBean
package mybeans;
import javax.ejb.Stateless;
@Stateless
public class CCBean
{
public CCBean()
{}
public double r2Dollor(double r)
{
return r/65.65;
}
public double d2Rupees(double d)
{
return d*65.65;
}}
45 | P a g e
6b. Develop a Simple Room Reservation System Application Using EJB.
Follow the same steps for creating project as defined in Practical 1A.
Required Files:
1. RoomBook.html
2. RBServlet.java
3. RRBean.java
4. Create Database using MYSQL
Database:
RoomBook.html
RBServlet.java
package mypack;
import java.io.*;
import javax.servlet.*;
46 | P a g e
import javax.servlet.http.*;
import javax.ejb.EJB;
import mybeans.RRBean;
public class RBServlet extends HttpServlet
{
@EJB RRBean obj;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter out=response.getWriter();
String rt=request.getParameter("txtType");
String cn=request.getParameter("txtCust");
String cm=request.getParameter("txtMob");
String msg = obj.roomBook(rt, cn, cm);
out.println(msg);
}}
RRBean.java
To create Stateless Session Bean (RRBean.java) refer the steps from 6A.
package mybeans;
import javax.ejb.Stateless;
import java.sql.*;
@Stateless
public class RRBean
{
public RRBean()
{}
public String roomBook(String rt, String cn, String cm)
{
String msg="";
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection
("jdbc:mysql://localhost:3306/rrdb","root","admin123");
String query="select * from roombook where RoomType=? and status='Not
Booked'"; PreparedStatement pst = con.prepareStatement(query);
pst.setString(1,rt);
47 | P a g e
ResultSet rs= pst.executeQuery();
if(rs.next())
{
String rno=rs.getString(1);
PreparedStatement stm1 = con.prepareStatement("update roombook set
cust=? where RoomId=? ");
PreparedStatement stm2 = con.prepareStatement("update roombook set
mobile=? where RoomId=? ");
PreparedStatement stm3=con.prepareStatement("update roombook set
status=?where RoomId=? ");
stm1.setString(1,cn);
stm1.setString(2,rno);
stm2.setString(1,cm);
stm2.setString(2,rno);
stm3.setString(1, "Booked");
stm3.setString(2,rno);
stm1.executeUpdate();
stm2.executeUpdate();
stm3.executeUpdate();
msg = "Room "+rno+ " Booked <br> Charges =
"+rs.getString(3); }
else
{
msg = "Room "+rt+ " currently Not available";
}
}
catch(Exception e)
{
msg=""+e;
}
return msg;
}}
48 | P a g e
Output:-
49 | P a g e
6c. Develop simple shopping cart application using EJB [Stateful Session
Bean].
50 | P a g e
Step 5: EJB Name->Provide Package Name->Select Stateful Session Type->
Select Local Interface
51 | P a g e
You have two files under EnterpriseApplication-ejb->Source Packages->cart->
CartBean.java and CartBeanLocal.java
CartBeanLocal.java
package cart;
import java.util.List;
import javax.ejb.Local;
@Local
public interface CartBeanLocal
{
public void initialize(String person) throws Exception;
public void initialize(String person, String id)
throws Exception;
public void addBook(String title);
public void removeBook(String title) throws Exception;
public List<String> getContents();
public void remove();
}
CartBean.java
package cart;
import java.util.*;
import javax.ejb.*;
@Stateful
public class CartBean implements CartBeanLocal
{
String customerName;
String customerId;
List<String> contents;
public void initialize(String person, String id)
throws Exception
{
if (person == null)
{
throw new Exception("Null person not
allowed."); }
else
{
52 | P a g e
customerName =
person; }
if ( person=="ABC" && id=="123")
{
customerId = id;
}
else
{
throw new Exception("Invalid id: " + id);
}
contents = new ArrayList<String>();
}
public void addBook(String title)
{
contents.add(title);
}
public void removeBook(String title) throws Exception
{
boolean result = contents.remove(title);
if (result == false)
{
throw new Exception(title + " not in
cart."); } }
public List<String> getContents()
{
return contents;
}
@Remove
public void remove()
{
contents =
null; }}
CartTestServlet.java
package testcart;
import cart.CartBeanLocal;
import java.io.*;
import java.util.*;
import java.util.logging.*;
53 | P a g e
import javax.naming.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
@WebServlet(name = "CartTestServlet", urlPatterns = {"/CartTestServlet"})
public class CartTestServlet extends HttpServlet
{
CartBeanLocal cartBean = lookupCartBeanLocal();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF- 8"); try
{
cartBean.initialize("ABC", "123");
}
catch(Exception e)
{}
cartBean.addBook("Java 8 Cookbook");
cartBean.addBook("Enterprise Java 7 ");
cartBean.addBook("Java for Dummies");
cartBean.addBook("Learn Java 8");
try (PrintWriter out = response.getWriter())
{ tr
y{
List<String> books = cartBean.getContents();
for( String s : books)
out.println(s +"<br />");
}
catch(Exception e){}
}}
private CartBeanLocal lookupCartBeanLocal()
{ tr
y{
Context c = new InitialContext();
return (CartBeanLocal)
c.lookup("java:global/EnterpriseApplication1/EnterpriseApplication1-
ejb/CartBean!cart.CartBeanLocal");
54 | P a g e
}
catch (NamingException ne)
{
Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught",
ne);
throw new
RuntimeException(ne); }}}
Output:-
55 | P a g e
7a. Develop simple EJB application to demonstrate Servlet Hit count using
Singleton Session Beans.
Follow the steps for creating new project as defined in Practical 1A.
Files Required:
1. CounterBean.java
2. Count.java
3. HitCountPage.xhtml
CounterBean.java
package counter.ejb;
import javax.ejb.Singleton;
@Singleton
public class CounterBean
{
private int hits = 1;
public int getHits()
56 | P a g e
{
return hits++ ;
}}
Count.java
package mypack;
import java.io.Serializable;
import javax.ejb.EJB;
import javax.enterprise.context.ConversationScoped;
import javax.inject.Named;
import counter.ejb.CounterBean;
@Named("count")
@ConversationScoped
public class Count implements Serializable
{
@EJB
private CounterBean counterBean;
private int hitCount;
public Count()
{
this.hitCount = 0;
}
public int getHitCount()
{
hitCount = counterBean.getHits();
return hitCount;
}
public void setHitCount(int newHits)
{
this.hitCount = newHits;
}}
HitCountPage.xhtml
57 | P a g e
<h:head>
<title>Page Hit Counter Using Singleton Session Bean ~~~~ </title>
</h:head>
<h:body>
<h1>Welcome to Hit Count Page</h1>
Page was hit #{count.hitCount} times
</h:body>
</html>
58 | P a g e
7b. Develop simple visitor Statistics application using Message Driven Bean
[Stateless Session Bean].
Follow the same steps for creating project as defined in Practical 1A.
Required Files:
1. index.jsp
2. VisitorStat.java(Stateless Session Bean File)
3. Add MYSQL connector in Libraries.
4. Database in MYSQL
Database Tables:-
create database bscit;
use bscit;
create table hello(fisrttime varchar(20), visitorname varchar(20), visits in(3));
index.jsp
59 | P a g e
<title>Welcome </title>
</head>
<body style="background-color: pink;">
<h1 style="text-align: center;">Hello World </h1>
</body>
</html>
VisitorStat.java
package ejb;
import java.sql.*;
import javax.annotation.*;
import javax.ejb.Stateless;
@Stateless
public class VisitorStat
{
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/bscit", "root",
"admin123");
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();
60 | P a g e
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)
{ tr
y{
stmt = conn.createStatement();
query = "INSERT INTO hello (visitorname, visits) VALUES('" + host + "','1')";
stmt.executeUpdate(query);
}
catch(SQLException e)
{
try
{
stmt = conn.createStatement();
query = "UPDATE hello SET visits = visits + 1 WHERE visitorname = '" + host +
"'";
stmt.executeUpdate(query);
}
catch(SQLException ex)
{
System.err.println("Cannot update: " +
ex.getMessage()); } } } }
61 | P a g e
7c. Develop simple Marks Entry Application to demonstrate accessing
database using EJB.
3. MarkEntryServ.java(Servlet file)
Database:
create database tyit;
use tyit;
create table marks(Roll_no varchar(10), Name varchar(20), P1 varchar(20), p2
varchar(20), p3 varchar(20), p4 varchar(20), p5 varchar(20));
index.jsp
62 | P a g e
Stateless Session Bean File
MarkEntry.java
package ejb;
impot javax.ejb.Stateless;
import javax.ejb.LocalBean;
import java.sql.*;
@Stateless
@LocalBean
public class MarkEntry
{
public void entry(String srollno, String sname, String p1, String p2, String p3,
String p5)
{
Connection con=null;
Statement st=null;
ResultSet rs= null;
try
{
Class.forname(“com.mysql.jdbc.Driver”);
con=DriverManager.getConnection(“jdbc:mysql://localhost/tyit”,”root”,”admi
n123”);
st=con.createStatement();
st=excuteUpdate(“insert into marks values(‘ “ +srollno+ “ ‘ , ‘ “ +sname+ “ ‘,‘ “
+p1+ “ ‘,‘ “ +p2+ “ ‘,‘ “ +p3+ “ ‘,‘ “ +p4+ “ ‘,‘ “ +p5+
“ ‘)”); }
catch(Exception e)
{
System.out.println(e);
}
}
public String submit(String name)
{
return name.toUpperCase()+ ” record is
submitted!!!”; }
63 | P a g e
Servlet file
MarentryServe.java
package Servlet;
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
import javax.ejb.EJB;
import ejb.MarkEntry;
@WebServlet(name=”MarkentryServ”, urlPatterns={“/MarkentryServe”})
public class MarkentryServe extends HttpServlet
{
@EJB
Markentry bean;
@Override
protected void doPost(HttpServletRequest request, HttpServletRespose
response)throws ServletException, IOException
{
PrintWriter out=response.getWriter();
String id, name, p1, p2,p3,p4,p5;
id=request.getParamter(“txtno”);
name=request.getParameter(“txtname”);
p1= request.getParameter(“txtp1”);
p2= request.getParameter(“txtp2”);
p3= request.getParameter(“txtp3”);
p4= request.getParameter(“txtp4”);
p5= request.getParameter(“txtp5”);
bean.entry(id,name,p1,p2,p3,p4,p5);
out.println(bean.subit(name));
}}
64 | P a g e
8A. Develop a Simple Inventory Application using JPA
65 | P a g e
7. Provide JNDI Name and Select Database Connection. Here, if Database is
already available to which you wish to connect to select it or else follow
the given steps:
a. Select New Database Connection.
b. In New Connection Wizard, it will ask you for Driver Select MYSQL
Connector, and Driver file(JAR file) by clicking on Add button.
66 | P a g e
Table Creation:
Inventory.java
package myApp;
import javax.persistence.*;
@Entity @Table(name=”
Inventory”) public class
Inventory
{
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name=”itemid”, unique=true, updatable=false)
Integer itemid;
@Column(name=”itemname”)
String itemname;
@Column(name=”itemprice”)
String itemprice;
@Column(name=”itemqty”)
String itemqty;
public Inventory()
{}
public Integer getItemid()
{
return itemid;
}
public void setItemid(Interger itemid)
{ this.itemid=itemi
d; }
public String getItemname()
{
return itemname;
}
public void setItemname(String itemname)
{
this.itemname=itemname;
}
67 | P a g e
public String getItemprice()
{
return itemprice;
}
public void setItemprice(String itemprice)
{
this.itemprice=itemprice;
}
public String getItemqty()
{
return itemqty;
}
public void setItemqty(String itemqty)
{
this.itemqty=itempqty;
}
index.jsp
InventoryView.jsp
68 | P a g e
<!DOCTYPE html>
<%!
EntityManagerFactory emf;
EntityManager em;
EntityTransaction tx;
List<Inventory> inventory;
%>
<%
emf=Persistence.createEntityManagerFactory(“InventoryJPAPU”);
em=emf.createEntityManager();
String submit=request.getParameter(“btnsubmit”);
if(submit!=null &&(“Submit”).equals(submit))
{
String name=request.getParameter(“iname”);
String price=request.getParameter(“iprice”;
String qty=request.getParameter(“iqty”);
Inventory gb=new Inventory();
gb.setItemname(name);
gb.setItemprice(price);
gb.setItemqty(qty);
tx=em.getTransaction();
tx.begin();
em.persistence(gb);
tx.commit();
}
catch(Exception e)
{
if(tx!=null)
tx.rollbacl();
throw e;
}
response.sendRequest(“InventoryView.jsp”);
}
try
inventory=em.createQuery(select * from Inventory”).getResult();
}
catch (Exception e)
{
throw e;
}
69 | P a g e
em.close();
%>
<html>
<head>
<meta http-equiv=”Content-Type” content=”txt/html; charset=UTF-8”>
<title> jSP Page</title>
</head>
<body>
<h1> View the Item List</h1>
Click<a href-“index.jsp”>here</a>to go back</br>
Iterator it=inventory.iterator();
while(it.hasNext())
{
Inventory obj=(Inventory)it.next();
<%=obj.getItemname()%>nbsp;
<%=obj.getItemprice()%> .
<%=obj.getItemqty()%></h1>
<%
}
%>
</body>
</html>
Output:
70 | P a g e
8C. Create a Simple JPA application to store and retrieve Book Details.
Database Creation:-
INSERT INTO books VALUES ("808-97365-80", "Java EE Project Using EJB 3, JPA
and Struts For Beginners", "650");
INSERT INTO books VALUES ("978-34-13394-1", "LAMP Programming For
Beginners", "450");
INSERT INTO books VALUES ("21-783592-1", "Struts 2.0 For Beginners", "350");
INSERT INTO books VALUES ("1-34523-880", "Hibernate 3 for Beginners",
"550");
INSERT INTO books VALUES ("783-983242-23", "Oracle For Professionals",
"750");
index.jsp
71 | P a g e
<body style="background-color: pink;">
<form name="frmgetBookDetails" method="post"
action="retrieveBookDetails">
ISBN: <input type="text" name="isbn" id="isbn"/>
<input type="submit" name="btnSubmit" value="Submit"/>
</form>
</body>
</html>
retrieveBookDetails.java
package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.WebServiceRef;
import webservice.BookWS;
@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 retrieveBookDetails</title>");
72 | P a g e
out.println("</head>");
out.println("<body style='background-color: pink;'>");
java.lang.String isbn = request.getParameter("isbn");
out.println(getBookDetails(isbn)); out.println("</
body>");
out.println("</html>");
} }
private String getBookDetails(java.lang.String isbn)
{
webservice.BookWS port = service.getBookWSPort();
return port.getBookDetails(isbn);
}}
BookWS.java
package webservice;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.ejb.Stateless;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
@WebService(serviceName = "BookWS")
@Stateless()
public class BookWS
{
@WebMethod(operationName = "getBookDetails")
public String getBookDetails(@WebParam(name = "isbn") String isbn)
{
try
{ Class.forName("com.mysql.jdbc.Driver").newInstance(
); Connection dbcon = DriverManager.getConnection
("jdbc:mysql://localhost/bookshopcr", "root", "admin123");
Statement stmt = dbcon.createStatement();
String query = "SELECT * FROM Books WHERE isbn = '" + isbn + "'";
ResultSet rs = stmt.executeQuery(query);
73 | P a g e
rs.next();
String bookDetails = "The name of the book is <b>" + rs.getString("BookName")
+ "</b> and its cost is <b>" + rs.getString("BookPrice") + "</b>.";
return bookDetails;
}
catch(SQLException | ClassNotFoundException | InstantiationException |
IllegalAccessException ex)
{
System.out.println("Sorry failed to connect to the Database. " +
ex.getMessage());
}
return null;
}
public BookWS getBookWSPort()
{
throw new UnsupportedOperationException("Not supported yet."); //To
change body of generated methods, choose Tools | Templates.
}
}
74 | P a g e
9B. Develop a Hibernate application to store Feedback of Website Visitor in
MySQL Database.
dmo4j-1.6.1.jar
slf4j-api-1.5.8.jar
From hibernate distribution 3.5.0 Beta-2->lib->bytecode->cglib directory
cglib 2.2.jar
Form the hibernate annotations 3.4.0 G.A ->lib->test directory
slf4j-log4j1.2.jar
log4j.jar
Database Creation:-
GuestBookBean.java
package mypack;
import javax.persistence.*;
@Entity
@Table(name="guestbook")
public class GuestBookBean implements java.io.Serializable
{
@Id
@GeneratedValue
@Column(name="vno")
private Integer visitorNo;
@Column(name="vname")
private String visitorName;
@Column(name="msg")
private String msg;
@Column(name="mdate")
private String msgDate;
public GuestBookBean()
{}
public Integer getVisitorNo()
{
return visitorNo; }
public String getVisitorName()
{
return visitorName;
}
public String getMsg()
{
return msg; }
public String getMsgDate()
76 | P a g e
{
return msgDate; }
public void setVisitorNo(Integer vn)
{
visitorNo = vn ; }
public void setVisitorName(String vn)
{
visitorName=vn;
}
public void setMsg(String m)
{
msg=m;
}
public void setMsgDate(String md)
{ Msgdate=md
;}
Hibernate.cgf.xml
<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/
feedbackdb?ze roDateTimeBehavior=convertToNull</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<mapping class="mypack.GuestBookBean" />
</session-factory>
</hibernate-configuration>
77 | P a g e
index.html
fb.jsp
79 | P a g e
10a. Develop an application to demonstrate Hibernate One- To -One
Mapping Using Annotation.
Required files:-
1. Student.java(Right Click on Source Packages->New->Java Class)
2. Library.java(Right Click on Source Packages->New->Java Class)
3. persistence.xml
4. OnetoOneExample.java
Create Database
create table student(S_ID int(3) primary key, S_NAME varchar(20));
create table library(B_ID int(3) primary key, B_NAME varchar(20), STUD_S_ID
varchar(20));
Create an entity class Student.java abc package that contains student id (s_id)
and student name (s_name);
Student.java
package abc;
import javax.persistence.*;
@Entity
public class Student
{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int s_id;
private String s_name;
public int getS_id() {
return s_id;
}
public void setS_id(int s_id)
{
this.s_id = s_id;
80 | P a g e
}
public String getS_name()
{
return s_name;
}
public void setS_name(String s_name) {
this.s_name = s_name;
}
}
Create another entity class Library.java under abc package that contains book
id (b_id), book name (b_name) and an object of student type marked with
@OneToOne annotation.
Library.java
package abc;
import javax.persistence.*;
@Entity
public class Library
{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int b_id;
private String b_name;
@OneToOne
private Student stud;
public Library(int b_id, String b_name, Student stud) {
super();
this.b_id = b_id;
this.b_name = b_name;
this.stud = stud;
}
public Library()
{
super();
}
public int getB_id()
{
return b_id;
81 | P a g e
}
public void setB_id(int b_id)
{
this.b_id = b_id;
}
public String getB_name()
{
return b_name;
}
public void setB_name(String b_name)
{
this.b_name = b_name;
}
public Student getStud()
{
return stud;
}
public void setStud(Student stud)
{
this.stud =
stud; } }
Persistence.xml
<persistence>
<persistence-unit name="Book_issued">
<class>abc.Student</class>
<class>abc.Library</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver
"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:33
06/mapping"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="admin123"/>
<property name="eclipselink.logging.level" value="SEVERE"/>
<property name="eclipselink.ddl-generation" value="create-or-extend-
tables"/>
82 | P a g e
</properties>
</persistence-unit>
</persistence>
import javax.persistence.*;
public class OneToOneExample
{
public static void main(String[] args)
{
EntityManagerFactory emf = Persistence.createEntityManagerFactory( "Book_i
ssued" );
EntityManager em = emf.createEntityManager( );
em.getTransaction( ).begin( );
Student st1=new Student();
st1.setS_id(1);
st1.setS_name("Vipul");
Student st2=new Student();
st2.setS_id(2);
st2.setS_name("Vimal");
em.persist(st1);
em.persist(st2);
Library lib1=new Library();
lib1.setB_id(101);
lib1.setB_name("Data Structure");
lib1.setStud(st1);
Library lib2=new Library();
lib2.setB_id(102);
lib2.setB_name("DBMS");
lib2.setStud(st2);
em.persist(lib1);
em.persist(lib2);
em.getTransaction().commit();
em.close();
emf.close();
}
}
83 | P a g e
Output:
After the execution of the program, two tables are generated under MySQL
workbench.
Student table - This table contains the student details. To fetch data, run select
* from student query in MySQL.
Library table - This table represents the mapping between student and library.
To fetch data, run select * from library query in MySQL.
84 | P a g e