EJ Lab Manual
EJ Lab Manual
EJ Lab Manual
Practical 1
CODE:
index.html
<html>
<body>
</form>
</body>
</html>
CalcServlet.java
{ response.setContentType("text/html");
a=Integer.parseInt(request.getParameter("t1"));
int b=Integer.parseInt(request.getParameter("t2"));
int c=0;
String op=request.getParameter("btn");
if (op.equals("+"))
c=a+b;
else if (op.equals("-"))
c=a-b;
else if (op.equals("*"))
c=a*b;
else if (op.equals("/"))
c=a/b;
out.println("<b>"+a+op+b+" = "+c+"<b>");
}
OUTPUT:
Q.1 b) Create a servlet for a login page. If the username and password are correct then it
says message “Hello ” else a message “login failed”.
CODE:
index.html <html>
<body>
</form>
</body>
</html>
LoginServlet.java
extends HttpServlet {
response.setContentType("text/html");
String username=request.getParameter("uname");
String password=request.getParameter("pw");
String msg="";
msg="Hello "+username;
out.println("<b>"+msg+"<b>");
OUTPUT:
Q.1 c) 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.
Code:
4. Enter table name user by replacing untitled. Click on Add column, name -> username,
type-> varchar, size-> 20, select checkbox of primary key, again click on Add column
password varchar size 20, again click on Add column emailid varchar(20), again click
Add column country varchar 10;
5. add mysql-connector to library folder of the current application
index.html <html>
<body>
<option>select...
<option> India
<option> Bangladesh
<option> Bhutan
<option> Canada
</select> <br>
</form>
</body>
</html>
RegistrationServlet.java
{ Connection con=null;
PreparedStatement ps=null;
response.setContentType("text/html");
String username=request.getParameter("uname");
String password=request.getParameter("pw");
String emailid=request.getParameter("email");
String country=request.getParameter("coun");
try
{ Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/registerdb","root","tiger");
catch(Exception e) { out.println(e); }
out.println("<b>"+"<b>");
OUTPUT:
PRACTICAL 2
Q.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.
PREPARED BY: MS. BEENA KAPADIA AND MS. PAYAL SHAH
T.Y.B.Sc. IT SEM V ENTERPRISE JAVA LAB MANUAL
CODE:
Index.html
<html>
<body>
</form>
</body>
</html>
ValidateServlet.java
{ res.setContentType("text/html");
PrintWriter out=res.getWriter();
String username=req.getParameter("un");
String password=req.getParameter("pw");
if(password.equals("Servlet"))
req.setAttribute("s1username",username);
req.setAttribute("s1password",password);
rd.forward(req, res);
PREPARED BY: MS. BEENA KAPADIA AND MS. PAYAL SHAH
T.Y.B.Sc. IT SEM V ENTERPRISE JAVA LAB MANUAL
else
out.print("Incorrect password");
rd.include(req, res);
WelcomeServlet.java
{ res.setContentType("text/html");
out.println("Welcome "+s2username);
OUTPUT:
Q.2 b) Create a servlet that uses Cookies to store the number of times a user has visited
servlet.
CODE:
CookieServlet.java
PREPARED BY: MS. BEENA KAPADIA AND MS. PAYAL SHAH
T.Y.B.Sc. IT SEM V ENTERPRISE JAVA LAB MANUAL
/*
* To change this template file, choose Tools | Templates * and open the
*/
package pract2;
extends HttpServlet
{ response.setContentType("text/html");
String k=String.valueOf(i);
response.addCookie(c); int
j=Integer.parseInt(c.getValue());
if(j==1)
else
{ synchronized(CookieServlet.this)
} i++;
PREPARED BY: MS. BEENA KAPADIA AND MS. PAYAL SHAH
T.Y.B.Sc. IT SEM V ENTERPRISE JAVA LAB MANUAL
OUTPUT:
Q.2 c) 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.
CODE:
PREPARED BY: MS. BEENA KAPADIA AND MS. PAYAL SHAH
T.Y.B.Sc. IT SEM V ENTERPRISE JAVA LAB MANUAL
CalculationVisitServlet.java
package sessionapp;
/*
*/
package pract2;
/*
*/
{ private int
counter;
response.setContentType("text/html");
HttpSession session=request.getSession(true);
if(session.isNew())
++counter;
else {
PREPARED BY: MS. BEENA KAPADIA AND MS. PAYAL SHAH
T.Y.B.Sc. IT SEM V ENTERPRISE JAVA LAB MANUAL
synchroni
zed(HttpS
essionSer
vlet.this)
if(counter==10)
{ session.invalidate();
counter=0;
request.getSession(false);
else
OUTPUT:
PRACTICAL 3
Q.3 a) Create a Servlet application to upload and download a file.
CODE:
Uploading a file
Index.html
<br>
</form>
javax.servlet.annotation.MultipartConfig; import
res.setContentType("text/html");
String path=req.getParameter("destination");
Part filePart=req.getPart("file");
String sfilePart=req.getPart("file").toString();
String filename=filePart.getSubmittedFileName().toString();
OutputStream os=null;
InputStream is=null;
try {
catch(FileNotFoundException e){out.print(e);}
}}
Downloading a file
Index.html
<body>
<br/><br/>
</body>
DownloadServlet.java package
{ response.setContentType("APPLICATION/OCTET-STREAM");
ask you about the editor with which you want to open the file
int i;
os.write(b);
is.close();
os.close();
OUTPUT:
Right click on table-> click on ‘view data’ -> right click on empty dataset -> insert a record
click on OK
CODE:
QueAnsDBServlet.java
package dbapp; import javax.servlet.*; import
HttpServlet
response.setContentType("text/html");
try
out.print("<html><body><br>");
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost/queansdb","root","tiger");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(sql);
int i=0;
out.print("<center>Online Exam</center>");
while(rs.next())
i++;
out.print("<br><br><hr>"+rs.getInt(1)+" ");
String ans="ans"+i;
out.println("</form>");
out.print("</body></html>");
catch(Exception e)
out.println("ERROR "+e.getMessage());
javax.servlet.*; import
HttpServlet
{ response.setContentType("text/html");
try
{ out.print("<html><body>"); int
total=Integer.parseInt(request.getParameter("total"));
String ans=request.getParameter("ans"+i); if
(sel.equals(ans)) marks++;
out.print("</body></html>");
catch(Exception e)
out.println("ERROR "+e.getMessage());
OUTPUT:
CODE:
Index.html
<html>
<body>
</body>
</html>
AsyncContext ac = null;
input = in;
ac = c; }
onDataAvailable() {
{ ac.complete();
{ ac.complete();
t.printStackTrace();
ReadingNonBlockingServlet.java
javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
{ response.setContentType("text/html");
AsyncContext ac = request.startAsync();
ServletInputStream in=request.getInputStream();
in.setReadListener(new ReadingListener(in,ac));
NonBlockingServlet.java
java.io.*;
import java.net.HttpURLConnection;
java.util.logging.Level; import
java.util.logging.Logger; import
javax.servlet.*; import
javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
@Override
ServletContext c = getServletContext();
InputStream is = c.getResourceAsStream("/"+filename);
Reader</h1>");
//out.flush();
hc.connect();
System.out.println("Reading started...");
{ bw.write(text);
bw.flush();
out.println(text+"<br>");
out.flush(); try
Thread.sleep(1000);
out.print(ex);
bw.write("Reading completed...");
bw.flush(); bw.close();
OUTPUT:
PRACTICAL 4
Q.4 a) Develop a simple JSP application to display values obtained from the use of intrinsic
objects of various types.
CODE:
PREPARED BY: MS. BEENA KAPADIA AND MS. PAYAL SHAH
T.Y.B.Sc. IT SEM V ENTERPRISE JAVA LAB MANUAL
index.jsp
<html>
<body>
<form action="implicitObjectEx.jsp">
</form>
</body> </html>
implicitObjectEx.js
<html>
<head>
<title>JSP Page</title>
</head>
<body>
<h1>Request Object</h1>
<h1>Response Object</h1>
<h1>Session Object</h1>
ID<%=session.getId() %><br>
</body>
</html>
OUTPUT:
Q.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).
CODE:
Index.jsp
<html>
<body>
<form action="Validate.jsp">
Enter Your Name <input type="text" name="name"><br>
Enter Your Age <input type="text" name="age"><br>
Select Hobbies <input type="checkbox" name="hob" value="Singing">Singing
<input type="checkbox" name="hob" value="Reading">Reading Books
<input type="checkbox" name="hob" value="Football">Playing Football<br>
Enter E-mail<input type="text" name="email"><br>
Select Gender <input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="other">Other<br>
<input type="hidden" name="error" value="">
<input type="submit" value="Submit Form">
</form >
</body>
</html>
CheckerBean.java
Validate.jsp
successful.jsp
OUTPUT:
Q.4 c) Create a registration and login JSP application to register and authenticate the
user based on username and password using JDBC.
PREPARED BY: MS. BEENA KAPADIA AND MS. PAYAL SHAH
T.Y.B.Sc. IT SEM V ENTERPRISE JAVA LAB MANUAL
CODE:
Index.html
<html> <head>
<title>New User Registration Page</title>
</head>
<body>
<form action="Registration.jsp">
<h1>New User Registration Page</h1>
Enter User Name<input type="text" name="txtName"><br>
Enter Password<input type="password" name="txtPass1"><br>
Re-Enter Password<input type="password" name="txtPass2"><br>
Enter Email<input type="text" name="txtEmail"><br>
Enter Country Name<select name="txtCon">
<option>India</option>
<option>France</option>
<option>England</option>
<option>Argentina</option>
</select><br>
<input type="submit" value="REGISTER"><input type="reset">
</form>
</body>
</html>
Registration.jsp
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/logindb",”root”,”tiger”);
PreparedStatement stmt=con.prepareStatement("insert into userpass 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 FAILED!!!!");
%>
<jsp:include page="index.html"></jsp:include>
<%
}
}catch(Exception e){out.println(e);}
} else { out.println("<h1>Password
Mismatch</h1>");
%>
<jsp:include page="index.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="submit" value="~~~LOGIN~~"><input type="reset">
</form>
</body>
</html>
Login.jsp
String pass=request.getParameter("txtPass");
ResultSet rs=null; try{
Class.forName("com.mysql.jdbc.Driver"); Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/logindb"",”root”,”tiger”);
Statement stmt=con.createStatement(); rs=stmt.executeQuery("select password from
userpass where username='"+uname+"'"); rs.next(); if(pass.equals(rs.getString(1)))
{
out.println("<h1>~~~LOGIN SUCCESSFULLL~~~</h1>");
} else { out.println("<h1>password does not
match!!!!!</h1>");
%>
<jsp:include page="index.html"></jsp:include>
<%
}
}catch(Exception e){ out.println("<h1>User does
not exist!!!!!</h1>");
%>
<jsp:include page="index.html"></jsp:include>
<%
}
%>
</body>
</html>
OUTPUT:
PRACTICAL 5
Q.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.
PREPARED BY: MS. BEENA KAPADIA AND MS. PAYAL SHAH
T.Y.B.Sc. IT SEM V ENTERPRISE JAVA LAB MANUAL
CODE:
Index.html
<html>
<body>
<form action="UpdateEmp.jsp" >
Enter Employee Number<input type="text" name="txtEno" ><br>
Enter Salary to update<input type="text" name="txtSal" ><br>
<input type="reset" ><input type="submit">
</form>
</body>
</html>
UpdateEmp.jsp
}catch(Exception e){out.println(e);}
%>
</body>
</html>
OUTPUT:
CODE:
a. Index.jsp
<body>
<h3>welcome to index page</h3>
<%
session.setAttribute("user","Admin");
%>
<%
Cookie ck=new Cookie("name","mycookie"); response.addCookie(ck);
%>
<form action="ExpressionLanguage.jsp">
Enter Name:<input type="text" name="name" /><br/><br/>
<input type="submit" value="Submit"/>
</form> </body>
b. ExpressionLanguage.jsp
<body>
Welcome, ${ param.name }
Session Value is ${ sessionScope.user } Cookie
name is , ${cookie.name.value}
</body>
c. ELArithemeticOperator.jsp
<body>
<%-- arithmetic op --%>
5*5+4: ${5*5+4} <br>
1.4E4+1.4: ${1.4E4+1.4}<br> 10
mod 4: ${10 mod 4}<br>
15 div 3: ${15 div 3}<br>
</body>
d. ELLogicalOperator.jsp
<body>
<%-- LogicalOperator --%>
<h2>Logical Operator</h2> true and
true: ${true and true}<br> true &&
false: ${true && false}<br> true or
true: ${true or true}<br> true || false:
${true || false}<br> not true: ${not
true}<br>
!false: ${!false}
</body>
e. ELRelationalOperator.jsp
<body>
<%-- RelationalOperator --%>
<h2>Relational Operator</h2>
10.0==10: ${10.0==10} <br>
10.0 eq 10: ${10.0 eq 10} <br>
((20*10)!= 200): ${((20*10)!= 200)} <br>
3 ne 3: ${3 ne 3} <br>
3.2>=2: ${3.2>=2} <br>
3.2 ge 2: ${3.2 ge 2} <br>
2<3: ${2<3} <br>
4 lt 6: ${4 lt 6} <br>
2 <= 4: ${2 <= 4} <br>
4 le 2: ${4 le 2}
</body>
f. ELconditional op
<body>
<h2>Conditional Operator</h2>
g. Empty Operator
OUTPUT:
CODE:
index.html
<html><body>
</body></html>
setDemo.jsp
${pageTitle}
Maxif.html
</form>
<c:if test="${x>y}">
</c:if>
ForeachDemo.jsp
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
</c:forEach>
outDemo.jsp
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
URLDemo.jsp
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:url value="/index.html"/>
choose_when_otherwise.jsp
<c:choose>
</c:when>
</c:when>
<c:otherwise>
Income is undetermined
</c:otherwise>
</c:choose>
OUTPUT:
PRACTICAL 6 Q.6 a)
CODE:
Index.html
<html><head><title>Currency Converter</title></head>
<body>
</form>
</body>
</html>
Step 2 : Create a session bean named as CCBean in the package named mybeans.
Select the option Stateless and click on Local Interface.
Here you will find two files created in the mybeans package named as CCBean.java
CCBean.java
javax.ejb.Stateless;
CCBean1Local
r)
{ return
r/65.65;
d)
{ return
d*65.65;
{ response.setContentType("text/html;charset=UTF-8");
Double.parseDouble(request.getParameter("amt"));
if(request.getParameter("type").equals("r2d"))
PREPARED BY: MS. BEENA KAPADIA AND MS. PAYAL SHAH
T.Y.B.Sc. IT SEM V ENTERPRISE JAVA LAB MANUAL
Dollars</h1>");
} if(request.getParameter("type").equals("d2r"))
Rupees</h1>");
}
OUTPUT:
CODE:
Index.html
<html>
<head>
<title>Room Reservation</title>
</head>
<body>
</form>
</body>
</html>
Step2: Create a session bean named as RoomBean in the package named ejb. Select
the option Stateless and click on Local Interface.
Here you will find two files created in the ejb package named as RoomBean.java and
RoomBeanLocal.java
RoomBeanLocal.java
package ejb; import
javax.ejb.Local;
RoomBeanLocal {
RoomBean.java
package ejb; import javax.ejb.Stateless; import
no) {
try
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost/roomdb","root","tiger");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery(sql1);
rs.next(); int
total=rs.getInt(1);
int occ=rs.getInt(2);
int free=total-occ;
System.out.println(total);
System.out.println(free);
if (free>=no)
PreparedStatement ps=con.prepareStatement(sql2);
ps.setInt(1, occ+no);
int res=ps.executeUpdate();
return res;
PREPARED BY: MS. BEENA KAPADIA AND MS. PAYAL SHAH
T.Y.B.Sc. IT SEM V ENTERPRISE JAVA LAB MANUAL
} else
return 0;
catch(Exception e)
return 0;
try
{ Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost/roomdb","root","tiger");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery(sql1);
rs.next(); int
total=rs.getInt(1); int
occ=rs.getInt(2); if
(occ>=no)
PreparedStatement ps=con.prepareStatement(sql2);
ps.setInt(1, occ-no);
int res=ps.executeUpdate();
return res;
} else
return 0;
catch(Exception e)
return 0;
ejb.RoomBeanLocal; import
javax.servlet.http.*; import
javax.servlet.annotation.*;
try { int
no=Integer.parseInt(request.getParameter("t1"));
String b=request.getParameter("btn");
int res=0;
if(b.equals("CheckIN"))
res=obj.checkin(no); if
check-in");
if(b.equals("CheckOUT"))
res=obj.checkout(no); if
check-out");
finally {
out.close();
OUTPUT:
Q.6 c) Develop simple shopping cart application using EJB [Stateful Session Bean].
CODE:
File -> new project-> java web->web application -> Prac6CShoppingCartApp -> select
Use dedicated folder for storing libraries -> finish
Source package -> new -> other -> enterprise java beans -> session bean -> next -> new
session bean -> ejb name: ->ShoppingCart -> package: -> ejb -> session type option ->
Stateful -> finish. ShoppingCart.java
package ejb; import
java.sql.*; import
java.util.*; import
javax.ejb.*; @Stateful
{ if (person != null) {
customerName = person;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch(SQLException e) {
System.err.println("Sorry failed to insert values from the database table. " + e.getMessage());
try { stmt =
conn.createStatement();
} catch(SQLException e) {
System.err.println("Sorry failed to delete values from the database table. " + e.getMessage());
stmt.executeQuery(query); while(rs.next()) {
contents.add(rs.getString("ItemName"));
} catch(SQLException e) {
System.err.println("Sorry failed to select values from the database table. " + e.getMessage());
} return
contents;
@Remove() public
void remove() {
contents = null;
Right click on wewb pages -> new -> JSP -> filename -> index -> finish.
<!DOCTYPE html>
<%!
try {
ic.lookup("java:global/Prac6CShoppingCartApp/ShoppingCart");
}
PREPARED BY: MS. BEENA KAPADIA AND MS. PAYAL SHAH
T.Y.B.Sc. IT SEM V ENTERPRISE JAVA LAB MANUAL
%>
<%
if(request.getParameter("txtCustomerName") != null) {
cart.initialize(request.getParameter("txtCustomerName"));
} else {
cart.initialize("Guest");
if (request.getParameter("btnRmvBook") != null) {
cart.removeBook(books[i]);
if (request.getParameter("btnAddBook") != null) {
if (books != null) {
cart.addBook(books[i]);
%>
<html>
<head>
<title>Shopping Cart</title>
</head>
<form method="post">
<b>Book Titles</b><br>
<br>
<%
if(cart!=null)
out.print("<b>Basket</b><br>");
(iterator.hasNext())
%>
<%
%>
</form>
</body>
</html>
Step 4:
Services -> create database -> cartdb ->select cartdb - > right click -> create table ->
cart -> UserName varchar 35
Step 5.
OUTPUT:
PRACTICAL 7
Q.7 a) Develop simple EJB application to demonstrate Servlet Hit count using Singleton
Session Beans.
CODE:
Step 1: 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">
<meta http-equiv="Refresh" content="0; URL=ServletClient">
</head>
<body>
<div>TODO write content</div>
</body>
</html>
Step 3: Create a Servlet File name ServletClient in the package name as servlet.
Do not select the Deployment Discriptor file.
package servlet;
import ejb.CountServletHitsBean;
import java.io.*; import
javax.ejb.EJB;
import javax.servlet.ServletException; import
javax.servlet.annotation.WebServlet; import
javax.servlet.http.*;
@WebServlet(name = "ServletClient", urlPatterns = {"/ServletClient"}) public
class ServletClient extends HttpServlet {
@EJB CountServletHitsBean obj;
@Override
protected void service (HttpServletRequest req, HttpServletResponse res) throws ServletException,
IOException
{
res.setContentType("text/html"); PrintWriter out=res.getWriter();
out.print("<b>Number of times this Servlet is accessed </b>: "+obj.getCount());
}
}
OUTPUT:
Q.7 b) Develop simple visitor Statistics application using Message Driven Bean [Stateless
Session Bean].
CODE:
Step 1: index.jsp
<%@page import="javax.jms.JMSException"%>
<%@page import="javax.naming.InitialContext"%>
<%@page import="javax.jms.Connection"%>
<%@page import="javax.jms.TextMessage"%>
<%@page import="javax.jms.MessageProducer"%>
<%@page import="javax.jms.Session"%>
<%@page import="javax.jms.Queue"%>
<%@page import="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>JSP Page</title>
</head>
<body>
Welcome to My Home Page
<%
try{
InitialContext ic= new InitialContext(); queue=
(Queue)ic.lookup("jms/Queue");
connectionFactory=(ConnectionFactory)ic.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)
PREPARED BY: MS. BEENA KAPADIA AND MS. PAYAL SHAH
T.Y.B.Sc. IT SEM V ENTERPRISE JAVA LAB MANUAL
{
System.out.println("Exception Occoured "+e.toString());
}
%>
</body>
</html>
Step2: Create a Database name visitorstat Create table name userstat column
names
Firstvisitdt – timestamp
Hostname – varchar 30 Primary Key
Visits – int
@PreDestroy public
void disconnect()
{ try
{
conn.close();
} catch (Exception e) {
System.err.println(e.getMessage());
}
} public void addVisitor(String
host)
{ try { st= conn.createStatement(); query="insert into userstat
(hostname,visits) values ('"+host+"','1')"; st.executeUpdate(query);
}
catch (SQLException e)
{ try { st=conn.createStatement(); query="update userstat
set visits=visits+1 where hostname='"+host+"' ";
st.executeUpdate(query);
}
catch (SQLException ex) {
System.err.println("Cannot Update"+e.getMessage());
}
}
}
Step 4: Right click on Source Packages Select New Other Enterprise Java Bean
MessageDrivenBean EJB Name: BasicMessageBean Package: ejb Select
Project Destination Click on Add Button Destination Name: jms/Queue
Destination Type select the option Queue click on OK Click on Next Activation
Configuration Properties should be as it is. Click on Finish
package ejb;
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 = {
@ActivationConfigProperty(propertyName = "destinationLookup", propertyValue = "jms/Queue"),
@ActivationConfigProperty(propertyName = "destinationType", propertyValue =
"javax.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();
}
}
}
Step 5:
Before deploying and running the application, Glassfish Server setting is required.
Browse the path:
Localhost:4848 on any browser.
Find Resources -> connectors -> Connector Resources double click on Connector
Resources -> click on ‘New’ Button -> write JNDI name as -> jms/QueryFactory.
Find Admin Object Resources and double click on that -> click on ‘New’ Button ->
write JNDI name as -> jms/Queue.
OUTPUT:
CODE:
Step 1:
Step 2:
3:
PREPARED BY: MS. BEENA KAPADIA AND MS. PAYAL SHAH
T.Y.B.Sc. IT SEM V ENTERPRISE JAVA LAB MANUAL
create table marks (id int primary key auto_increment, sname varchar(35), marks1 int,
marks2 int, marks3 int); step 4: index.jsp
<%@page import="ejb.MarksEntryBean"%>
<%@page import="javax.naming.InitialContext"%>
<!DOCTYPE html>
<%!
void jspInit()
try
obj=(MarksEntryBean)ic.lookup("java:global/Pract7CMarksApp/MarksEntryBean");
catch(Exception e)
System.out.println(e);
%>
<%
if(request.getParameter("InsertMarks")!=null)
sname = request.getParameter("sname");
PREPARED BY: MS. BEENA KAPADIA AND MS. PAYAL SHAH
T.Y.B.Sc. IT SEM V ENTERPRISE JAVA LAB MANUAL
marks1=Integer.parseInt(request.getParameter("m1"));
marks2=Integer.parseInt(request.getParameter("m2"));
marks3=Integer.parseInt(request.getParameter("m3"));
obj.addMarks(sname,marks1,marks2,marks3);
%>
<html>
<head>
<title>JSP Page</title>
</head>
<body>
<h2>Enter Details</h2>
</form>
</body>
</html>
Step 4:
create stateful java bean as select source package -> session bean -> class name ->
MarksEntryBean -> package -> ejb -> bean type-> stateful -> don’t select Local /
MarksEntryBean { String
Connection con=null;
try
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/marksdb", "root","tiger");
st=con.createStatement();
st.executeUpdate(query);
catch(Exception e){System.out.println(e);}
OUTPUT:
PRACTICAL 9
Q.9 a) Develop a JPA Application to demonstrate use of ORM associations.
CODE:
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>
</body>
</html>
userview.jsp
<%@page import="java.util.List"%>
<%@page import="java.util.Iterator"%>
<%@page import="hibernate.User"%> <%!
SessionFactory sf;
org.hibernate.Session ss;
List<hibernate.User> User;
%>
<%
sf = new Configuration().configure().buildSessionFactory();
ss= sf.openSession(); Transaction tx=null; User ur=new
User(); try
{
tx=ss.beginTransaction();
String uname=request.getParameter("uname");
String utype=request.getParameter("utype");
ur.setUname(uname);
ur.setUtype(utype);
ss.save(ur); tx.commit();
{
ss.beginTransaction();
User=ss.createQuery("from User").list();
}
catch(Exception e){ }
%>
<html> <head>
<title>Guest View</title>
</head>
<body>
Guest View
Click here to go <a href="index.html"> BACK </a>
<br><br>
<%
Iterator it=User.iterator();
while(it.hasNext())
User eachrecord=(User)it.next();
out.print(eachrecord.getUid()+" ");
out.print(eachrecord.getUname()+"<br>");
out.print(eachrecord.getUtype()+"<br><hr>");
}
%>
</body>
</html>
hibernate.revenge.xml
<hibernate-reverse-engineering>
<schema-selection match-catalog="userdb"/>
<table-filter match-name="user"/>
</hibernate-reverse-engineering>
hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
PREPARED BY: MS. BEENA KAPADIA AND MS. PAYAL SHAH
T.Y.B.Sc. IT SEM V ENTERPRISE JAVA LAB MANUAL
User.hbm.xml
<hibernate-mapping>
<class optimistic-lock="version" catalog="userdb" table="user" name="hibernate.User">
<id name="uid" type="java.lang.Integer">
<column name="uid"/>
<generator class="identity"/>
</id>
<property name="uname" type="string">
<column name="uname" length="20"/>
</property>
<property name="utype" type="string">
<column name="utype" length="100"/>
</property>
</class>
</hibernate-mapping>
User.java package
hibernate;
public class User implements java.io.Serializable {
private Integer uid; private String uname; private
String utype; public User() { } public
User(String uname, String utype) { this.uname
= uname; this.utype = utype;
}
public Integer getUid() {
return this.uid;
this.uid = uid;
} public String
getUname()
{ return
this.uname;
}
public void setUname(String uname)
{
this.uname = uname;
} public String
getUtype()
{
return this.utype;
}
OUTPUT:
Select Services -> right click on database -> connect -> password -> ok ->again right
click on database -> create database -> db -> ok.
Expand db -> Select and right click table -> click on Execute command -> Create
table guestbook (no int primary key auto_increment, name varchar(20), msg
varchar(100), dt varchar(40));
Right click on Project -> new -> other -> select Hibernate -> Hibernate Reverse
Engineering wizard file type -> next -> file name (hibernate.reveng) , folder -> click
on browse and select src->java -> next -> select guestbook table name from the
available tables option -> click add ( select the checkbox – include related files) ->
finish.
Step 4: Adding Hibernate mapping files and POJOs from Database file type:-
Right click on Project -> new -> other -> select Hibernate -> Hibernate mapping files
and POJOs from Database file type) -> next -> keep the default configuration file
name file name (hibernate.cfg) and Hibernate Reverse Engineering File
(hibernate.reveng) -> type the package name (hibernate) -> finish.
CODE:
return this.no;
this.no = no;
return this.name;
this.name = name;
return this.msg;
this.msg = msg;
return this.dt;
this.dt = dt;
<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/db</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">tiger</property>
<mapping resource="hibernate/Guestbook.hbm.xml"/>
</session-factory>
</hibernate-configuration>
</id>
</property>
</property>
</property>
</class>
</hibernate-mapping>
<html>
<head>
<title>Guest Book</title>
</head>
<body>
</form>
</body>
</html>
<%@page import="org.hibernate.Session"%>
<%@page import="org.hibernate.cfg.Configuration"%>
<%@page import="org.hibernate.Transaction"%>
<%@page import="java.util.List"%>
import="hibernate.Guestbook"%>
<%!
SessionFactory sf;
org.hibernate.Session ss;
List<hibernate.Guestbook> gbook;
%>
<%
sf = new Configuration().configure().buildSessionFactory();
try
tx=ss.beginTransaction();
String name=request.getParameter("name");
String
msg=request.getParameter("msg");
gb.setName(name); gb.setMsg(msg);
gb.setDt(dt); ss.save(gb);
tx.commit();
try
{ ss.beginTransaction();
gbook=ss.createQuery("from Guestbook").list();
catch(Exception e){ }
%>
<html>
<head>
<title>Guest View</title>
</head>
<body>
Guest View
<br><br>
while(it.hasNext())
Guestbook eachrecord=(Guestbook)it.next();
out.print(eachrecord.getDt()+" ");
out.print(eachrecord.getName()+"<br>");
out.print(eachrecord.getMsg()+"<br><hr>");
%>
</body>
</html>
OUTPUT:
Q.9 c) Develop a Hibernate application to store and retrieve employee details in MySQL
Database.
CODE:
index.html
<html>
<head>
<title>Employee Details</title>
</head>
<body>
Employee Details <hr><br><br>
<form action="empview.jsp" >
Name <input type="text" name="name" maxlength="20"><br>
Salary <input type="text" name="salary" maxlength="20"><br>
Designation <input type="text" name="designation" maxlength="20">
<br><input type="submit" value="submit">
</form>
</body>
</html>
empview.jsp
<%@page import="org.hibernate.SessionFactory"%>
<%@page import="org.hibernate.Session"%>
<%@page import="org.hibernate.cfg.Configuration"%>
<%@page import="org.hibernate.Transaction"%>
<%@page import="java.util.List"%>
<%@page import="java.util.Iterator"%>
<%@page import="hibernate.Emp"%>
<%!
SessionFactory sf;
org.hibernate.Session ss;
List<hibernate.Emp> Emplist;
%>
<% sf = new
Configuration().configure().buildSessionFactory();
em.setSalary(Salary);
em.setDesignation(Designation);
System.out.print("set done........................");
ss.save(em);
System.out.print("save done...................");
tx.commit();
System.out.print("commit done.............");
}
try
{
ss.beginTransaction();
Emplist=ss.createQuery("from Emp").list();
}
catch(Exception e){ }
%>
<html>
<head>
<title>Employee View</title>
</head>
<body>
Employee View
PREPARED BY: MS. BEENA KAPADIA AND MS. PAYAL SHAH
<%
Iterator it=Emplist.iterator(); while(it.hasNext())
{
Emp eachrecord=(Emp)it.next(); out.print(eachrecord.getName()+"<br>");
out.print(eachrecord.getSalary()+"<br><hr>");
out.print(eachrecord.getDesignation()+"<br><hr>");
}
%>
hibernate.revenge.xml
<hibernate-reverse-engineering>
<schema-selection match-catalog="employeedb"/>
<table-filter match-name="emp"/>
</hibernate-reverse-engineering>
hibernate1.cfg.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/employeedb?zeroDateTimeBehavior=
c onvertToNull</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">tiger</property>
</session-factory>
</hibernate-configuration>
<hibernate-mapping>
<class optimistic-lock="version" catalog="employeedb" table="emp" ame="hibernate.Emp">
<id name="id" type="java.lang.Integer">
<column name="id"/>
<generator class="identity"/>
</id>
<property name="name" type="string">
<column name="name" length="20"/>
</property>
<property name="salary" type="string">
<column name="salary" length="20"/>
</property>
<property name="designation" type="string">
<column name="designation" length="20"/>
</property>
</class>
</hibernate-mapping>
Emp.java
package hibernate; public class Emp implements
java.io.Serializable { private Integer id; private
String name; private String salary; private String
designation; public Emp() { }
public Emp(String name, String salary, String designation)
{ this.name = name; this.salary = salary;
this.designation = designation;
}
public Integer getId() { return
this.id;
} public void setId(Integer id)
{ this.id = id;
}
public String getName() { return
this.name;
} public void setName(String name)
{ this.name = name;
OUTPUT: