EJ Practical Journal
EJ Practical Journal
Q.1 b) 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".
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>Login Page</title>
</head>
<body>
<form method="post" action="LoServlet">
username: <input type="text" name="un"><br>
password: <input type="password" name="pw"><br>
<input type="submit" value="login">
</form>
</body>
</html>
LoServlet:-
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class LoServlet extends HttpServlet
{
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String username = req.getParameter("un");
String password = req.getParameter("pw");
if((username.equals("admin"))&&(password.equals("admin123")))
{
out.print("Hello Ab");
}
else
{
out.print("login failed...!!");
}
}
NAME:- Abhishek Misal ROLL NO:- 16302E0011 2
T.Y.B.Sc.IT SEM V ENTERPRISE JAVA PRACTICAL JOURNAL
}
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.
index.html:-
<html><head><title>New User Registration Page</title></head>
<body>
<form action="Register.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>
NAME:- Abhishek Misal ROLL NO:- 16302E0011 3
T.Y.B.Sc.IT SEM V ENTERPRISE JAVA PRACTICAL JOURNAL
<option>England</option>
<option>Argentina</option>
</select><br>
<input type="submit" value="REGISTER" > <input type="RESET" >
</form>
</body>
</html>
Register.jsp:-
<%@page contentType="text/html" import="java.sql.*"%>
<html><body>
<h1>Registration JSP Page</h1>
<%
String uname=request.getParameter("txtName");
String pass1 = request.getParameter("txtPass1");
String pass2 = request.getParameter("txtPass2");
String email = request.getParameter("txtEmail");
String ctry = request.getParameter("txtCon");
if(pass1.equals(pass2))
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/logindb","root","tiger");
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 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>
Output:
NAME:- Abhishek Misal ROLL NO:- 16302E0011 4
T.Y.B.Sc.IT SEM V ENTERPRISE JAVA PRACTICAL JOURNAL
Q.2 b) Create a servlet that uses Cookies to store the number of times a user has
visited servlet.
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>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>
CookieServlet:-
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class CookieServlet extends HttpServlet
{
static int i=1;
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.
VisitServlet.java:-
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class VisitServlet extends HttpServlet
{
private int counter;
public void doGet(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOException
{
indexu.jsp:-
<%@page contentType="text/html" pageEncoding="UTF-8"%>
ReadingNonBlockingServlet.java:-
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
@WebServlet(name ="ReadingNonBlockingServlet",urlPatterns =
{"/ReadingNonBlockingServlet"},asyncSupported = true)
public class ReadingNonBlockingServlet extends HttpServlet
{
@Override
protected void service(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException{
res.setContentType("text/html");
AsyncContext ac=req.startAsync();
ServletInputStream in=req.getInputStream();
in.setReadListener(new ReadingListener(in,ac));
}
}
Output:
index.jsp:-
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</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>
implicitObjectEx.jsp:-
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</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:
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).
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>Validate JSP Page</title>
</head>
<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">
NAME:- Abhishek Misal ROLL NO:- 16302E0011 18
T.Y.B.Sc.IT SEM V ENTERPRISE JAVA PRACTICAL JOURNAL
</form>
</body>
</html>
Validate.jsp:-
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"
import="mypack.*">
</head>
<body>
<h1>Validation Page</h1>
<jsp:useBean id="obj" scope="request"
class="mypack.CheckerBean" >
<jsp:setProperty name="obj" property="*"/>
</jsp:useBean>
<%if (obj.validate())
{ %>
<jsp:forward page="successful.jsp"/>
<% }
else {%>
<jsp:include page="index.html"/>
<%}%>
<%=obj.getError() %>
</body>
</html>
Succesful.jsp:-
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<h1>DATA VALIDATED SUCCESSFULLY </h1>
</body>
</html>
CheckerBean.java:-
package mypack;
import java.beans.*;
import java.io.Serializable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CheckerBean
{
String name, hob, email, gender, error;
int age;
public CheckerBean()
{
name="";
hob="";
email="";
NAME:- Abhishek Misal ROLL NO:- 16302E0011 19
T.Y.B.Sc.IT SEM V ENTERPRISE JAVA PRACTICAL JOURNAL
gender="";
error="";
age=0;
}
public void setName(String n)
{
name=n;
}
public String getName()
{
return name;
}
public void setAge(int a)
{
age=a;
}
public int getAge()
{
return age;
}
public void setHob(String h)
{
hob=h;
}
public String getHob()
{
return hob;
}
public void setEmail(String e)
{
email=e;
}
public String getEmail()
{
return email;
}
public void setGender(String g)
{
gender=g;
}
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";
NAME:- Abhishek Misal ROLL NO:- 16302E0011 20
T.Y.B.Sc.IT SEM V ENTERPRISE JAVA PRACTICAL JOURNAL
res=false;
}
if(age < 0 || age > 99 )
{
error+="<br>Age Invalid";
res=false;
}
String emailregex = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-
9-]+)*(\\.[A-Za-z]{2,})$";
Boolean b = email.matches(emailregex);
if(!b)
{
error+="<br>email Invalid";
res=false;
}
return res;
}
}
Output:
Q.4 c) Create a registration and login JSP application to register and authenticate the
user based on username and password using JDBC.
index.html:-
<html><head><title>New User Registration Page</title></head>
<body>
<form action="Register.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>
NAME:- Abhishek Misal ROLL NO:- 16302E0011 21
T.Y.B.Sc.IT SEM V ENTERPRISE JAVA PRACTICAL JOURNAL
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>
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:-
<%@page contentType="text/html" import="java.sql.*"%>
<html>
<body>
<h1>Registration JSP Page</h1>
<%
String uname=request.getParameter("txtName");
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 user 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)
{
NAME:- Abhishek Misal ROLL NO:- 16302E0011 22
T.Y.B.Sc.IT SEM V ENTERPRISE JAVA PRACTICAL JOURNAL
out.println("<h1>User does not exist !!!!!</h1>");
%>
<jsp:include page="index.html" ></jsp:include>
<% }
%>
</body>
</html>
Register.jsp:-
<%@page contentType="text/html" import="java.sql.*"%>
<html><body>
<h1>Registration JSP Page</h1>
<%
String uname=request.getParameter("txtName");
String pass1 = request.getParameter("txtPass1");
String pass2 = request.getParameter("txtPass2");
String email = request.getParameter("txtEmail");
String ctry = request.getParameter("txtCon");
if(pass1.equals(pass2))
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/logindb","root","tiger");
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 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>
Output:
Index.html:-
<html>
<head>
<title>Currency Converter</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="CCServlet">
Enter Amount: <input type="text" name="amt"><br>
Select Conversion Type<br>
<input type="Radio" name="type" value="r2d" checked>Rupee to Dollar
<input type="Radio" name="type" value="d2r">Dollar to Rupee<br>
<input type="Reset"><br><input type="submit" value="Convert">
</form>
</body>
</html>
CCBean.java:-
package mybeans;
import javax.ejb.Stateless;
@Stateless
public class CCBean implements CCBeanLocal
{
@Override
public double r2Dollar(double r)
{
return r/65.65;
}
@Override
public double d2Rupee(double d)
{
return d*65.65;
}
}
CCBeanLocal.java:-
package mybeans;
import javax.ejb.Local;
@Local
public interface CCBeanLocal
{
public double r2Dollar(double r);
public double d2Rupee(double d);
}
CCServlet.java:-
package mypack;
NAME:- Abhishek Misal ROLL NO:- 16302E0011 33
T.Y.B.Sc.IT SEM V ENTERPRISE JAVA PRACTICAL JOURNAL
import java.io.*;
import javax.ejb.EJB;
import javax.servlet.*;
import javax.servlet.http.*;
import mybeans.CCBeanLocal;
public class CCServlet extends HttpServlet
{
@EJB CCBeanLocal obj;
@Override
public void doGet(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
double amt= Double.parseDouble(req.getParameter("amt"));
if(req.getParameter("type").equals("r2d"))
{
out.println("<h1>"+amt+" Rupee= "+obj.r2Dollar(amt)+" Dollar</h1>");
}
if(req.getParameter("type").equals("d2r"))
{
out.println("<h1>"+amt+" Dollar= "+obj.d2Rupee(amt)+" Rupee</h1>");
}
}
}
Output:
Step 2: Create a Servlet file named as RoomClient. Do not click on web.xml (Deployment
Descriptor)
Index.html:-
<!DOCTYPE html>
<html>
<head>
<title>Room Reservation System</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="RoomClient" method="post">
<br> No of Rooms <input type="text" name="t1">
<br> <input type="submit" name="btn" value="CheckIN">
<br> <input type="submit" name="btn" value="CheckOUT">
</form>
</body>
</html>
RoomBean.java:-
package ejb;
import java.sql.*;
import javax.ejb.Stateless;
@Stateless
public class RoomBean implements RoomBeanLocal
{
@Override
public int checkin(int no)
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost/roomdb","root","tiger");
String sql1="select * from room";
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)
{
String sql2="update room set occ=?";
PreparedStatement ps=con.prepareStatement(sql2);
ps.setInt(1, occ+no);
NAME:- Abhishek Misal ROLL NO:- 16302E0011 35
T.Y.B.Sc.IT SEM V ENTERPRISE JAVA PRACTICAL JOURNAL
int rse=ps.executeUpdate();
return rse;
}
else
{
return 0;
}
}
catch(Exception e)
{
return 0;
}
}
@Override
public int checkout(int no)
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost/roomdb","root","tiger");
String sql1="select * from room";
Statement st=con.createStatement();
ResultSet rs=st.executeQuery(sql1);
rs.next();
int total=rs.getInt(1);
int occ=rs.getInt(2);
if(occ>=0)
{
String sql2="update room set occ=?";
PreparedStatement ps=con.prepareStatement(sql2);
ps.setInt(1, occ-no);
int rse=ps.executeUpdate();
return rse;
}
else
return 0;
}
catch(Exception e)
{
return 0;
}
}
}
RoomBeanLocal.java:-
package ejb;
import javax.ejb.Local;
@Local
public interface RoomBeanLocal
{
public int checkin(int no);
public int checkout(int no);
}
RoomClient.java:-
NAME:- Abhishek Misal ROLL NO:- 16302E0011 36
T.Y.B.Sc.IT SEM V ENTERPRISE JAVA PRACTICAL JOURNAL
package mypack;
import ejb.RoomBeanLocal;
import java.io.*;
import javax.ejb.EJB;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
@WebServlet(name = "RoomClient", urlPatterns = {"/RoomClient"})
public class RoomClient extends HttpServlet
{
@EJB RoomBeanLocal obj;
@Override
protected void doPost(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
try
{
int no=Integer.parseInt(req.getParameter("t1"));
String b=req.getParameter("btn");
int rse=0;
if(b.equals("CheckIN"))
{
rse=obj.checkin(no);
if(rse==1)
out.println(no+" rooms check-in");
}
if(b.equals("CheckOUT"))
{
rse=obj.checkout(no);
if(rse==1)
out.println(no+"rooms check-out");
}
if(rse==0)
{
out.println("not Possible to do Check In/Out");
out.println("<br><br><a href=index.html> Back </a>");
}
}
finally
{
out.close();
}
}
}
Output:
Q.6 c) Develop simple shopping cart application using EJB [Stateful Session Bean].
Step 1: creating application File -> new project-> java web->web application ->
Prac6CShoppingCartApp -> select Use dedicated folder for storing libraries -> finish
Step 2: Creating a stateful session bean Source package -> new -> other -> enterprise java beans -
> session bean -> next -> new session bean -> ejb name: ->ShoppingCart -> package: -> ejb ->
session type option -> Stateful -> finish.
Step 3: creating a web client using index.jsp Right click on wewb pages -> new -> JSP -> filename ->
index -> finish.
Step 4: Create database and database table Services -> create database -> cartdb ->select cartdb -
> right click -> create table -> cart -> UserName varchar 35 ItemName varchar 50 Finish.
Index.jsp:-
<%@page import="java.util.Iterator, java.util.List, javax.naming.InitialContext,
ejb.ShoppingCart"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%!
private static ShoppingCart cart;
public void jspInit() {
try {
InitialContext ic = new InitialContext();
cart = (ShoppingCart) ic.lookup("java:global/ShoppingCartApp/ShoppingCart");
} catch (Exception ex) {
NAME:- Abhishek Misal ROLL NO:- 16302E0011 38
T.Y.B.Sc.IT SEM V ENTERPRISE JAVA PRACTICAL JOURNAL
System.out.println("Could not create cart bean." + ex.getMessage());
}
}
%>
<%
if(request.getParameter("txtCustomerName") != null) {
cart.initialize(request.getParameter("txtCustomerName"));
} else {
cart.initialize("Guest");
}
if (request.getParameter("btnRmvBook") != null) {
String books[] = request.getParameterValues("chkBook");
if (books != null) {
for (int i=0; i<books.length; i++) {
cart.removeBook(books[i]);
}
}
}
if (request.getParameter("btnAddBook") != null) {
String books[] = request.getParameterValues("chkBook");
if (books != null) {
for (int i=0; i<books.length; i++) {
cart.addBook(books[i]);
}
}
}
%>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Shopping Cart</title>
</head>
<body style="background-color: pink;">
<h1 style="text-align: center;">Books For Sale</h1><br>
<form method="post">
Customer Name: <input type="text" name="txtCustomerName" value=<%=
request.getParameter("txtCustomerName")%> /><br>
<b>Book Titles</b><br>
<input type="checkbox" name="chkBook" value="Struts 2.0 For
Beginners">Struts 2.0 For Beginners<br>
<input type="checkbox" name="chkBook" value="Oracle 11g For
Professionals">Oracle 11g For Professionals<br>
<input type="checkbox" name="chkBook" value="Hibernate 3 For
Beginners">Hibernate 3 For Beginners<br>
<input type="checkbox" name="chkBook" value="Java Persistence API In
EJB 3 For Beginners">Java Persistence API In EJB 3 For Beginners<br>
<br>
<input type='submit' value='Add To My Basket' name='btnAddBook'>
<input type='submit' value='Remove From My Basket'
name='btnRmvBook'><br><br><br>
<%
if(cart!=null)
{
out.print("<b>Basket</b><br>");
List<String> bookList = cart.getContents();
NAME:- Abhishek Misal ROLL NO:- 16302E0011 39
T.Y.B.Sc.IT SEM V ENTERPRISE JAVA PRACTICAL JOURNAL
Iterator iterator = bookList.iterator();
while (iterator.hasNext())
{
String title = (String) iterator.next();
%>
<%= title %><br>
<%
}
}
%>
</form>
</body>
</html>
ShoppingCart.java:-
package ejb;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Remove;
import javax.ejb.Stateful;
@Stateful
public class ShoppingCart
{
List<String> contents;
String customerName;
private Connection conn = null;
private ResultSet rs;
private Statement stmt = null;
private String query = null;
public void initialize(String person) {
if (person != null) {
customerName = person;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/cartdb", "root",
"tiger");
} catch(ClassNotFoundException | IllegalAccessException | InstantiationException |
SQLException e) {
System.err.println("Sorry failed to connect to the Database." + e.getMessage());
}
}
contents = new ArrayList<>();
}
public void addBook(String title) {
try {
stmt = conn.createStatement();
query = "INSERT INTO cart VALUES('" + customerName + "','" + title + "')";
stmt.executeUpdate(query);
} catch(SQLException e) {
Index.jsp:-
<%@page import="ejb.MarksEntryBean"%>
<%@page import="javax.naming.InitialContext"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%!
private static MarksEntryBean obj;
public void jspInit()
{
Try
{
InitialContext ic=new InitialContext();
obj=(MarksEntryBean)ic.lookup("java:global/MarksApp/MarksEntryBean");
}
catch(Exception e)
{
System.out.println(e);
}
}
%>
<%
if(request.getParameter("InsertMarks")!=null)
{
String sname;
int marks1, marks2, marks3;
sname = request.getParameter("sname");
marks1=Integer.parseInt(request.getParameter("m1"));
NAME:- Abhishek Misal ROLL NO:- 16302E0011 46
T.Y.B.Sc.IT SEM V ENTERPRISE JAVA PRACTICAL JOURNAL
marks2=Integer.parseInt(request.getParameter("m2"));
marks3=Integer.parseInt(request.getParameter("m3"));
obj.addMarks(sname,marks1,marks2,marks3);
out.print("Marks entered successfully..!!!!");
}
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h2>Enter Details</h2>
<form name="result" method="post">
Enter student's name: <input type='text' name="sname" /><br>
Enter subject 1 marks: <input type='text' name="m1" /><br>
Enter subject 2 marks: <input type='text' name="m2" /><br>
Enter subject 3 marks: <input type='text' name="m3" /><br>
<input type='submit' name="InsertMarks" /><br>
</form>
</body>
</html>
MarksEntryBean:-
package ejb;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
import javax.ejb.Stateful;
@Stateful
public class MarksEntryBean
{
String sname;
int m1,m2,m3;
Connection con=null;
Statement st=null;
String query="";
public void addMarks(String sname,int m1,int m2,int m3)
{
try
{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/marksdb",
"root","tiger");
st=con.createStatement();
query="insert into marks (sname,marks1,marks2,marks3) values
('"+sname+"','"+m1+"','"+m2+"','"+m3+"')";
st.executeUpdate(query);
System.out.print("Marks entered sucessfully!!");
}
catch(Exception e){System.out.println(e);}
}
}
NAME:- Abhishek Misal ROLL NO:- 16302E0011 47
T.Y.B.Sc.IT SEM V ENTERPRISE JAVA PRACTICAL JOURNAL
Output:
Q.9 c) Develop a Hibernate application to store and retrieve employee details in MySQL
Database.
Same steps to be followed as 9b
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>Emp App</title>
</head>
<body>
<form action="empview.jsp" >
Emp Name:- <input type="text" name="ename" maxlength="20"><br>
Emp Salary:- <input type="text" name="esal" maxlength="10"><br>
Emp Designation:- <input type="text" name="edesag" maxlength="100"><br>
<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"%>
NAME:- Abhishek Misal ROLL NO:- 16302E0011 54
T.Y.B.Sc.IT SEM V ENTERPRISE JAVA PRACTICAL JOURNAL
<%@page import="hibernate.Emp"%>
<%!
SessionFactory sf;
org.hibernate.Session ss;
List<hibernate.Emp> ebook;
%>
<%
sf = new Configuration().configure().buildSessionFactory();
ss= sf.openSession();
Transaction tx=null;
Emp ep = new Emp();
try{
tx=ss.beginTransaction();
String name=request.getParameter("ename");
int sal=Integer.parseInt(request.getParameter("esal"));
String disg=request.getParameter("edesag");
ep.setEmpname(name);
ep.setEmpsal(sal);
ep.setEmpdisg(disg);
ss.save(ep);
tx.commit();
}
catch(Exception e){ out.println("Error"+e.getMessage()); }
try{
ss.beginTransaction();
ebook=ss.createQuery("from Emp").list();
}
catch(Exception e){ }
%>
<html><head>
<title>Guest View</title>
</head>
<body>
Guest View
Click here to go <a href="index.jsp"> BACK </a>
<br><br>
<%
Iterator it=ebook.iterator();
while(it.hasNext()){
Emp eachrecord=(Emp)it.next();
out.print(eachrecord.getEmpno() +" ");
out.print(eachrecord.getEmpname() +"<br>");
out.print(eachrecord.getEmpsal() +"<br>");
out.print(eachrecord.getEmpdisg() +"<br><hr>");
}
%>
</body>
</html>
Emp.java:-
package hibernate;
// Generated 4 Oct, 2018 9:15:44 AM by Hibernate Tools 4.3.1
/**
* Emp generated by hbm2java
*/
NAME:- Abhishek Misal ROLL NO:- 16302E0011 55
T.Y.B.Sc.IT SEM V ENTERPRISE JAVA PRACTICAL JOURNAL
public class Emp implements java.io.Serializable {
private Integer empno;
private String empname;
private Integer empsal;
private String empdisg;
public Emp() {
}
public Emp(String empname, Integer empsal, String empdisg) {
this.empname = empname;
this.empsal = empsal;
this.empdisg = empdisg;
}
public Integer getEmpno() {
return this.empno;
}
public void setEmpno(Integer empno) {
this.empno = empno;
}
public String getEmpname() {
return this.empname;
}
public void setEmpname(String empname) {
this.empname = empname;
}
public Integer getEmpsal() {
return this.empsal;
}
public void setEmpsal(Integer empsal) {
this.empsal = empsal;
}
public String getEmpdisg() {
return this.empdisg;
}
public void setEmpdisg(String empdisg) {
this.empdisg = empdisg;
}
}
Output: