You are on page 1of 95

S.I.C.E.

S Degree College of Arts,Science& Commerce


JambhulPhata, Chikhloli, Kalyan--Badlapur Road, Ambernath(w)-421505
Affiliated to University of Mumbai

Certificate
This is to certify that the______________________________ of B.Sc.(I.T.)
degree (Semester- V) Examination has completed the Practical/Journals in
the subject of ________________ during the academic year 2019-20
under the guidance of __________________ being the partial requirement
for the fulfillment of the curriculum of Degree of Bachelor of Science in
Information Technology, University of Mumbai.

Signature of Internal Guide Signature


HOD / In-charge / Coordinator

Signature of External Examiner

College Seal
Sr. Practical Name Date Sign Pg.
No. No.
1. Implement the Following servlet Application. 3
a) Create a simple calculator application using servlet. / / 3
b) Create a servlet for a login page. If the username and 6
password are correct then it says message “Hello” else a / /
message “login failed”.
c) Create a registration servlet in Java using JDBC. Accept the 9
details such as Username, Password, Email, and Country
/ /
from the user using HTML Form and store the registration
details in the database.
d) Servlet Program to find the factorial of n. / / 11
2. Implement the following Servlet applications with 14
Cookies and Sessions.
a) Using Request Dispatcher Interface create a Servlet which 14
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
b) Create a servlet that uses Cookies to store the number of 19
/ /
times a user has visited servlet
c) Create a servlet demonstrating the use of session creation 25
and destruction. Also check whether the user has visited this / /
page first time or has visited earlier also using sessions.
3. Implement the Servlet IO and File applications. 31
a) Create a Servlet application to upload and download a file. / / 31
b) Develop Simple Servlet Question Answer Application using 36
/ /
Database.
c) Develop Simple Servlet Question Answer Application using JSP 39
/ /
and Sevlet.
4. Implement the following JSP applications. 42
a) Develop a simple JSP application to display values obtained 42
/ /
from the use of intrinsic objects of various types.
b) Develop a simple JSP application to pass values from one 43
page to another with validations.(Name-txt, age-txt, hobbies- / /
checkbox, email-txt, gender-radio button).
c) Create a registration and login JSP application to register 46
and authenticate the user based on username and password / /
using JDBC
d) Create Database program using Servlets. / / 49
5. Implement the following JSP JSTL and EL Applications. 52

1|Page
a) Create an html page with fields, eno, name, age, desg, salary. 52
Now on submit this data to a JSP.page which will update the / /
employee table of database with matching eno.
b) Create a JSP page to demonstrate the use of Expression 54
/ /
language.
c) Create a JSP application to demonstrate the use of JSTL. For 56
/ /
database connectivity
d) Create a JSP application to demonstrate the use of JSTL. / / 61
6. Implement the following EJB Applications. 65
a) Create a currency converter application using EJB. / / 65
b) Develop a Simple Room Reservation System Application 69
/ /
Using EJB.
c) Develop simple shopping cart application using EJB 73
/ /
[Stateful Session Bean].
7. Implement the following EJB applications with different 79
types of Beans.
a) Develop a simple EJB application to demonstrate Servlet hit 79
/ /
count Singleton Session Bean
b) Develop simple visitor Statistics application using Message 81
/ /
Driven Bean [Stateless Session Bean].
8. Implement the following JPA applications. 84
a) Develop a Guest Book application JPA. / / 84
9. Implement the following JPA applications with ORM 88
and Hibernate.
a) Develop a Hibernate application to store Feedback of 88
/ /
Website Visitor in MySQL Database.
b) Develop a Hibernate application to store and retrieve 92
/ /
employee details in MySQL Database.

2|Page
Practical No. 1 Implement the Following servlet Application.

a) Create a simple calculator application using servlet.

index.jsp:
<%--
Document : index
Created on : Jul 28, 2018, 9:05:13 AM
Author : Administrator
--%>
<%@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>CALCULATOR PROGRAM</h1>
<form method="get"action="calci">
Enter the first number:
<input type="text" name="t1"/>
<select name="op">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
Enter the second number
<input type="text" name="t2"/>
<input type="submit" value="submit"/>
</form>
</body>
</html>

Calci.java:
package p1;
importjava.io.IOException;
importjava.io.PrintWriter;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
/**
*
* @author Administrator
*/

3|Page
public class calci extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throwsServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
int n1,n2;
n1=Integer.parseInt(request.getParameter("t1"));
n2=Integer.parseInt(request.getParameter("t2"));
String op1=request.getParameter("op");
if(op1.equals("+")) {
out.println("sum is"+(n1+n2)); }
else if(op1.equals("-")) {
out.println("Difference"+(n1-n2)); }
else if(op1.equals("*")) {
out.println("Product is"+(n1*n2)); }
else if(op1.equals("/")) {
out.println("Division is"+(n1/n2)); }
try {
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet calci</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet calci at " + request.getContextPath () + "</h1>");
out.println("</body>");
out.println("</html>");
} finally {
out.close(); }
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left
to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throwsServletException, IOException {

4|Page
processRequest(request, response); }
/**
* Handles the HTTP <code>POST</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throwsServletException, IOException {
processRequest(request, response);
} }

Output:

5|Page
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”.

Index.html:
<!DOCTYPE html>
<html>
<head>
<title>Servlet login page</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<form action="LoginServlet" method="get" >
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 p1;
import java.io.*;
import javax.servlet.ServletException;
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><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>");
}
out.println("</body></html>");
}
}

6|Page
Output:

7|Page
8|Page
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:
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="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 p1;
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)
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/login","root","aarti");
PreparedStatementpst = con.prepareStatement("insert into user values(?,?,?,?)");
pst.setString(1,id);
pst.setString(2,ps);
pst.setString(3,em);
pst.setString(4,co);

9|Page
int row = pst.executeUpdate();
out.println("<h1>"+row+ " Inserted Succesfullyyyyy"); }
catch(Exception e) {
out.println(e); }
} }

Output:

10 | P a g e
d) Servlet Program to find the factorial of n.

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>
<form method ="get" action="fact">
Enter the number <input type="text" name="t1"/>
<input type="submit" value="submit"/>
</form>
</body>
</html>

fact.java:
package p1;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author Administrator
*/
public class fact extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
int n,f=1;
n=Integer.parseInt(request.getParameter("t1"));
while(n>=1)
{
f=f*n;
n=n-1;

11 | P a g e
}
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet fact</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet fact at " + request.getContextPath() + "</h1>");
out.println("factorial is"+f);
out.println("</body>");
out.println("</html>");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left
to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/

12 | P a g e
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}

Output:

13 | P a g e
Practical No. 2 Implement the following Servlet applications with Cookies and Sessions.

a) Using Request Dispatcher Interface create a Servlet which will validate the password entered
by the user, if the user has entered "Servlet" as password, then he will be forwarded to
Welcome Servlet else the user will stay on the index.html page and an error message will be
displayed

Index.jsp:
<html>
<head>
<title>login form</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="servlet1" method="post">
Enter Username:<input type="text" name="uname"/>
Enter Password:<input type="password" name="pwd"/>
<input type="submit" value="Log in"/>
</form>
</body>
</html>

Servlet1.java:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author Vinay Kumar
*/
public class servlet1 extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {

14 | P a g e
/* TODO output your page here. You may use following sample code. */
String pwd=request.getParameter("pwd");
String name=request.getParameter("uname");
if(pwd.equals("servlet")&&name.equals("vinay"))
{
RequestDispatcher rd=request.getRequestDispatcher("servlet2");
rd.forward(request, response);
}
else
{
out.println("Incorrect Username or Password!!!");
RequestDispatcher rd=request.getRequestDispatcher("index.html");
rd.include(request,response);
}
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left
to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description

15 | P a g e
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}

Servlet2.java:
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
/**
*
* @author Vinay Kumar
*/
public class servlet2 extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
String n=request.getParameter("uname");
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet servlet2</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Welcome "+n+"</h1>");
out.println("<h3>You are successfully logged-in<h3>");
out.println("</body>");
out.println("</html>");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left
to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request

16 | P a g e
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}

17 | P a g e
Output:

b) Create a servlet that uses Cookies to store the number of times a user has visited servlet

18 | P a g e
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>

Page1.java:
package p1;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Cookie;
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);
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 p1;
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();

19 | P a g e
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>");
out.println("<h1><a href=Page5 >Click to visit Page 5 </a></h1>");
out.println("</body>");
out.println("</html>");
}
}
}

Page3.java:
package p1;
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class Page3 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

20 | P a g e
{
out.println(ck[i].getName()+ " = "+ck[i].getValue());
}
out.println("<h1><a href=Page3 >Click to visit Page 2 </a></h1>");
out.println("<h1><a href=Page4 >Click to visit Page 4 </a></h1>");
out.println("<h1><a href=Page5 >Click to visit Page 5 </a></h1>");
out.println("</body>");
out.println("</html>");
}
}
}

Page4.java:
package p1;
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class Page4 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 2 </a></h1>");
out.println("<h1><a href=Page4 >Click to visit Page 3 </a></h1>");
out.println("<h1><a href=Page5 >Click to visit Page 5 </a></h1>");
out.println("</body>");
out.println("</html>");
}
}
}

21 | P a g e
Page5.java:
package p1;
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class Page5 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 2 </a></h1>");
out.println("<h1><a href=Page4 >Click to visit Page 3 </a></h1>");
out.println("<h1><a href=Page5 >Click to visit Page 4 </a></h1>");
out.println("</body>");
out.println("</html>");
}
}
}

Output:

22 | P a g e
23 | P a g e
24 | P a g e
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.

Index.html:
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="Page1" method="get" >
Enter User ID <input type="text" name="txtName"><br>
<input type="reset" ><input type="submit" >
</form>
</body>
</html>

Page1.java:
package p1;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class 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>");
HttpSessionhs = request.getSession(true);
if(hs.isNew()){
out.println("<body bgcolor=yellow>");
String name = request.getParameter("txtName");
hs.setAttribute("uname", name);
hs.setAttribute("visit", "1");
out.println("<h1>Welcome First Time</h1>");
}
else{

25 | P a g e
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 p1;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class 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>");
HttpSessionhs = request.getSession(false);
out.println("<h1>Welcome Again on Page No. 2</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=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>");
}
}

26 | P a g e
Page3.java:
package p1;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class Page3 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>");
HttpSessionhs = request.getSession(false);
out.println("<h1>Welcome Again on Page No. 2</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=Page1>Click for Page 1 </a></h1>");
out.println("<h1><a href=Page3>Click for Page 2 </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>");
}
}

Page4.java:
package p1;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class Page4 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>");
HttpSessionhs = request.getSession(false);
out.println("<h1>Welcome Again on Page No. 2</h1>");

27 | P a g e
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=Page1>Click for Page 1 </a></h1>");
out.println("<h1><a href=Page3>Click for Page 2 </a></h1>");
out.println("<h1><a href=Page4>Click for Page 3 </a></h1>");
out.println("<h1><a href=LogoutServlet>Click for Terminate Session </a></h1>");
out.println("</body>");
out.println("</html>");
}
}

LogoutServlet.java:
package p1;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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.HttpSessionhs = request.getSession();
if(hs != null) hs.invalidate();
out.println("<h1>You are Logged out now........</h1>");
out.println("</body>");
out.println("</html>");
}
}

28 | P a g e
29 | P a g e
30 | P a g e
Practical No. 3 Implement the Servlet IO and File applications.

a) Create a Servlet application to upload and download a file.


i. File Uploading.

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>
<form action="upload" method="post" enctype="multipart/form-data">
Select File to Upload:<input type="file" name="file" id="file">
Destination <input type="text" value="d://tmp" name="destination">
<br>
<input type="submit" value="Upload file" name="upload" id="upload">
</form>
</body>
</html>

Upload.java:
package p1;
import java.io.*;
importjavax.servlet.*;
importjavax.servlet.http.*;
import javax.servlet.annotation.MultipartConfig;
/**
*
* @author Administrator
*/
@MultipartConfig
public class upload extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void doPost(HttpServletRequestreq, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String path=req.getParameter("destination");

31 | P a g e
Part filePart=req.getPart("file");
String filename=filePart.getSubmittedFileName().toString();
out.print("<br><br><hr> file name: "+filename);
OutputStreamos=null;
InputStream is=null;
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:

32 | P a g e
ii. FileDownloading.
Index.html:
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h1>File Download Application</h1>
Click <a href="DownloadServlet?filename=b.txt">Sample Chapter</a>
<br/><br/>
Click <a href="DownloadServlet?filename=c.txt">Table Of Contents</a>
</body>
</html>

Download servlet:
package p1;
import java.io.*;
importjavax.servlet.*;
importjavax.servlet.http.*;
/**
*
* @author Administrator
*/
public class DownloadServlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(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);

33 | P a g e
//ServletOutputStream out = response.getOutputStream(); // any of the two works
PrintWriter out=response.getWriter();
response.setHeader("Content-Disposition","attachment; filename=\"" + filename + "\""); //
inti;
while ((i=is.read()) != -1) {
out.write(i);
}
is.close();
out.close();
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign
on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold> }

34 | P a g e
Output:
Now we download the file b.txt

Now the file is downloaded

35 | P a g e
b) Develop Simple Servlet Question Answer Application using Database.

Mysql Database Queries:

mysql> use register;


Database changed
mysql> show tables;
+--------------------+
| Tables_in_register |
+--------------------+
| test |
+--------------------+
1 row in set (0.03 sec)
mysql> use register;
Database changed
+--------------------+
| test |
+--------------------+
1 row in set (0.00 sec)
mysql> desc test;
+-------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| ques | varchar(100) | YES | | NULL | |
| op1 | varchar(20) | YES | | NULL | |
| op2 | varchar(20) | YES | | NULL | |
| op3 | varchar(20) | YES | | NULL | |
| op4 | varchar(20) | YES | | NULL | |
| ans | varchar(30) | YES | | NULL | |
+-------+--------------+------+-----+---------+-------+
6 rows in set (0.03 sec)
mysql> insert into test values('sum of 2 +3','3','3','2','5','5');
Query OK, 1 row affected (0.06 sec)
mysql> insert into test values('4 divide by 2','2','3','3','5','2');
Query OK, 1 row affected (0.04 sec)
mysql> select * from test;
+---------------+------+------+------+------+------+
| ques | op1 | op2 | op3 | op4 | ans |
+---------------+------+------+------+------+------+
| sum of 2 +3 | 3 | 3 | 2 | 5 | 5 |
| 4 divide by 2 | 2 | 3 | 3 | 5 | 2 |
+---------------+------+------+------+------+------+
2 rows in set (0.00 sec)

36 | P a g e
Index.jsp:
<%--
Document : index
Created on : 14 Oct, 2018, 8:20:43 AM
Author : Administrator
--%>
<%@page import="java.sql.*"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<form method="post" action="result.jsp">
<table>
<%
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/register","root","sices");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("Select * from test");
int i=1;
while(rs.next()){
%>
<tr><td><%=i%></td><td><%=rs.getString("ques")%></td><td><input type="radio"
value="<%=rs.getString("op1")%>"
name="radio<%=i%>"/><%=rs.getString("op1")%></td><td><input type="radio"
value="<%=rs.getString("op2")%>"
name="radio<%=i%>"/><%=rs.getString("op2")%></td><td><input type="radio"
value="<%=rs.getString("op3")%>"
name="radio<%=i%>"/><%=rs.getString("op3")%></td><td><input type="radio"
value="<%=rs.getString("op4")%>" name="radio<%=i%>"/><%=rs.getString("op4")%></td></tr>
<%
i++;
}
%>
<tr><td><input type="submit" value="submit"></td></tr>
</table>
</form>
</html>

result.jsp:
<%--
Document : result
Created on : 14 Oct, 2018, 8:25:48 AM
Author : Administrator
--%>
<%@page import="java.sql.*"%>
<%
String st[]=new String[10];
for(int i=0;i<st.length;i++){
int j=i+1;

37 | P a g e
st[i]=request.getParameter("radio"+j);
System.out.println(st[i]);
}
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/register","root",
"sices");
Statement stmt=conn.createStatement();
ResultSet rs=stmt.executeQuery("Select ans from test");
String ans="";
while(rs.next()){
ans+=rs.getString("ans")+" ";
}
int count=0;
String answers[]=ans.split(" ");
for(int i=0;i<answers.length;i++){
if(st[i].equals(answers[i])){
count++;
}
}
out.println("Your "+count+" answers are correct");
%>

Output:

38 | P a g e
c) Develop Simple Servlet Question Answer Application using JSP and Sevlet.

index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>QUIZ</h1>
<form method="get" action="quiz">
Q.1>Which of the following is the default layout for Frame?<br/>
<input type="radio" name="q1" value="FlowLayout">FlowLayout<br/>
<input type="radio" name="q1" value="BorderLayout">BorderLayout<br/>
<input type="radio" name="q1" value="GridLayout">GridLayout<br/>
<input type="radio" name="q1" value="GridbackLayout">GridbackLayout<br/>
Q.2>Which one is the first JDBC driver?<br/>
<input type="radio" name="q2" value="Native API Driver">Native API Driver<br/>
<input type="radio" name="q2" value="Network Protocol Driver">Network Protocol Driver<br/>
<input type="radio" name="q2" value="Native Protocol Java Driver">Native Protocol Java Driver<br/>
<input type="radio" name="q2" value="JDBC-ODBC Bridge">JDBC-ODBC Bridge<br/>
Q.1>Which is an independent platform language?<br/>
<input type="radio" name="q3" value="C++">C++<br/>
<input type="radio" name="q3" value="Java">Java<br/>
<input type="radio" name="q3" value="C">C<br/>
<input type="radio" name="q3" value="Pearl">Pearl<br/>
Q.1>Which of the following is not supported in applet?<br/>
<input type="radio" name="q4" value="RadioButton">RadioButton<br/>
<input type="radio" name="q4" value="CheckBox">CheckBox<br/>
<input type="radio" name="q4" value="TextField">TextField<br/>
<input type="radio" name="q4" value="Choice">Choice<br/>
submit here<input type="submit" value="check"/>
</form>
</body>
</html>

quiz.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class quiz extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)

39 | P a g e
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
int correct=0;
int incorrect=0;
String a1=request.getParameter("q1");
String a2=request.getParameter("q2");
String a3=request.getParameter("q3");
try {
if(a1.equals("BorderLayout"))
{
correct++;
}
else
{
incorrect++;
}
if(a1.equals("JDBC-ODBC Bridge"))
{
correct++;
}
else
{
incorrect++;
}
if(a1.equals("Java"))
{
correct++;
}
else
{
incorrect++;
}
if(a1.equals("RadioButton"))
{
correct++;
}
else
{
incorrect++;
}
out.println("you scored ");
out.println("correct answer :"+correct);
out.println("incorrect answer ");
out.println("incorrect answer :"+incorrect);
}
finally {
out.close();

40 | P a g e
}
}
}

OUTPUT:

41 | P a g e
Practical No. 4 Implement the following JSP applications.

a) Develop a simple JSP application to display values obtained from the use of intrinsic objects of
various types.

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>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()) %>
</body>
</html>

Output:

42 | P a g e
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>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">
</form>
</body>
</html>

validate.jsp
<%@page import="mypack.CheckerBean" 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>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"/>
<% }

43 | P a g e
else {%>
<jsp:include page="index.html"/>
<%}%>
<%=obj.getError() %>
</body>
</html>

CheckerBean.java
package mypack;
/**
*
* @author sices23
*/
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){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;
}
}

44 | P a g e
Output:

45 | P a g e
c) Create a registration and login JSP application to register and authenticate the user based on
username and password using JDBC

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>ENTER YOUR LOGIN DETAILS </h1>
<form action="login.jsp" method="get">
<table>
<tr>
<td>Enter your username</td>
<td><input type="text" name="t1"/></td>
</tr>
<tr>
<td>Enter your Password</td>
<td><input type="text" name="t2"/></td>
</tr>
<tr>
<input type="submit" value="submit"/>
</tr>
</table>
</form>
</body>
</html>

Login.jsp:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%@page import="java.sql.*"%>
<%@page import="javax.sql.*"%>
<%
String uname=request.getParameter("t1");
String upass=request.getParameter("t2");
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/college","root","sices");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from student where name='"+uname+"'");
if(rs.next()) {
if(rs.getString(3).equals(upass));
response.sendRedirect("welcome.jsp");
out.println("welocme");

46 | P a g e
}
else {
response.sendRedirect("error.jsp");
}
}
catch(Exception e)
{}
%>

Welcome.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>Welcome to your home page</h1>
</body>
</html>

Error.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> please provide correct username and password</h1>
</body>
</html>

Output:

47 | P a g e
48 | P a g e
d) Create Database program using Servlets.
i. Creating tables and inserting values.

Data.java:
package data;
import java.sql.*;
public class Data
{
public static void main(String[] args)
{
Connection con;
Statement st;
try
{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver Registered Successfully.");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/college","root","sices");
System.out.println("Database connected Successfully.");
st=con.createStatement();
//st.executeUpdate("Create table emp(eid varchar(6),ename varchar(10),esal int)");
st.executeUpdate("insert into emp(eid,ename,esal)values('e001','gmail.com',2000)");
System.out.println("Data inserted successfully.");
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

Output:

49 | P a g e
ii. Update tables using addBatch()

Batchupdate.java
package batchupdate;
import java.sql.*;
public class Batchupdate
{
public static void main(String[] args)
{
Connection con;
Statement st;
try
{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver Registered Successfully.");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/college","root","sices");
System.out.println("Database connected Successfully.");
st=con.createStatement();
//st.executeUpdate("Create table course(cid varchar(6),cname varchar(10),cfees int)");
//st.executeUpdate("insert into course(cid,cname,cfees)values('c001','gmail.com',2000)");
st.addBatch("insert into employee(eid,ename,esal)values('e002','pranu.com',4000)");
st.addBatch("insert into employee(eid,ename,esal)values('e003','swati.com',5000)");
st.addBatch("insert into employee(eid,ename,esal)values('e004','priya.com',3000)");
st.addBatch("insert into employee(eid,ename,esal)values('e005','kala.com',2000)");
//st.addBatch("insert into course(cid,cname,cfees)values('004','swati',25000)");
System.out.println("Data inserted successfully");
int[] count=st.executeBatch();
}
catch(Exception e)
{
e.printStackTrace(); }
}
}

OUTPUT:

50 | P a g e
iii. Retriving Results using ResultSet

Resultset.java
package resultset;
import java.sql.*;
public class Resultset
{
public static void main(String[] args)
{
Connection con;
Statement st;
ResultSet rs;
try
{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver Registered Successfully.");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/college","root","sices");
System.out.println("Database connected Successfully.");
st=con.createStatement();
rs=st.executeQuery("select * from employee");
System.out.println("Results Retrived Successfully");
while(rs.next())
{
System.out.println(rs.getString(1)+"\t"+rs.getString(2)+"\t"+rs.getInt(3));
System.out.println("");
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

Output:

51 | P a g e
Practical No. 5 Implement the following JSP JSTL and EL Applications.

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.

Index.html
<!DOCTYPE html>
<html>
<body>
<form action="UpdateEmp.jsp" >
Enter Employee Number<input type="text" name="txtEno" ><br>
Enter Name<input type="text" name="txtName" ><br>
Enter age<input type="text" name="txtAge" ><br>
Enter Salary<input type="text" name="txtSal" ><br>
<input type="reset" ><input type="submit">
</form>
</body>
</html>

UpdateEmp.jsp
<%@page contentType="text/html" import="java.sql.*" %>
<html>
<body>
<h1>Employee Record Update</h1>
<%
String eno=request.getParameter("txtEno");
String name=request.getParameter("txtName");
String age = request.getParameter("txtAge");
String sal = request.getParameter("txtSal");
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/empdb","root","sices");
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>

52 | P a g e
Output:

53 | P a g e
b) Create a JSP page to demonstrate the use of Expression language.

index.jsp:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%
application.setAttribute("author","vaishali Bhusare");
session.setAttribute("country","india");
%>
<!DOCTYPE html>
<html>
<head>
<title>Expression language example2</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="show.jsp">
User First Name:<input type="text" name="ufname"/><br>
User Last Name:<input type="text" name="ulname"/><br>
<input type="submit" value="Check EL Use!!"/>
</form>
</body>
</html>

show.jsp:
<%@page contentType="text/html" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Display Page</title>
</head>
<body bgcolor="${pageScope.colour}">
<b>Welcome ${param.ufname}${param.ulname}</b><br>
Below we are accessing Application object:
<p>
Author name:<b>${applicationScope.author}</b>
</p>
Below we are session object:
<p>
Author country: <b> ${sessionScope.country}</b>
</p>
Below we are showing some basic comparisons using EL:
<p>
Is 1 less then 2? ${1<2} <br>
Dose 5 equal 5? ${5==5} <br>
Is 6 greater then 7? ${6 gt 7} <br>
</p>

54 | P a g e
Below we are session object:
<p>Now for some maths:<br>
6+7=${6+7}<br>
8*9=${8*9}<br>
<hr>you appear to be using the following browser:</hr>
${header["user-agent"]}
</p>
</body>
</html>

Output:

55 | P a g e
c) Create a JSP application to demonstrate the use of JSTL. For database connectivity

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>Choose Option</h1>
<a href="insert.jsp">Insert Record</a><p></p>
<a href="display.jsp">Display Record</a>
</body>
</html>

Insert.jsp:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form action="insertdb.jsp" method="post">
<table border="0" cellspacing="2" cellpadding="5">
<thead>
<tr>
<th colspan="2">Purchase Product</th>
</tr>
</thead>
<tbody>
<tr>
<td><label>Product Name</label></td>
<td><input type="text" name="pname"/></td>
</tr>
<tr>
<td><label>Quantity</label></td>
<td><input type="text" name="qty"/></td>
</tr>
<tr>
<td><input type="submit" value="Save" /></td>
<td><input type="reset" value="reset"/></td>
</tr>
</tbody>

56 | P a g e
</table>
</form>
<font color="red"><c:if test="${not empty param.errMsg}">
<c:out value="${param.errMsg}" />
<a href="index.jsp">Go Back</a>
</c:if></font>
<font color="green"><c:if test="${not empty param.susMsg}">
<c:out value="${param.susMsg}" />
<a href="index.jsp">Go Back</a>
</c:if></font>
</body>
</html>

Insertdb.jsp:
<%@ page import="java.io.*,java.util.*,java.sql.*"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<html>
<head>
<title>JINSERT Operation</title>
</head>
<body>
<c:if test="${ empty param.pname or empty param.qty}">
<c:redirect url="insert.jsp" >
<c:param name="errMsg" value="Please Enter Product and Quantity" />
</c:redirect>
</c:if>
<sql:setDataSource var="dbsource" driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/loginjdbc"
user="root" password="sices"/>
<sql:update dataSource="${dbsource}" var="result">
INSERT INTO product(pname, quantity) VALUES (?,?);
<sql:param value="${param.pname}" />
<sql:param value="${param.qty}" />
</sql:update>
<c:if test="${result>=1}">
<font size="5" color='green'> Congratulations ! Data inserted
successfully.</font>
<c:redirect url="insert.jsp" >
<c:param name="susMsg" value="Congratulations ! Data inserted
successfully." />
</c:redirect>
</c:if>
</body>
</html>

Display.jsp:
<%@ page import="java.io.*,java.util.*,java.sql.*"%>

57 | P a g e
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<html>
<head>
<title>SELECT Operation</title>
<script>
function confirmGo(m,u) {
if ( confirm(m) ) {
window.location = u;
}
}
</script>
</head>
<body>
<sql:setDataSource var="dbsource" driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/loginjdbc"
user="root" password="sices"/>
<sql:query dataSource="${dbsource}" var="result">
SELECT * from product;
</sql:query>
<center>
<form>
<table border="1" width="40%">
<caption>Product List</caption>
<tr>
<th>Product ID</th>
<th>Product Name</th>
<th>Quantity</th>
<th colspan="2">Action</th>
</tr>
<c:forEach var="row" items="${result.rows}">
<tr>
<td><c:out value="${row.id}"/></td>
<td><c:out value="${row.pname}"/></td>
<td><c:out value="${row.quantity}"/></td>
<td><a href="update.jsp?id=<c:out value="${row.id}"/>">Update</a></td>
<td><a href="javascript:confirmGo('Sure to delete this record?','deletedb.jsp?id=<c:out
value="${row.id}"/>')">Delete</a></td>
</tr>
</c:forEach>
</table>
</form>
<a href="index.jsp">Go Home</a>
</center>
</body>
</html>

58 | P a g e
Output:

59 | P a g e
60 | P a g e
d) Create a JSP application to demonstrate the use of JSTL.

Index.html:
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>Page Data Example</title>
</head>
<body bgcolor="#585858">
<form method="POST" action="show.jsp">
<table bgcolor="#D8D8D8">
<tr>
<td width="33%">
<b>First Name</b>
</td>
<td width="73%">
<input type="text" name="first" size="40" />
</td>
</tr>
<tr>
<td width="33%">
<b>Last Name</b>
</td>
<td width="73%">
<input type="text" name="last" size="40" />
</td>
</tr>
<tr>
<td width="33%">
<b>Qualification</b>
</td>
<td width="73%">
<SELECT NAME="gourl">
<OPTION VALUE="">Select..
<OPTION VALUE="mca">MCA
<OPTION VALUE="btech">B.Tech
<OPTION VALUE="be" >BE
</SELECT>
</td>
</tr>
<tr>
<td width="33%">
<b>Address</b>

61 | P a g e
</td>
<td width="73%">
<TEXTAREA NAME="address" ROWS=3 COLS=30></TEXTAREA>
</td>
</tr>
<tr>
<td width="33%">
<b>City</b>
</td>
<td width="73%">
<input type="text" name="city" size="20" />
</td>
</tr>
<tr>
<td width="33%">
<b>State</b>
</td>
<td width="73%">
<input type="text" name="state" size="20" />
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Submit" name="action"/>
<input type="reset" value="Reset" name="action" />
</td>
</tr>

</table>
</form>
</body>
</html>

Show.jsp:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:if test="${pageContext.request.method=='POST'}">
<c:choose>
<c:when test="${param.add!=null}">
<c:if test="${list!=null}">
<c:set var="list" value="${list}," scope="session" />
</c:if>
<c:set var="list" value="${list}${param.item}"
scope="session" />
</c:when>
<c:when test="${param.remove!=null}">
<c:set var="list2" value="" />
<c:forEach var="item" items="${list}">
<c:if test="${item!=param.item}">

62 | P a g e
<c:if test="${list2!=''}">
<c:set var="list2" value="${list2}," />
</c:if>
<c:set var="list2" value="${list2}${item}" />
</c:if>
</c:forEach>
<c:set var="list" value="${list2}" scope="session" />
<c:remove var="list2" />
</c:when>
</c:choose>
</c:if>

<html>
<head>
<title>Updatable Collections</title>
</head>
<body>
<table border="0">
<form method="post">
<tr bgcolor="blue">
<td colspan="2">
<font color="white">Add and remove application</font>
</td>
</tr>
<tr>
<td valign="top">
<select NAME="choice" SIZE="5">
<c:forEach var="item" items="${list}">
<option>
<c:out value="${item}" />
</option>
</c:forEach>
</select>
</td>
<td valign="top">Enter a item to add or remove.
<br />
<input type="text" name="item" size="20" />
<br />
<input type="submit" name="add" value="Add" />
<input type="submit" name="remove" value="Remove" />
</td>
</tr>
</form>
</table>
</body>
</html>

63 | P a g e
Output:

64 | P a g e
Practical No. 6 Implement the following EJB Applications.

a) Create a currency converter application using EJB.

Index.html:
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div>
<form method="post" action="convertCurrencyServlet">
Enter an amount to convert:
Convert:
<input type="text" name="amount"/>
From this currency:<br/>
<select name="From" size="3" >
<option value="USD">America (United States),Dollar
</option>
<option value="INR">INDIA,Rupee (INR)
</option>
</select><br/>
To this Currency <br/>
<select name="To" size="3" >
<option value="USD">America (United States),Dollar
</option>
<option value="INR">INDIA,Rupee (INR)
</option>
</select>
<br/>
<input type="submit" value="Submit"/>
</form>
</div>
</body>
</html>

CurrencyConverterBean.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates

65 | P a g e
* and open the template in the editor.
*/
package ejb;
import java.io.*;
import javax.ejb.Stateless;
import java.math.BigDecimal;
importjava.math.*;
/**
*
* @author Administrator
*/
@Stateless
public class CurrencyConverterBean {
private BigDecimal USD=new BigDecimal("0.0229137");
private BigDecimal INR=new BigDecimal("46.589100");
public BigDecimal convert(String from,Stringto,BigDecimal amount){
if(from.equals(to)){
return amount;
}
else
{
BigDecimaltoRate=findRate(to);
BigDecimal result=toRate.multiply(amount);
return result.setScale(2,BigDecimal.ROUND_UP);
}
}
public BigDecimalfindRate(String to){
BigDecimalreturnValue=null;
if(to.equals("INR")){
returnValue =INR;
}
if(to.equals("USD")){
returnValue=USD;
}
return returnValue;
}
}

convertCurrencyServlet.java
package servlet;
importjavax.servlet.*;
importjavax.servlet.http.*;
import java.io.*;
import ejb.CurrencyConverterBean;
import java.math.BigDecimal;
import javax.ejb.EJB;
importjava.math.*;
/**

66 | P a g e
*
* @author Administrator
*/
public class convertCurrencyServlet extends HttpServlet {
CurrencyConverterBeanconverterBean=new CurrencyConverterBean();
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try
{
String amount=request.getParameter("amount");
if(amount !=null &&amount.length()>0)
{
BigDecimal d=new BigDecimal(amount);
BigDecimal
convertedAmount=converterBean.convert(request.getParameter("From"),request.g
etParameter("To"),d);

out.println(amount+""+request.getParameter("From")+"=");
out.println(convertedAmount+""+request.getParameter("To"));
}
} finally {
out.close();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the +
sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)

67 | P a g e
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}

Output:

68 | P a g e
b) Develop a Simple Room Reservation System Application Using EJB.

index.html:
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="RBservlet" method="get" >
Select a room Type
<input type="radio" name="txtType" value="Delux">Delux
<input type="radio" name="txtType" value="Super Delux">Super Delux
<input type="radio" name="txtType" value="Suit">Suit<br>
Enter Your Name<input type="text" name="txtCust" ><br>
Enter Mobile No.<input type="text" name="txtMob" ><br>
<input type="reset" ><input type="submit" value="Book Room">
</form>
</body>
</html>

RBean.java:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package p1;
import javax.ejb.Stateless;
import java.sql.*;
import javax.ejb.Stateless;
/**
*
*
* @author Administrator
*/
@Stateless
public class RBean {
public String roomBook(String rt, String cn, String cm){
String msg="";

69 | P a g e
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/reservation","root","aarti");
String query="select * from book where RoomType=? and status='Not Booked'";
PreparedStatement pst = con.prepareStatement(query);
pst.setString(1,rt);
ResultSet rs= pst.executeQuery();
if(rs.next()){
String rno=rs.getString(1);
PreparedStatement stm1 = con.prepareStatement("update book set cust=? where RoonId=? ");
PreparedStatement stm2 = con.prepareStatement("update book set mob=? where RoonId=? ");
PreparedStatement stm3 = con.prepareStatement("update book set status=? where RoonId=? ");
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 Charges = "+rs.getString(3);
}
else
{
msg = "Room "+rt+ " currently Not available";
}
}catch(Exception e){msg=""+e;}
return msg;
}
}

RBservlet.java:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package p1;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.ejb.EJB;
import p1.*;
public class RBservlet extends HttpServlet {
@EJB RBean obj;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
PrintWriter out=response.getWriter();

70 | P a g e
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);
}
}

Output:

71 | P a g e
72 | P a g e
c) Develop simple shopping cart application using EJB [Stateful Session
Bean].

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/ShoppingCart/ShoppingCart");
} catch (Exception ex) {
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]);
}
}
}
%>
<html>
<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>

73 | P a g e
<form name="frmBooks" method="post">
<table style="background-color: pink; width: 100%; padding: 1px; border-spacing: 1px;">
<tr style="background-color: pink;">
<td style="width: 70%">
<table style="padding: 1px 1px 1px 1px; border-spacing: 1px; border: 2px solid maroon; width: 400px;">
<tr>
<td style="border: 2px solid maroon;">Customer</td>
<td style="border: 2px solid maroon;">
<input type="text" name="txtCustomerName" value=<%=
request.getParameter("txtCustomerName")%> />
</td>
</tr>
<tr style="background-color: maroon;">
<th style="text-align: left; width: 340px; color: white; border: 2px solid maroon;" colspan="2">
<b>Book Titles</b>
</th>
</tr>
<tr>
<td style="border: 2px solid maroon;">
<input type="checkbox" name="chkBook" value="Struts 2.0 For Beginners">
</td>
<td style="width: 340px; border: 2px solid maroon;">Struts 2.0 For Beginners</td>
</tr>
<tr>
<td style="border: 2px solid maroon;">
<input type="checkbox" name="chkBook" value="Oracle 11g For Professionals">
</td>
<td style="width: 340px; border: 2px solid maroon;">Oracle 11g For Professionals</td>
</tr>
<tr>
<td style="border: 2px solid maroon;">
<input type="checkbox" name="chkBook" value="Hibernate 3 For Beginners">
</td>
<td style="width: 340px; border: 2px solid maroon;">Hibernate 3 For Beginners</td>
</tr>
<tr>
<td style="border: 2px solid maroon;">
<input type="checkbox" name="chkBook" value="Java Persistence API In EJB 3 For Beginners">
</td>
<td style="width: 340px; height: 24px; border: 2px solid maroon;">Java Persistence API In EJB 3 For
Beginners</td>
</tr>
<tr>
<td colspan="4" style="border: 2px solid maroon;">
<table style="background-color: pink; text-align: center;">
<tr>
<td style="text-align: center;">
<input type='submit' value='Add To My Basket' name='btnAddBook'>

74 | P a g e
</td>
<td style="text-align: center;">
<input type='submit' value='Remove From My Basket' name='btnRmvBook'>
</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
<td>
<table style="border: 1px solid blue; width: 300px; height: 180px; text-align: right;">
<tr>
<td style="text-align: center; background-color: lightblue; border: 1px solid blue; height:
20px;">Basket</td>
</tr>
<%
if(cart!=null){
List<String> bookList = cart.getContents();
Iterator iterator = bookList.iterator();
while (iterator.hasNext()) {
String title = (String) iterator.next();
%>
<tr>
<td style="text-align: left; background-color: lightblue; border: 1px solid blue;"><%= title %></td>
</tr>
<%
}
}
%>
</table>
</td>
</tr>
</table>
</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;

75 | P a g e
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/Cart", "root", "1234");
} 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) {
System.err.println("Sorry failed to insert values from the database table. " + e.getMessage());
}
}
public void removeBook(String title) {
try {
stmt = conn.createStatement();
query = "DELETE FROM Cart WHERE UserName='" + customerName + "' AND ItemName='" + title
+ "';";
stmt.executeUpdate(query);
} catch(SQLException e) {
System.err.println("Sorry failed to delete values from the database table. " + e.getMessage());
}
}
public List<String> getContents() {
try {
stmt = conn.createStatement();
query = "SELECT * FROM Cart WHERE UserName='" + customerName + "';";
rs = stmt.executeQuery(query);
while(rs.next()) {
contents.add(rs.getString("ItemName"));

76 | P a g e
}
} 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;
}
}

Output:

77 | P a g e
78 | P a g e
Practical No. 7 Implement the following EJB applications with different types of Beans.

a) Develop a simple EJB application to demonstrate Servlet hit count Singleton Session Bean

Index .jsp:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Refresh" content="0;URL=counter">
<title>JSP Page</title>
</head>
<body>
</body>
</html>

Countservlet.java:
package ejb;
import javax.ejb.Singleton;
import javax.ejb.LocalBean;
/**
*
* @author Administrator
*/
@Singleton
@LocalBean
public class countservlet {
private int count;
public synchronized int increment(){
return count++;
}
}

Counter.java:
package ejb;
import java.io.*;
importjavax.servlet.*;
importjavax.servlet.http.*;
importjavax.ejb.*;
import javax.ejb.EJB;
import javax.servlet.annotation.WebServlet;
/**
*
* @author Administrator
*/

public class counter extends HttpServlet {


@EJB

79 | P a g e
countservletcountbean;
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
methods.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("no of times this servlet is accessedd");
out.println(+countbean.increment());
out.close();
}
}

Output:

80 | P a g e
b) Develop simple visitor Statistics application using Message Driven Bean [Stateless Session
Bean].

Index.jsp:
<%@page import="javax.naming.InitialContext, ejb.VisitorStat"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%!
private static VisitorStat visits;
public void jspInit()
{
try {
InitialContext ic = new InitialContext();
visits = (VisitorStat) ic.lookup("java:global/VisitorStatistics/VisitorStat");
} catch (Exception ex) {
System.out.println("Could not create timer bean." + ex.getMessage());
}
}
%>
<%
visits.addVisitor(request.getRemoteAddr());
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Welcome To Sharanam's Home Page</title>
</head>
<body style="background-color: pink;">
<h1 style="text-align: center;">Welcome To Sharanam Shah's home page</h1>
</body>
</html>

Visitorstat.java:
package ejb;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.ejb.Stateless;
@Stateless
public class VisitorStat {
private Connection conn = null;
private ResultSet rs;
private Statement stmt = null;
private String query = null;

81 | P a g e
@PostConstruct
public void connect()
{
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost/visitorstat", "root",
"sices");
System.out.println("Database connection established successfully.");
} catch(ClassNotFoundException | InstantiationException | IllegalAccessException |
SQLException e) {
System.err.println("Sorry failed to connect to the Database.");
}
}
@PreDestroy
public void disconnect() {
try {
conn.close();
System.out.println("Database connection closed successfully.");
} catch(SQLException e) {
System.err.println("Cannot close the database connection: " + e.getMessage());
}
}
public void addVisitor(String host)
{
try {
stmt = conn.createStatement();
query = "INSERT INTO UserStat (hostname, visits) VALUES('" + host + "','1')";
stmt.executeUpdate(query);
} catch(SQLException e) {
try {
stmt = conn.createStatement();
query = "UPDATE UserStat SET visits = visits + 1 WHERE hostname = '" + host +
"'";
stmt.executeUpdate(query);
} catch(SQLException ex) {
System.err.println("Cannot update: " + ex.getMessage()); }
}
}
}

Mysql database Queries:


mysql> create database visitorstat;
Query OK, 1 row affected (0.11 sec)
mysql> use visitorstat;
Database changed
mysql> create table UserStat(hostname varchar(30) primary key,visits int);
Query OK, 0 rows affected (0.30 sec)

82 | P a g e
Output:

83 | P a g e
Practical No. 8 Implement the following JPA applications.

a) Develop a Guest Book application JPA.

Index.jsp
<%--
Document : index
Created on : Aug 14, 2018, 8:48:21 AM
Author : Administrator
--%>
<%@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>
<form action="feedback.jsp" method="post">
Enter User Name <input type="text" name="t1"><br>
Enter ur message <input type="text" name="t2"><br>
<input type="submit" name="btnsubmit" value="Submit">
</form>
</body>
</html>

Feedback.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
packagemyapp;
importjavax.persistence.*;
/**
*
* @author Administrator
*/
@Entity
@Table(name="guestbook")
public class feedback {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id",unique=true,updatable=false)
private Integer vno;
@Column(name="vname")
private String name;
@Column(name="message")
private String nmessage;

84 | P a g e
public feedback()
{ }
/*public feedback(Integer vno,Stringvname,String message)
{
this.vno=vno;
this.vname=vname;
this.message=message;
}
*/
public Integer getVno(){
returnvno;
}
public void setVno(Integer vno){
this.vno=vno;
}
public String getname(){
return name;
}
public void setVname(String name){
this.name=name;
}
public String getnMessage(){
returnnmessage;
}
public void setMessage(String nmessage){
this.nmessage=nmessage;
}
}

feedback.jsp
<%--
Document : feedback
Created on : Aug 14, 2018, 9:08:44 AM
Author : Administrator
--%>
<%@page import="java.util.*,myapp.*,
javax.persistence.*" contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBIC*-//>
<%!
privateEntityManagerFactoryemf;
privateEntityManagerem;
privateEntityTransactiontx;
List<feedback> bean;
%>
<%
emf=Persistence.createEntityManagerFactory("jpa1PU");
em=emf.createEntityManager();
//String b1=request.getParameter("btnsubmit");

85 | P a g e
//if(b1!=null&&("Submit").equals(b1))
try
{
String n=request.getParameter("t1");
String m=request.getParameter("t2");
feedback feed=new feedback();
feed.setVname(n);
feed.setMessage(m);
tx=em.getTransaction();
tx.begin();
em.persist(feed);
tx.commit();
out.println("record addedd");
}catch(RuntimeException e1)
{
if(tx!=null)tx.rollback();
throw e1;
}
finally {}
%>

<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>

Persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="guestjpaPU" transaction-type="RESOURCE_LOCAL">
<non-jta-data-source>jdbc/guestbook</non-jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties/>
</persistence-unit>
</persistence>

86 | P a g e
Output:

87 | P a g e
Practical No. 9 Implement the following JPA applications with ORM and Hibernate.

a) Develop a Hibernate application to store Feedback of Website Visitor in MySQL Database.

feedback.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC '-//Hibernate/Hibernate Mapping DTD 3.0//EN'
'http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd'>
<hibernate-mapping>
<class name="myapp.mybean" table="feedback" catalog="college" >
<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="message" type="string">
<column name="message" length="100" />
</property>
</class>
</hibernate-mapping>

hibernate.cfg.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/college</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">sices</property>
<mapping resource="feedback.xml"/>
</session-factory>
</hibernate-configuration>

index .html:
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form action="feedback.jsp" method="post">
Enter User Name <input type="text" name="t1"><br>

88 | P a g e
Enter ur message <input type="text" name="t2"><br>
<input type="submit">
</form>
</body>
</html>

mybean.java:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
packagemyapp;
importjava.io.Serializable;
/**
*
* @author Administrator
*/
public class mybean implements Serializable {
private String name;
private String message;
private Integer id;
public mybean()
{}
public mybean(String name,String message)
{
this.name=name;
this.message=message;
}
public void setName(String name)
{
this.name=name;
}
public String getName()
{
return name;
}
public void setMessage(String message)
{
this.message=message;
}
public String getMessage()
{
return message;
}
public void setId(Integer id)
{
this.id=id;
}

89 | P a g e
public Integer getId()
{
return id;
}
}

feedback .jsp:
<%--
Document : feedback
Created on : Aug 13, 2018, 10:43:49 AM
Author : Administrator
--%>
<%@page import="org.hibernate.*,org.hibernate.cfg.*,myapp.mybean" %>
<!DOCTYPE html>
<%! SessionFactorysf;Session s;%>
<%
String name=request.getParameter("t1");
String message=request.getParameter("t2");
sf=new Configuration().configure().buildSessionFactory();
s=sf.openSession();
Transaction t=null;
mybean b1=new mybean();
try
{
t=s.beginTransaction();
b1.setName(name);
b1.setMessage(message);
s.save(b1);
t.commit();
out.println("record added");
}
catch(RuntimeException e)
{
if(t!=null)
t.rollback();
out.println(e);
}
finally {}
%>

90 | P a g e
Output:

91 | P a g e
b) Develop a Hibernate application to store and retrieve employee details in MySQL Database.

mybean.java:
packagemyapp;
importjava.io.Serializable;
/**
*
* @author Administrator
*/
public class mybean implements Serializable {
private String name;
private String message;
private Integer id;
public mybean()
{}
public mybean(String name,String message) {
this.name=name;
this.message=message;
}
public void setName(String name) {
this.name=name;
}
public String getName()
{
return name;
}
public void setMessage(String message)
{
this.message=message;
}
public String getMessage()
{
return message;
}
public void setId(Integer id)
{
this.id=id;
}
public Integer getId()
{
return id;
}
}

feedback.jsp:
<%@page import="org.hibernate.*,org.hibernate.cfg.*,java.lang.*,java.util.*,myapp.*"
language="java"%>
<!DOCTYPE html>

92 | P a g e
<%! SessionFactorysf;Session s;
List<mybean>b;
%>
<%
String name=request.getParameter("t1");
String message=request.getParameter("t2");
sf=new Configuration().configure().buildSessionFactory();
s=sf.openSession();
Transaction t=null;
mybean b1=new mybean();
try
{
t=s.beginTransaction();
b1.setName(name);
b1.setMessage(message);
s.save(b1);
t.commit();
out.println("record added");
}
catch(RuntimeException e)
{
if(t!=null)
t.rollback();
out.println(e);
}
finally {}
try
{
s.beginTransaction();
b= s.createQuery("from mybean ").list();
}
catch(RuntimeException e)
{
throw e;
}
s.close();
%>
<html>
<body bgcolor="pink">
<%
Iterator it=b.iterator();
while(it.hasNext())
{
mybeanobj=(mybean)it.next();
%>
<table>
<tr>
<td>

93 | P a g e
<%=obj.getId()%>
<%=obj.getName()%>
<%=obj.getMessage()%><br/>
<%
}
%>
</td>
</tr>
</table>
</body>
</html>

Output:

94 | P a g e

You might also like