You are on page 1of 254

Practical 1A

Aim: Create a Simple calculator application using Servlet

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="Calcservlet" method="GET">

<h2>Enter number 1:</h2>

<input type="text" name="t1"><br>

<h2>Enter number 2:</h2>

<input type="text" name="t2"><br>

<h3>Select operation:</h3>

<input type="radio" name="operation" value="add" checked>Addition<br>

<input type="radio" name="operation" value="sub"> Subtraction<br>

<input type="radio" name="operation" value="mul"> Multiplication<br>

<input type="radio" name="operation" value="div"> Division<br>

<input type="submit">

</form>
</body>

</html>

Calcservlet.java

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns = {"/calcservlet"})

public class calcservlet extends HttpServlet

protected void processRequest(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html;charset=UTF-8");

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 calcservlet</title>");
out.println("</head>");

out.println("<body>");

int n1=Integer.parseInt(request.getParameter("t1"));

int n2=Integer.parseInt(request.getParameter("t2"));

String o=request.getParameter("operation");

if(o.equals("add"))

int a=n1+n2;

out.println("<h1>Addition is:"+a+"</h1>");

if(o.equals("sub"))

int a=n1-n2;

out.println("<h1>Subtraction is:"+a+"</h1>");

if(o.equals("mul"))

int a=n1*n2;

out.println("<h1>multiplication is:"+a+"</h1>");

if(o.equals("div"))

{
int a=n1/n2;

out.println("<h1>division is:"+a+"</h1>");

out.println("</body>");

out.println("</html>");

}
Practical 1B

2) Create aServlet for a login page.If the username and password are correct then it says
message “Hello <username> else a message “login failed”.

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="loginservlet" method="GET">

<h2>Enter user id:</h2>

<input type="text" name="t1"><br>

<h2>Enter password:</h2>

<input type="text" name="t2"><br><br>

<input type="submit" value="login" />

</form>

</body>

</html>

Loginservlet.java

import java.io.IOException;

import java.io.PrintWriter;
import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

/**

* @author admin

*/

@WebServlet(urlPatterns = {"/loginservlet"})

public class loginservlet 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()) {

/* 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 loginservlet</title>");

out.println("</head>");

out.println("<body>");

out.println("<h1>Servlet loginservlet at " + request.getContextPath() + "</h1>");

String uid=request.getParameter("t1");

String pwd=request.getParameter("t2");

if(uid.equals("ram") && (pwd.equals("1234")))

out.println("Hello "+uid);

else

out.println("Login fail ");

out.println("</body>");

out.println("</html>");

}
Practical 1C

Aim: 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.

create database mydb1;

show databases;

use mydb1;

CREATE TABLE emp (uid CHAR(25),pwd CHAR(25), email CHAR(25), country


CHAR(25));

Select * from emp;

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="Registerservlet">
<h2>Enter user id:</h2>
<input type="text" name="t1"><br>
<h2>Enter password:</h2>
<input type="text" name="t2"><br><br>
<h2>Enter email:</h2>
<input type="text" name="t3">
<h2>Enter country:</h2>
<input type="text" name="t4">
<input type="submit" value="submit" />
</form>
</body>
</html>
Registerservlet.java

import java.io.IOException;
import java.io.PrintWriter;
import static java.lang.System.out;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns = {"/Registerservlet"})
public class Registerservlet 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()) {
/* 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 Registerservlet</title>");
out.println("</head>");
out.println("<body>");

Class.forName("com.mysql.jdbc.Driver");
Connection
com=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb1","root","12345"
);

String a,b,c,d;
String Query="insert into emp Values(?,?,?,?)";
Statement st= (Statement) com.createStatement();
PreparedStatement ps;
ps=com.prepareStatement(Query);
a=request.getParameter("t1");
b=request.getParameter("t2");
c=request.getParameter("t3");
d=request.getParameter("t4");
ps.setString(1,a);
ps.setString(2,b);
ps.setString(3,c);
ps.setString(4,d);
ps.executeUpdate();
out.println("Record inserted successfully");
com.close();

}
catch(Exception e)
{
System.out.println(e);
}

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
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>

}
Practical 2A

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

Index.html

<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="LoginServlet" >
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>

</body>
</html>

LoginServlet.java

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns = {"/LoginServlet"})
public class LoginServlet extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {

out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet LoginServlet</title>");
out.println("</head>");
out.println("<body>");

String uname = request.getParameter("txtId");


String upass = request.getParameter("txtPass");
if(uname.equals("admin") && upass.equals("servlet")){
RequestDispatcher rd = request.getRequestDispatcher("WelcomeServlet");
rd.forward(request, response);
}
else{

out.println("<h1> Login Fail !!! </h1>");


RequestDispatcher rd = request.getRequestDispatcher("index.html");
rd.include(request, response);
}
out.println("</body>");
out.println("</html>");
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

@Override
public String getServletInfo() {
return "Short description";
}
WelcomeServlet.java

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns = {"/WelcomeServlet"})
public class WelcomeServlet extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {

out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet WelcomeServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Welcome to the world of Servlet !!!!</h1>");
out.println("</body>");
out.println("</html>");
}
}

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

@Override
public String getServletInfo() {
return "Short description";
}
}

Output
Practical 2B

Aim: Create a servlet that uses Cookies to store the number of times a user has visited
servlet.

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="page1" method="GET">

Enter Your Name <input type="text" name="txtName"><br>


<input type="submit" value="Click to Enter ">
</form>

</body>
</html>

page1.java

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.Cookie;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns = {"/page1"})
public class page1 extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse


response)

throws ServletException, IOException {

response.setContentType("text/html;charset=UTF-8");

try (PrintWriter out = response.getWriter()) {

out.println("<!DOCTYPE html>");

out.println("<html>");

out.println("<head>");

out.println("<title>Servlet page1</title>");

out.println("</head>");

out.println("<body>");

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("<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("</body>");

out.println("</html>");
}

@Override

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

processRequest(request, response);

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

}
page2.java

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.Cookie;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns = {"/page2"})

public class page2 extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse


response)

throws ServletException, IOException {

response.setContentType("text/html;charset=UTF-8");

try (PrintWriter out = response.getWriter()) {

out.println("<!DOCTYPE html>");

out.println("<html>");

out.println("<head>");

out.println("<title>Servlet page2</title>");

out.println("</head>");

out.println("<body>");
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=page1 >Click to visit Page 1 </a></h1>");

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("</body>");

out.println("</html>");

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException

processRequest(request, response);

PrintWriter out = response.getWriter();

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

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

*/

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.Cookie;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

/**

* @author USER

*/

@WebServlet(urlPatterns = {"/page3"})

public class page3 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())

/* 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 page2</title>");

out.println("</head>");

out.println("<body>");

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=page1 >Click to visit Page 1 </a></h1>");

out.println("<h1><a href=page2 >Click to visit Page 2 </a></h1>");

out.println("<h1><a href=page4 >Click to visit Page 4 </a></h1>");

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

*/

@Override

public String getServletInfo() {

return "Short description";

}// </editor-fold>

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

*/

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

/**

* @author USER

*/

@WebServlet(urlPatterns = {"/page4"})

public class page4 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()) {


out.println("<!DOCTYPE html>");

out.println("<html>");

out.println("<head>");

out.println("<title>Servlet page2</title>");

out.println("</head>");

out.println("<body>");

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=page1 >Click to visit Page 1 </a></h1>");


out.println("<h1><a href=page2 >Click to visit Page 2 </a></h1>");

out.println("<h1><a href=page3 >Click to visit Page 3 </a></h1>");

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

*/

@Override

public String getServletInfo() {

return "Short description";

}// </editor-fold>

}
Practical 2C

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

<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

/*

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

*/

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

/**

* @author USER

*/

@WebServlet(urlPatterns = {"/page1"})

public class page1 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()) {

/* 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 page1</title>");

out.println("</head>");

out.println("<body>");

HttpSession hs = request.getSession(true);

if(hs.isNew()){

String name = request.getParameter("txtName");

hs.setAttribute("uname", name);

hs.setAttribute("visit", "1");

out.println("<h1>Welcome First Time</h1>");

else{

out.println("<h1>Welcome Again</h1>");

int visit = Integer.parseInt((String)hs.getAttribute("visit"))+1;

out.println("<h1>You Visited "+visit+"Times</h1>"); hs.setAttribute("visit", ""+visit); }

out.println("<h1>Your Session ID "+hs.getId()+"</h1>");

out.println("<h1>You Logged in at "+new java.util.Date(hs.getCreationTime())+"</h1>");

out.println("<h1><a href=page2>Click for Page 2 </a></h1>");


out.println("<h1><a href=page3>Click for Page 3 </a></h1>");

out.println("<h1><a href=LogoutServlet>Click to Terminate Session </a></h1>");

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

*/

@Override

public String getServletInfo() {

return "Short description";

}// </editor-fold>
}

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

*/

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

/**

* @author USER

*/

@WebServlet(urlPatterns = {"/page2"})

public class page2 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()) {

/* 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 page2</title>");

out.println("</head>");

out.println("<body>");

out.println("<html><head><title>Servlet Page2</title></head>");

HttpSession hs = request.getSession(false);
out.println("<h1>Welcome Again on Page No. 2</h1>");

int visit = Integer.parseInt((String)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=LogoutServlet>Click for Terminate Session </a></h1>");

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

*/
@Override

public String getServletInfo() {

return "Short description";

}// </editor-fold>

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

*/

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

/**

* @author USER
*/

@WebServlet(urlPatterns = {"/page3"})

public class page3 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()) {

/* 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 page3</title>");

out.println("</head>");

out.println("<body>");
//out.println("<html><head><title>Servlet Page2</title></head>");

HttpSession hs = request.getSession(false);

out.println("<h1>Welcome Again on Page No. 2</h1>");

int visit = Integer.parseInt((String)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=page2>Click for Page 2 </a></h1>");

out.println("<h1><a href=LogoutServlet>Click for Terminate Session </a></h1>");

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

*/

@Override

public String getServletInfo() {

return "Short description";

}// </editor-fold>

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

*/

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

/**

* @author USER

*/

@WebServlet(urlPatterns = {"/LogoutServlet"})

public class LogoutServlet 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()) {


/* 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 LogoutServlet</title>");

out.println("</head>");

out.println("<body>");

out.println("<html><head><title>Servlet LogoutServlet</title></head>");

out.println("<body>");

javax.servlet.http.HttpSession hs = request.getSession();

if(hs != null) hs.invalidate();

out.println("<h1>You are Logged out now........</h1>");

out.println("</body>");

out.println("</html>");

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

Output:
Practical 3a.
Aim: Create a Servlet application to upload and download a file.

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

FileUploadServlet.java

/*
* 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 fileservletapp;

import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.*;

/**
*
* @author Beena Kapadia
*/
@MultipartConfig
public class FileUploadServlet extends HttpServlet {
public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException,
IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String path=req.getParameter("destination");
Part filePart=req.getPart("file");
//String sfilePart=req.getPart("file").toString();
//out.print("<br> filePart: "+sfilePart);
String filename=filePart.getSubmittedFileName().toString();
out.print("<br><br><hr> file name: "+filename);
OutputStream os=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);}
}}
Index.html

<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>File Download Page</title>
</head>
<body>
<h1>File Download Application</h1>
Click <a href="DownloadServlet?filename=SampleChapter.pdf">Sample Chapter</a>
<br/><br/>
Click <a href="DownloadServlet?filename=TOC.pdf">Table Of Contents</a>

</body>
</html>

DownloadServlet.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 filedownloadapp;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DownloadServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
response.setContentType("APPLICATION/OCTET-STREAM");
String filename = request.getParameter("filename");
ServletContext context = getServletContext();
InputStream is = context.getResourceAsStream("/" + filename);
//ServletOutputStream out = response.getOutputStream(); // any of the two works
PrintWriter out=response.getWriter();
response.setHeader("Content-Disposition","attachment; filename=\"" + filename +
"\""); // if comment this statement then it wl ask you about the editor with which you want to
open the file

int i;

while ((i=is.read()) != -1) {


out.write(i);
}
is.close();
out.close();
}

}
Practical 3b.
Aim: Develop Simple Servlet Question Answer Application using Database.
create database qadb;

use qadb;

CREATE TABLE myquiz (qno CHAR(25),question CHAR(100), op1 CHAR(50), op2


CHAR(50), op3 CHAR(50), op4 CHAR(50),ans CHAR(20));

INSERT INTO myquiz (qno, question, op1,op2,op3,op4,ans) VALUES ('001','What is the


capital of India??','New Delhi','Kolkata','Chennai','Mumbai','New Delhi');

INSERT INTO myquiz (qno, question, op1,op2,op3,op4,ans) VALUES ('002','Who was the First
President of India??','Dr. Rajendra Prasad','Dr. S. Radhakrishnan','Ram Nath Kovind','V. V.
Giri','Dr. Rajendra Prasad');

INSERT INTO myquiz(qno, question, op1,op2,op3,op4,ans) VALUES ('003','What is


ORM','Object Ratio Mean','Object Rotation Measure','Object Relation Mapping','Oracle Request
Management','Object Relation Mapping');

INSERT INTO myquiz(qno, question, op1,op2,op3,op4,ans) VALUES ('004','Unit of Energy


is','Dozon','Kilo Meter ','Joul','Hertz','Joul');

INSERT INTO myquiz(qno, question, op1,op2,op3,op4,ans) VALUES ('005',' is the smallest


memory unit.','bit','byte','Kilo Byte','Giga Byte','bit');

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>

<h1>Welcome to Online Quiz</h1>

<h1><a href="QuizServlet" >CLICK TO START QUIZ</a></h1>

</body>

</html>

QuizServlet.java

import java.io.IOException;

import java.io.PrintWriter;

import java.sql.DriverManager;

import java.sql.Connection;

import java.sql.ResultSet;

import java.sql.Statement;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class QuizServlet extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException {

response.setContentType("text/html;charset=UTF-8");

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 QuizServlet</title>");

out.println("</head>");

out.println("<body>");

out.println("<form action=ShowResult >");

try {

Class.forName("com.mysql.jdbc.Driver");

Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/qadb","root","1234");

Statement stmt = con.createStatement();

ResultSet res = stmt.executeQuery("select * from myquiz");

out.println("<table border=1 >");

int qno=0;

while(res.next()){
qno++;

out.println("<tr><td>"+res.getString(1)+"</td>");

out.println("<td>"+res.getString(2)+"</td></tr>");

out.println("<tr><td><input type=radio name="+qno+"


value="+res.getString(3)+"></td><td>"+res.getString(3)+"</td></tr>");

out.println("<tr><td><input type=radio name="+qno+"


value="+res.getString(4)+"></td><td>"+res.getString(4)+"</td></tr>");

out.println("<tr><td><input type=radio name="+qno+"


value="+res.getString(5)+"></td><td>"+res.getString(5)+"</td></tr>");

out.println("<tr><td><input type=radio name="+qno+"


value="+res.getString(6)+"></td><td>"+res.getString(6)+"</td></tr>");

}catch(Exception e){out.println(e);}

out.println("</table>");

out.println("<input type=reset >");

out.println("<input type=submit value=SUBMIT >");

out.println("</form>");

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

*/

@Override

public String getServletInfo() {

return "Short description";

}// </editor-fold>

ShowResult.java

import java.io.IOException;

import java.io.PrintWriter;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.Statement;

import java.sql.Connection;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;
public class ShowResult extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse


response)

throws ServletException, IOException {

response.setContentType("text/html;charset=UTF-8");

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 ShowResult</title>");

out.println("</head>");

out.println("<body>");

try {

Class.forName("com.mysql.jdbc.Driver");

Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/qadb","root","1234");

Statement stmt = con.createStatement();

ResultSet res = stmt.executeQuery("select ans from myquiz");

int count =0, qno=0;


while(res.next()){

if(res.getString(1).equals(request.getParameter(""+(++qno))))

{ count++; out.println("<h1>Correct </h1>");

else { out.println("<h1>Incorrect </h1>");

out.println("<h1>Your Score is "+count+" </h1>"); }catch(Exception e){out.println(e);

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

*/

@Override

public String getServletInfo() {

return "Short description";

}// </editor-fold>

}
Practical 3c.

Aim:Create simple Servlet application to demonstrate Non-Blocking Read Operation.

index .html

<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">

<meta http-equiv="Refresh" content="0; URL=NonBlockingServlet">

</head>
<body>
<div>TODO write content</div>
</body>
</html>

NonBlockingServlet.java

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
*
* @author USER
*/
public class NonBlockingServlet extends HttpServlet {

protected void service(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out =
response.getWriter()) {

out.println("<h1>FileReader</h1>");

String filename="/WEB-INF/booklist.txt";

ServletContext c=getServletContext();

InputStream in=c.getResourceAsStream(filename);

String

path="http://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+
"/ReadingNonBloclingServlet";

URL url=new URL(path);

HttpURLConnection conn=(HttpURLConnection)url.openConnection();
conn.setChunkedStreamingMode(2); conn.setDoOutput(true);

conn.connect();

if(in!=null)

InputStreamReader inr=new InputStreamReader(in); BufferedReader br = new


BufferedReader(inr); String text="";

System.out.println("Reading started....");

BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));


while((text=br.readLine())!=null){

out.print(text+"<br>");
try{

Thread.sleep(1000);

out.flush();

catch(InterruptedException ex){}
}out.print("reading completed....");

bw.flush();

bw.close();

protected void processRequest(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
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 NonBlockingServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet NonBlockingServlet at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
}
}

ReadingListener.java

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.AsyncContext;
import javax.servlet.ReadListener;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
*
* @author USER
*/
public class ReadingListener implements ReadListener {

private ServletInputStream input = null;

private AsyncContext ac = null;

ReadingListener(ServletInputStream in, AsyncContext c) { input = in;

ac = c;

@Override

public void onDataAvailable() throws IOException {

public void onAllDataRead() throws IOException { ac.complete();

public void onError(final Throwable t) {

ac.complete();

t.printStackTrace();

ReadingNonBlockingServlet.java

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet (name = "ReadingNonBlockingServlet", urlPatterns =
{"/ReadingNonBlockingServlet"},asyncSupported = true )

public class ReadingNonBlockingServlet extends HttpServlet { @Override

protected void service(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

response.setContentType("text/html");

AsyncContext ac = request.startAsync();

ServletInputStream in=request.getInputStream();

in.setReadListener(new ReadingListener(in,ac));

}
}
Practical 4a.

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

Newjsp.jsp

<%--
Document : newjsp
Created on : Aug 3, 2018, 9:11:55 PM
Author : USER
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%> <html><head><title>JSP


Page</title></head> <body>

<h1>Use of Intrinsic Objects in JSP</h1>

<h1>Request Object </h1>

Query String <%=request.getQueryString() %><br>

Context Path <%=request.getContextPath() %><br>

Remote Host <%=request.getRemoteHost() %><br>

<h1>Response Object </h1>

Character Encoding Type <%=response.getCharacterEncoding() %><br>

Content Type <%=response.getContentType() %><br> Locale <%=response.getLocale()


%><br>

<h1>Session Object </h1>

ID <%=session.getId() %><br>

Creation Time <%=new java.util.Date(session.getCreationTime()) %><br>

Last Access Time<%=new java.util.Date(session.getLastAccessedTime()) %><br> </body>

</html>
Practical 4b.
Aim: 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.html

<html><head><title>User Information Paage</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">
<br>
</form>
</body>
</html>

Validate.jsp

<%@page contentType="text/html" pageEncoding="UTF-8" import="mypack.*" %>


<html><head><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="sussessful.jsp"/>
<% }
else {
%>
<jsp:include page="index.html"/>
<%}%>
<%=obj.getError() %>
</body>
</html>

sussessful.jsp

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>DATA VALIDATED SUCCESSFULLY </h1>
</body>
</html>

CheckerBean.java

package mypack;

public class CheckerBean {


private String name, age, hob, email, gender,error;
public CheckerBean(){error="";}
public void setName(String n){name=n;}
public void setAge(String a){age=a;}
public void setHob(String h){hob=h;}
public void setEmail(String e){email=e;}
public void setGender(String g){gender=g;}
public void setError(String e){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;
}
}
Practical 4c.

Aim: Create a registration and login JSP application to register and authenticate the user
based on username and password using JDBC.

create database mydb1;

show databases;

use mydb1;

CREATE TABLE user (userid CHAR(25),password CHAR(25), emailid CHAR(25), country


CHAR(25));

INSERT INTO user (userid,password, emailid,country) VALUES


('ram','ram12','ram@gmail.com','Chennai');

Select * from user;

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>

<h1><a href="Login.html" >Login</a></h1>

<h1><a href="Register.html" >Register</a></h1>

</body>

</html>
Register.html

<html>

<head>

<title>TODO supply a title</title>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

</head>

<body>

<div>register</div>

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

Enter Email<input type="text" name="txtEmail" ><br>

Enter Country Name <input type="text" name="txtCon" ><br>

<input type="reset" ><input type="submit" value="REGISTER" >

</form>

</body>

</html>

Register.jsp

<%--

Document : Register

Created on : Aug 10, 2018, 8:05:31 PM


Author : USER

--%>

<%@page import="java.sql.DriverManager"%>

<%@page import="java.sql.PreparedStatement"%>

<%@page import="java.sql.Connection"%>

<%@page import="java.sql.Connection"%>

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

<%

String uname=request.getParameter("txtName");

String pwd = request.getParameter("txtPass1");

String email = request.getParameter("txtEmail");

String contry = request.getParameter("txtCon");

//if(pass1.equals(pass2)){

try{

Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb1","root","1234");

PreparedStatement stmt = con.prepareStatement("insert into user values (?,?,?,?)");

stmt.setString(1, uname);

stmt.setString(2, pwd);

stmt.setString(3, email);

stmt.setString(4, contry);

int row = stmt.executeUpdate();

if(row==1)

out.println("Registration Successful");

else

out.println("fail");

%>

<jsp:include page="index.html" ></jsp:include>

<%

}catch(Exception e){out.println(e);}

%>

</body>

</html>

Login.html
<html>

<head>

<title>TODO supply a title</title>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

</head>

<body>

<div>login</div>

<form action="Login.jsp" >

Enter User Name <input type="text" name="txtName" ><br>

Enter Password <input type="password" name="txtPass" ><br>

<input type="reset" ><input type="submit" value="LOGIN" >

</form>

</body>

</html>

Login.jsp

<%--

Document : Login

Created on : Aug 10, 2018, 8:17:52 PM

Author : USER

--%>
<%@page import="java.sql.DriverManager"%>

<%@page import="java.sql.PreparedStatement"%>

<%@page import="java.sql.Connection"%>

<%@page import="java.sql.Connection"%>

<%@page contentType="text/html" import="java.sql.*"%>

<html>

<body>

<%

String uname=request.getParameter("txtName");

String pass = request.getParameter("txtPass");

try{

Class.forName("com.mysql.jdbc.Driver");

Connection con
=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb1","root","1234");

PreparedStatement stmt = con.prepareStatement("select password from user where userid=?");

stmt.setString(1, uname);

ResultSet rs = stmt.executeQuery();

if(rs.next()){

if(pass.equals(rs.getString(1)))

out.println("<h1>~~~ LOGIN SUCCESSFULLL ~~~ </h1>");

Else

out.println("<h1>User Name not exist !!!!!</h1>");


%>

<jsp:include page="Register.html" ></jsp:include>

<%

}catch(Exception e){out.println(e);}

%>

</body>

</html>

Output
Practical 5a

Aim: 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.

(Update emp Table)

create database mydb1;

show databases;

use mydb1;

CREATE TABLE emp(empid CHAR(10) PRIMARY KEY, ename CHAR(50), salary


CHAR(50),age INT);

INSERT INTO emp VALUES ('1','ram','5000', 21);

INSERT INTO emp VALUES ('2','sham','3000','25');

INSERT INTO emp VALUES ('3','john','10000','30');

INSERT INTO emp VALUES ('4','riya','8500','35');

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

Register.jsp

<%--

Document : UpdateEmp

Created on : 10 Aug, 2018, 2:17:36 PM

Author : Admin

--%>

<%@page import="java.sql.ResultSet"%>

<%@page import="java.sql.PreparedStatement"%>

<%@page import="java.sql.DriverManager"%>

<%@page import="java.sql.Connection"%>

<%@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>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/mydb1","root","1234");

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>
Practical 5b

Aim:Create a JSP page to demonstrate the use of Expression language.

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="display.jsp">
<h2>Enter number 1:</h2>
<input type="text" name="t1"><br>
<h2>Enter number 2:</h2>
<input type="text" name="t2"><br>
<input type="submit">
</form>
</body>
</html>

display .jsp

<%--
Document : display
Created on : Aug 3, 2018, 10:24:02 PM
Author : USER
--%>

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

Addition= ${param.t1+param.t2} <br>


Subtraction= ${param.t1-param.t2} <br>
Division= ${param.t1/param.t2} <br>
Multiplication= ${param.t1*param.t2} <br>
</body>
</html>

Practical 5c
Aim: Create a JSP application to demonstrate the use of JSTL

Example 1

<html>
<head>
<title>Tag Example</title>
</head>
<body>
<c:out value="${'Welcome to java'}"/>
</body>
</html>

Example 2

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>


<html>
<head>
<title>Core Tag Example</title>
</head>
<body>
<c:set var="Income" scope="session" value="${4000*4}"/>
<c:out value="${Income}"/>
</body>
</html>

Example 3

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>


<html>
<head>
<title>Core Tag Example</title>
</head>
<body>
<c:catch var ="catchtheException">
<% int x = 2/0;%>
</c:catch>

<c:if test = "${catchtheException != null}">


<p>The type of exception is : ${catchtheException} <br />
There is an exception: ${catchtheException.message}</p>
</c:if>
</body>
</html>

Practical 6A
Aim: Create a Currency Converter application using EJB

Step 1)index.html

<html>

<head>

<title>TODO supply a title</title>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

</head>

<body>

<form action="ConvertServlet" >

Enter Amount <input type="text" name="amt"><br>

Select Conversion Type

<input type="radio" name="operation" value="r2d" checked>Rupees to Dollar

<input type="radio" name="operation" value="d2r" >Dollar to Rupees<br>

<input type="reset" ><input type="submit" value="CONVERT" >

</form>

</body>

</html>

Step 2 create stateless session bean

Right click on project -new--session bean-fill details as shown below -ejb name =
give name as ConvertBean finish
Step3 (add 2 business method)

Right click inside public class- insert code------add business method as shown below --
ok
Step 4 write code

package mypack;

import javax.ejb.Stateless;

@Stateless

public class ConvertBean implements ConvertBeanLocal {

@Override

public Double r2dollar(double r)

return r/65.65;

}
@Override

public Double d2rupees(double d)

return d*65.65;

Step 5 create servlet name as ConvertServlet

Step 6 to insert ejb reference in servlet

Right click above the line (public class ConvertServlet extends HttpServlet)insert code---
---call Enterprise java beans---- select ejb bean which we created above in step 2--
write code as given below (only bold text)

import java.io.IOException;

import java.io.PrintWriter;

import javax.ejb.EJB;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import mypack.ConvertBeanLocal;

public class ConvertServlet extends HttpServlet {


@EJB

private ConvertBeanLocal convertBean;

protected void processRequest(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html;charset=UTF-8");

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 ConvertServlet</title>");

out.println("</head>");

out.println("<body>");

double amt = Double.parseDouble(request.getParameter("amt"));

String o=request.getParameter("operation");

if(o.equals("r2d"))

out.println("<h1>rupees to dollar is:"+convertBean.r2dollar(amt)+"</h1>");

if(o.equals("d2r"))

out.println("<h1>dollar to rupees is :"+convertBean.d2rupees(amt)+"</h1>");


}

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

*/

@Override

public String getServletInfo() {

return "Short description";

}// </editor-fold>
Output
Practical 6b.

Aim: Develop a Simple Room Reservation System Application Using EJB.

Steps

1) Go to mysql and create database and table (use below code )

create database mydb2;


show databases;

use mydb2;

CREATE TABLE roombook(RoomId CHAR(4) PRIMARY KEY, RoomType CHAR(20),


charges INT, name CHAR(20), mobile CHAR(20), status CHAR(10)) ;

INSERT INTO roombook(RoomId, RoomType,charges,status)VALUES('1002','Super


Delux',7000,'Not Booked');

INSERT INTO roombook (RoomId, RoomType,charges,status) VALUES('1001','Suit',9500,'Not


Booked');

INSERT INTO roombook (RoomId, RoomType,charges,status) VALUES('1003','Suit',9500,'Not


Booked');

INSERT INTO roombook (RoomId, RoomType,charges,status) VALUES('1004','Super


Delux',8500,'Not Booked');

INSERT INTO roombook (RoomId, RoomType,charges,status)


VALUES('1005','Delux',5000,'Not Booked');

INSERT INTO roombook (RoomId, RoomType,charges,status)


VALUES('1006','Delux',5000,'Not Booked');

Select * from roombook;

2) download jar file


https://stackoverflow.com/questions/17484764/java-lang-classnotfoundexception-
com-mysql-jdbc-driver-in-eclipse

3) Take a new project ---name as practical6b


4) Add jar to project ---- right click on practical6b project -----go to properties --select
libraries from (left) categories and select add jar/folder from right—add the jar file
5) go to window menu---select services ----database----drivers--- right click on mysql
jconnector--- select connect using ----enter database and password and select test
connection button.
6) (follow the pic)
Click next-next-finish

6) Write code for index.html

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="RBServlet" >

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>

7) right click on practical6b project ----new---session bean---create stateless session


bean give name as RRBean

8)add business method

Right click inside public class- insert code------add business method--give details as
shown below in picture -write code
package mypack;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import javax.ejb.Stateless;

@Stateless

public class RRBean implements RRBeanLocal {


@Override

public String roombook(String rt, String cn, String cm) {

String msg="";

try{

Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb2","root","1234");
String query="select * from roombook 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 roombook set name=? where


RoomId=? ");

PreparedStatement stm2 = con.prepareStatement("update roombook set mobile=? where


RoomId=? ");

PreparedStatement stm3 = con.prepareStatement("update roombook set status=? where


RoomId=? ");

stm1.setString(1,cn); stm1.setString(2,rno);

stm2.setString(1,cm); stm2.setString(2,rno);

stm3.setString(1, "Booked"); stm3.setString(2,rno);

stm1.executeUpdate();

stm2.executeUpdate();

stm3.executeUpdate();

msg = "Room "+rno+ " Booked <br> Charges = "+rs.getString(3);

else
{

msg = "Room "+rt+ " currently Not available";

}
catch(Exception e)
{msg=""+e;}

return msg;

}
}

Step 9) create servlet name as RBServlet

Step 10) to insert ejb reference in servlet

Right click above the line (public class RBServlet extends HttpServlet)insert code------
call Enterprise java beans---- select ejb bean created above write code in
processRequest method as given below

/*

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

*/

import java.io.IOException;

import java.io.PrintWriter;

import javax.ejb.EJB;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import mypack.RRBeanLocal;

public class RBServlet extends HttpServlet {

@EJB

private RRBeanLocal rRBean;

protected void processRequest(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html;charset=UTF-8");

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 RBServlet</title>");

out.println("</head>");

out.println("<body>");

String rt=request.getParameter("txtType");

String cn=request.getParameter("txtCust");

String cm=request.getParameter("txtMob");
String msg = rRBean.roombook(rt, cn, cm);

out.println(msg);

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

*/

@Override

public String getServletInfo() {

return "Short description";

}// </editor-fold>

}
Practical 6C

AIM: Develop a Stateful session bean to add items to a cart. Develop a web client to test the
converter.

Step 1
Step 2:
Step 3:

package server;

import java.util.Collection;

import javax.ejb.Remote;

@Remote

public interface CartBeanRemote

public void addItem(String item);

public void removeItem(String item);


public Collection getItems();

Step 4:

package server;

import java.util.ArrayList;

import java.util.Collection;

import javax.annotation.PostConstruct;

import javax.ejb.Stateful;

@Stateful

public class CartBean implements CartBeanRemote

private ArrayList items;

@PostConstruct

public void initialize() {

items = new ArrayList();

@Override

public void addItem(String item) {

items.add(item);

}
@Override

public void removeItem(String item) {

items.remove(item);

@Override

public Collection getItems() {

return items;

}
Step 5:
Step 6:

protected void processRequest(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException

response.setContentType("text/html;charset=UTF-8");

PrintWriter out = response.getWriter();

try

out.println("<html>");

out.println("<head>");

out.println("<title>Servlet CartServlet</title>");
out.println("</head>");

out.println("<body>");

final Context context= new InitialContext();

CartBeanRemote cart =
(CartBeanRemote)context.lookup("java:global/CartStatefulEJB/CartBean");

out.println("<br>Adding items to cart<br>");

cart.addItem("Pizza");

cart.addItem("Pasta");

cart.addItem("Noodles");

cart.addItem("Bread");

cart.addItem("Butter");

out.println("<br>Listing cart contents<br>");

Collection items = cart.getItems();

for (Iterator i = items.iterator(); i.hasNext();)

String item = (String) i.next();

out.println("<br>" + item);

} catch (Exception ex)

{
out.println("ERROR -->" + ex.getMessage());

out.println("</body>");

out.println("</html>");

out.close();

}
Output:
Practical 7a

Aim: Ejb application to demonstrate servlet hit count using singleton session bean

Steps 1)

Right click on project -new--session bean-fill details as shown below -write code

(EJB Name – CountServletHitsBean)

Steps2(add business method)

Right click inside public class- insert code------add business method as shown below --
ok
Step 3 write code only bold text

CountServletHitsBean.java

package mypack;
import javax.ejb.Singleton;

@Singleton
public class CountServletHitsBean implements CountServletHitsBeanLocal
{
private int hitCount;
@Override
public Integer incrementAndGetHitCount()
{
return hitCount++;
}
}
Step 4 create servlet name as ServletClient
Step 5 to insert ejb reference in servlet

Right click above the line (public class ServletClient extends HttpServlet)insert code------
call Enterprise java beans---- select ejb bean as shown below in picture-write code as
given below

Step 6 write code

import java.io.IOException;
import java.io.PrintWriter;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import mypack.CountServletHitsBeanLocal;

/**
*
* @author USER
*/
@WebServlet(urlPatterns = {"/ServletClient"})

public class ServletClient extends HttpServlet {

@EJB
private CountServletHitsBeanLocal countServletHitsBean;

@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet ServletClient</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Number of times this servlet is accessed: " +
countServletHitsBean.incrementAndGetHitCount() + "</h1>");
out.println("</body>");
out.println("</html>");
}
}
}
Practical 7c

Develop Simple Marks entry Application to demonstrate accessing Database using EJB.

Steps

1) Go to mysql and create database and table (use below code )

create database mydb2;

show databases;

use mydb2;

CREATE TABLE student (rollno int, name CHAR(20), class CHAR(20), sub1 int,sub2 int,sub3
int);

Select * from student;

2) download jar file

https://stackoverflow.com/questions/17484764/java-lang-classnotfoundexception-com-
mysql-jdbc-driver-in-eclipse

3)Take a new project ---name as practical7c

4)Add jar to project ---- right click on practical7c project -----go to properties --select
libraries from (left) categories and select add jar/folder from right—add the jar file

5) go to window menu---select services ----database----drivers--- right click on mysql


jconnector--- select connect using ----enter database and password and select test
connection button.

(follow the pic)


Click next-next-finish

6) Write code for index.html

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="studentServlet" >

Enter Your Roll no<input type="text" name="txtroll" ><br>


Enter Your Name<input type="text" name="txtname" ><br>
Enter Your Class<input type="text" name="txtclass" ><br>
Enter Your subject1 marks<input type="text" name="txts1" ><br>
Enter Your subject2 marks<input type="text" name="txts2" ><br>
Enter Your subject3 marks<input type="text" name="txts3" ><br>
<input type="reset" ><input type="submit" value="submit">

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

6) right click on practical7c project ----new---session bean---create stateless session bean


give name as studentbean

7) add business method

Right click inside public class- insert code------add business method--give details as
shown below in picture -write code
Following code will appear
8) write the code below (Only bold text )

package mypack;

import javax.ejb.Stateless;
import java.sql.*;

@Stateless
public class studentbean implements studentbeanLocal {

@Override
public String insertmark(int rno, String n, String c, int s1, int s2, int s3)

String msg="";

try{
Class.forName("com.mysql.jdbc.Driver");
Connection con
=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb2","root","1234");
PreparedStatement stm1 = con.prepareStatement("insert into student (rollno , name, class
, sub1 ,sub2 ,sub3)values(?,?,?,?,?,?)");

stm1.setInt(1,rno);
stm1.setString(2,n);
stm1.setString(3,c);
stm1.setInt(4,s1);
stm1.setInt(5,s2);
stm1.setInt(6,s3);

stm1.executeUpdate();
msg="insert successful";

}catch(Exception e)
{
msg=""+e;
}
return msg;
}

Step 9)create servlet---- name as studentServlet

Step 10) to insert ejb reference in servlet

Right click above the line (public class studentServlet extends HttpServlet)insert code----
--call Enterprise java beans---- select ejb bean write code as given below in
processRequest

import java.io.IOException;
import java.io.PrintWriter;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import mypack.studentbeanLocal;

@WebServlet(urlPatterns = {"/studentServlet"})

public class studentServlet extends HttpServlet {

@EJB
private studentbeanLocal studentbean;

protected void processRequest(HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
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 studentServlet</title>");
out.println("</head>");
out.println("<body>");
int rno=Integer.parseInt(request.getParameter("txtroll"));
String n=request.getParameter("txtname");
String c=request.getParameter("txtclass");
int s1=Integer.parseInt(request.getParameter("txts1"));
int s2=Integer.parseInt(request.getParameter("txts2"));
int s3=Integer.parseInt(request.getParameter("txts3"));
String msg=studentbean.insertmark(rno,n,c,s1,s2,s3);

out.println(msg);

out.println("</body>");
out.println("</html>");
}
}

Output
Practical 8A
Aim:Develop a Simple Inventory Application Using JPA.
Step 1

create database Product ;

show Databases;

use Product;

create table Product (ProductNo int PRIMARY KEY AUTO_INCREMENT, ProductName


CHAR(50), Message CHAR(100), MessageDate CHAR(50));

select * from Product;

Download jar file

Link to download jar file

https://stackoverflow.com/questions/17484764/java-lang-classnotfoundexception-com-
mysql-jdbc-driver-in-eclipse

Step 2

1. Create new project name as inventory1Right click on inventory1new-other


2. Add jar file
3. Create Persistence unit by Right click on inventory1
Select mysqlconnector/java-----click next
Click next ----next------finish
Select product -----click add
Click next
Click next
Select util.list option --------finish
Go to product .java in ganesh folder the below code of product .java will come
automatically you don’t write anything in this product.java

product .java

package ganesh;

import java.io.Serializable;

import javax.persistence.Basic;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;
import javax.persistence.NamedQueries;

import javax.persistence.NamedQuery;

import javax.persistence.Table;

import javax.validation.constraints.Size;

import javax.xml.bind.annotation.XmlRootElement;

/**

* @author USER

*/

@Entity

@Table(name = "product")

@XmlRootElement

@NamedQueries({

@NamedQuery(name = "Product.findAll", query = "SELECT p FROM Product p")

, @NamedQuery(name = "Product.findByProductNo", query = "SELECT p FROM Product p


WHERE p.productNo = :productNo")

, @NamedQuery(name = "Product.findByProductName", query = "SELECT p FROM Product


p WHERE p.productName = :productName")

, @NamedQuery(name = "Product.findByMessage", query = "SELECT p FROM Product p


WHERE p.message = :message")

, @NamedQuery(name = "Product.findByMessageDate", query = "SELECT p FROM Product


p WHERE p.messageDate = :messageDate")})

public class Product implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)

@Basic(optional = false)

@Column(name = "ProductNo")

private Integer productNo;

@Size(max = 50)

@Column(name = "ProductName")

private String productName;

@Size(max = 100)

@Column(name = "Message")

private String message;

@Size(max = 50)

@Column(name = "MessageDate")

private String messageDate;

public Product() {

public Product(Integer productNo) {

this.productNo = productNo;

public Integer getProductNo() {

return productNo;

}
public void setProductNo(Integer productNo) {

this.productNo = productNo;

public String getProductName() {

return productName;

public void setProductName(String productName) {

this.productName = productName;

public String getMessage() {

return message;

public void setMessage(String message) {

this.message = message;

public String getMessageDate() {

return messageDate;

public void setMessageDate(String messageDate) {


this.messageDate = messageDate;

@Override

public int hashCode() {

int hash = 0;

hash += (productNo != null ? productNo.hashCode() : 0);

return hash;

@Override

public boolean equals(Object object) {

// TODO: Warning - this method won't work in the case the id fields are not set

if (!(object instanceof Product)) {

return false;

Product other = (Product) object;

if ((this.productNo == null && other.productNo != null) || (this.productNo != null &&


!this.productNo.equals(other.productNo))) {

return false;

return true;

@Override
public String toString() {

return "ganesh.Product[ productNo=" + productNo + " ]";

Step 3

Create a new jsp by right click on project and name as index and write following code

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 style="background-color: pink;">

product description

<form action="ProductView.jsp" method="post">

product name : <input name="pr" maxlength="25" size="50" />

Price: : <input type ="text" name="message" />


</textarea> <input type="submit" name="btnSubmit" value="Submit" />

</form>

</body>

</html>

Create a new jsp by right click on project and name as ProductView and write following
code

ProductView.jsp

<%--

Document : ProductView

Created on : Sep 21, 2018, 6:49:30 PM

Author : USER

--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<%@page import ="java.util.*,javax.persistence.*,ganesh.Product" %>

<!DOCTYPE html>

<%!

private EntityManagerFactory entityManagerFactory;

private EntityManager entityManager;

private EntityTransaction entityTransaction;

List<Product>Product;

%>
<%

entityManagerFactory=Persistence.createEntityManagerFactory("inventory1PU");

entityManager=entityManagerFactory.createEntityManager();

String submit =request.getParameter("btnSubmit");

if(submit !=null && ("submit").equals("submit"))

try

String pr=request.getParameter("pr");

String message =request.getParameter("message");

String messageDate =new java.util.Date().toString();

Product gb=new Product() ;

gb.setProductName(pr);

gb.setMessage(message);

gb.setMessageDate(messageDate);

entityTransaction=entityManager.getTransaction();

entityTransaction.begin();

entityManager.persist(gb);

entityTransaction.commit();

}catch(RuntimeException e)

if(entityTransaction!=null)entityTransaction.rollback();
throw e;

response.sendRedirect("ProductView.jsp");

try{

Product =entityManager.createQuery("SELECT g from Product g").getResultList();

}catch(RuntimeException e)

entityManager.close();

%>

<html>

<body>

<hr/>

<%

Iterator iterator=Product.iterator();

while (iterator.hasNext())

Product obj=(Product) iterator.next();

%>

On<%=obj.getMessageDate()%><br>

<b><%=obj.getProductName()%></b>

<%=obj.getMessage()%>
<br>

<br>

<%

%>

*/

</body>

</html>

Run index.jsp file


Practical 8B

Aim:Develop a GuestBook Application using JPA.

Step 1

create database GuestBook;


show databases;

use GuestBook;

create table GuestBook(VisitorNo int PRIMARY KEY AUTO_INCREMENT, VisitorName


CHAR(50), Message CHAR(100), MessageDate CHAR(50));
select * from GuestBook;

Add the jar file

Link to download jar file

https://stackoverflow.com/questions/17484764/java-lang-classnotfoundexception-com-
mysql-jdbc-driver-in-eclipse

Step 2

1. Create new project name as GuestApplication


2. Add jar file
3. Create Persistence unit by Right click on GuestApplication new-other
Select mysql------go next
Click Add
Select util.list----finish

Go to Guest.java in ganesh folder the below code of product .java will come automatically
you don’t write anything in this Guest.java

Guest.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 ganesh;
import java.io.Serializable;

import javax.persistence.Basic;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;

import javax.persistence.NamedQueries;

import javax.persistence.NamedQuery;

import javax.persistence.Table;

import javax.validation.constraints.Size;

import javax.xml.bind.annotation.XmlRootElement;

/**

* @author USER

*/

@Entity

@Table(name = "guest")

@XmlRootElement

@NamedQueries({

@NamedQuery(name = "Guest.findAll", query = "SELECT g FROM Guest g")

, @NamedQuery(name = "Guest.findByVisitorNo", query = "SELECT g FROM Guest g


WHERE g.visitorNo = :visitorNo")

, @NamedQuery(name = "Guest.findByVisitorName", query = "SELECT g FROM Guest g


WHERE g.visitorName = :visitorName")
, @NamedQuery(name = "Guest.findByMessage", query = "SELECT g FROM Guest g
WHERE g.message = :message")

, @NamedQuery(name = "Guest.findByMessageDate", query = "SELECT g FROM Guest g


WHERE g.messageDate = :messageDate")})

public class Guest implements Serializable {

private static final long serialVersionUID = 1L;

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

@Basic(optional = false)

@Column(name = "VisitorNo")

private Integer visitorNo;

@Size(max = 50)

@Column(name = "VisitorName")

private String visitorName;

@Size(max = 100)

@Column(name = "Message")

private String message;

@Size(max = 50)

@Column(name = "MessageDate")

private String messageDate;

public Guest() {

public Guest(Integer visitorNo) {


this.visitorNo = visitorNo;

public Integer getVisitorNo() {

return visitorNo;

public void setVisitorNo(Integer visitorNo) {

this.visitorNo = visitorNo;

public String getVisitorName() {

return visitorName;

public void setVisitorName(String visitorName) {

this.visitorName = visitorName;

public String getMessage() {

return message;

public void setMessage(String message) {

this.message = message;
}

public String getMessageDate() {

return messageDate;

public void setMessageDate(String messageDate) {

this.messageDate = messageDate;

@Override

public int hashCode() {

int hash = 0;

hash += (visitorNo != null ? visitorNo.hashCode() : 0);

return hash;

@Override

public boolean equals(Object object) {

// TODO: Warning - this method won't work in the case the id fields are not set

if (!(object instanceof Guest)) {

return false;

Guest other = (Guest) object;


if ((this.visitorNo == null && other.visitorNo != null) || (this.visitorNo != null &&
!this.visitorNo.equals(other.visitorNo))) {

return false;

return true;

@Override

public String toString() {

return "ganesh.Guest[ visitorNo=" + visitorNo + " ]";

Create a new jsp by right click on project and name as index and write following code

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 style="background-color: pink;">

Guest book Application


<form action="GuestBookView.jsp" method="post">

visitors name : <input name="pr" maxlength="25" size="50" />

Message : <input type ="text" name="message" />

</textarea> <input type="submit" name="btnSubmit" value="Submit" />

</form>

</body>

</html>

Create a new jsp by right click on project and name as GuestBookView and write following
code

GuestBookView.jsp

<%--

Document : GuestBookView

Created on : Sep 21, 2018, 11:34:17 PM

Author : USER

--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<%@page import ="java.util.*,javax.persistence.*,ganesh.Guest" %>

<!DOCTYPE html>

<%!

private EntityManagerFactory entityManagerFactory;

private EntityManager entityManager;


private EntityTransaction entityTransaction;

List<Guest>Guest;

%>

<%

entityManagerFactory=Persistence.createEntityManagerFactory("GuestApplicationPU");

entityManager=entityManagerFactory.createEntityManager();

String submit =request.getParameter("btnSubmit");

if(submit !=null && ("submit").equals("submit"))

try

String pr=request.getParameter("pr");

String message =request.getParameter("message");

String messageDate =new java.util.Date().toString();

Guest gb=new Guest() ;

gb.setVisitorName(pr);

gb.setMessage(message);

gb.setMessageDate(messageDate);

entityTransaction=entityManager.getTransaction();

entityTransaction.begin();

entityManager.persist(gb);

entityTransaction.commit();

}catch(RuntimeException e)
{

if(entityTransaction!=null)entityTransaction.rollback();

throw e;

response.sendRedirect("GuestBookView.jsp");

try{

Guest =entityManager.createQuery("SELECT g from guest g").getResultList();

}catch(RuntimeException e)

entityManager.close();

%>

<html>

<body>

<hr/>

<%

Iterator iterator=Guest.iterator();

while (iterator.hasNext())

Guest obj=(Guest) iterator.next();


%>

On<%=obj.getMessageDate()%><br>

<b><%=obj.getVisitorName()%></b>

<%=obj.getMessage()%>

<br>

<br>

<%

%>

*/

</body>

</html>

Run index .jsp


Practical 8C

Aim: Create simple JPA Application to store and retrieve Book details

create database Book;

show Databases;

use Book;

create table Book (BookNo int PRIMARY KEY AUTO_INCREMENT, BookName CHAR(50),
AuthorName CHAR(100), Date CHAR(50));

select * from Book;

Download jar file

Link to download jar file

https://stackoverflow.com/questions/17484764/java-lang-classnotfoundexception-com-
mysql-jdbc-driver-in-eclipse

Step 2

1. Create new project name as BookDetails Right click on inventory1new-other


2. Add jar file
3. Create Persistence unit by Right click on BookDetails
Select mysqlconnector/java-----click next
 Click next ----next------finish
 SelectBook -----click add
 Click next
 Type package name as ganesh
 Click next
 Select util.list option --------finish

Go to book .java in ganesh folder the below code of product .java will come automatically you
don’t write anything in this product.java

Step 3

Create a new jsp by right click on project and name as index and write following code

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 style="background-color: pink;">

Book description <br>

<form action="BookView.jsp" method="post">

Book name : <input name="pr" maxlength="25" size="50" />

Author Name: : <input type ="text" name="message" />

<input type="submit" name="btnSubmit" value="Submit" />

</form>

</body>

</html>

Create a new jsp by right click on project and name as ProductView and write following
code

BookView.jsp

<%--

Document : BookView

Created on : Sep 21, 2018, 6:49:30 PM

Author : USER

--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<%@page import ="java.util.*,javax.persistence.*,ganesh.Book" %>

<!DOCTYPE html>

<%!

private EntityManagerFactory entityManagerFactory;

private EntityManager entityManager;

private EntityTransaction entityTransaction;

List<Book>Book;

%>

<%

entityManagerFactory=Persistence.createEntityManagerFactory("Book1PU");

entityManager=entityManagerFactory.createEntityManager();

String submit =request.getParameter("btnSubmit");

if(submit !=null && ("submit").equals("submit"))

try

String bn=request.getParameter("pr");

String an =request.getParameter("message");

String messageDate =new java.util.Date().toString();

Book gb=new Book() ;

gb.setBookName(pr);

gb.setAuthorName(message);

gb.setMessageDate(messageDate);
entityTransaction=entityManager.getTransaction();

entityTransaction.begin();

entityManager.persist(gb);

entityTransaction.commit();

}catch(RuntimeException e)

if(entityTransaction!=null)entityTransaction.rollback();

throw e;

response.sendRedirect("BookView.jsp");

try{

Book =entityManager.createQuery("SELECT g from Book g").getResultList();

}catch(RuntimeException e)

entityManager.close();

%>

<html>

<body>

<hr/>

<%

Iterator iterator=Book.iterator();
while (iterator.hasNext())

Product obj=(Book) iterator.next();

%>

On<%=obj.getMessageDate()%><br>

<b><%=obj.getBookName()%></b>

<%=obj.getAuthorName()%>

<br>

<br>

<%

%>

*/

</body>

</html>

Run index.jsp file


Practical 9A
Aim: Develop a JPA Application to demonstrate use of ORM associations

create database mydb4;

show databases;

use mydb4;

CREATE TABLE student (sid int PRIMARY KEY,sname CHAR(25),age int);

Click on project name ie Practical9a--new--java class

Give Name StudentEntity.java

package mypack;
import javax.persistence.*;

@Entity
@Table(name="student")
public class StudentEntity
{
@Id
private int id;
private String name;
private int age;
public StudentEntity (int id,String name,int age)
{

super();
this.id=id;
this.name=name;
this.age=age;

public StudentEntity ()
{

super();

public int getId() {


return id;
}

public void setId(int id) {


this.id = id;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public int getAge() {


return age;
}

public void setAge(int age) {


this.age = age;
}

Java class
(PersistStudent.java)

package mypack;
import javax.enterprise.inject.New;
import javax.persistence.*;
import mypack.StudentEntity.*;

public class PersistStudent


{

public static void main (String[] args)


{
EntityManagerFactory emf=Persistence.createEntityManagerFactory ("Studentdetails");
EntityManager em=emf.createEntityManager();
em.getTransaction().begin ();
StudentEntity s1=New StudentEntity();
s1.setId(1);
s1.setName("ram");
s1.setAge(22);
StudentEntity s2=New StudentEntity();
s1.setId(2);
s1.setName("sham");
s1.setAge(21);

em.persist (s1);
em.persist (s2);
em.getTransaction ().commit ();
emf.close ();
em.close();
}

}
Output
Practical 9B
Aim:Develop a hibernate application to store Feedback of Website Visitor in MySQL
Database.

create database feedbackdbs;

use feedbackdbs;

create table GuestBook1(vno int PRIMARY KEY AUTO_INCREMENT, vname CHAR(50),


msg CHAR(100), mdate CHAR(50));

select * from GuestBook1;

download jar file

https://stackoverflow.com/questions/17484764/java-lang-classnotfoundexception-com-
mysql-jdbc-driver-in-eclipse

step

go to file –new project –java (left)—web applications (right)

project name –empfeedback—next ---next---select hibernate framework


Choose mysql--next
Next – next --- finish

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="fb.jsp">

visitors name : <input type ="text" name="name" /> <br>

Message : <textarea cols="50" rows="10" name="message"> </textarea><br>

<input type="submit" name="btnSubmit" value="Submit" />

</form>

</body>

</html>

Right click on project name ie userfeedback ---new –java class

Name – guestbook

package --mypack

write code

guestbook.java

package mypack;

import javax.persistence.*;

@Entity

@Table(name="GuestBook1")

public class GuestBook implements java.io.Serializable

{
@Id

@GeneratedValue

@Column(name="vno")

private Integer visitorNo;

@Column(name="vname")

private String visitorName;

@Column(name="msg")

private String message;

@Column(name="mdate")

private String messageDate;

public GuestBook(){ }

Place cursor on line 20 or below public GuestBook(){ } and right click --- insert code ---
getter and setter
Click generate

Code will come automatically

So your guestbook.java will look like this after code generate

package mypack;

import javax.persistence.*;
@Entity

@Table(name="GuestBook1")

public class GuestBook implements java.io.Serializable

@Id

@GeneratedValue

@Column(name="vno")

private Integer visitorNo;

@Column(name="vname")

private String visitorName;

@Column(name="msg")

private String message;

@Column(name="mdate")

private String messageDate;

public GuestBook(){ }

public Integer getVisitorNo() {

return visitorNo;

public void setVisitorNo(Integer visitorNo) {

this.visitorNo = visitorNo;

public String getVisitorName() {


return visitorName;

public void setVisitorName(String visitorName) {

this.visitorName = visitorName;

public String getMessage() {

return message;

public void setMessage(String message) {

this.message = message;

public String getMessageDate() {

return messageDate;

public void setMessageDate(String messageDate) {

this.messageDate = messageDate;

Right click on project userfeedback --- new jsp----Name –fb


fb.jsp

<%--

Document : fb

Created on : Sep 26, 2018, 8:01:47 PM

Author : USER

--%>

<%@page import="org.hibernate.*,org.hibernate.cfg.*,mypack.*" %>

<%!SessionFactory sf;

org.hibernate.Session hibSession;

%>

<%

sf=new Configuration().configure().buildSessionFactory();

hibSession=sf.openSession();

Transaction tx=null;

GuestBook gb=new GuestBook();

try{

tx= hibSession.beginTransaction();

String username =request.getParameter("name");

String usermsg =request.getParameter("message");

String nowtime =""+new java.util.Date();

gb.setVisitorName(username);

gb.setMessage(usermsg);
gb.setMessageDate(nowtime);

hibSession.save(gb);

tx.commit();

out.println("thanks for feedback ");

catch(Exception e)

{out.println(e);}

hibSession.close();

%>

Go to source package – default package –open Hibernate.cfg.xml

hibernate.cfg.xml

<hibernate-configuration>

<session-factory>

<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>

<property
name="hibernate.connection.url">jdbc:mysql://localhost:3306/feedbackdbs?zeroDateTimeBehav
ior=convertToNull</property>

<property name="hibernate.connection.username">root</property>

<property name="hibernate.connection.password">1234</property>

<mapping class ="mypack.GuestBook"/>


</session-factory>

</hibernate-configuration>
Practical 9C
Aim: Develop a Hibernate application to store and retrieve employeedetails in MySQL
Database

create database feedbackdbs;


use feedbackdbs;

create table emptable(eno int PRIMARY KEY AUTO_INCREMENT, ename CHAR(50), eadd
CHAR(100), edate CHAR(50));

select * from emptable;

project name -empfeedback

step

go to file –new project –java (left)—web applications (right)

project name –empfeedback—next ---next---select hibernate framework


Choose mysql--next
Next – next --- finish

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="fb.jsp">

Employee name : <input type ="text" name="name" /> <br>

Address : <textarea cols="50" rows="10" name="address"> </textarea><br>

<input type="submit" name="btnSubmit" value="Submit" />

</form>

</body>

</html>

Right click on project name ie empfeedback ---new –java class

Name –empbook

package --mypack

empbook.java

write this code


Place cursor on line 20 ie below public empbook(){ } and right click --- insert code ---
getter and setter
Click generate

Code will come automatically

So your empbook.java will look like this after code generate

package mypack;

import javax.persistence.*;
@Entity

@Table(name="emptable")

public class empbook implements java.io.Serializable{

@Id

@GeneratedValue

@Column(name="eno")

private Integer empNo;

@Column(name="ename")

private String empName;

@Column(name="eadd")

private String eAddress;

@Column(name="edate")

private String eDate;

public empbook(){ }

public Integer getEmpNo() {

return empNo;

public void setEmpNo(Integer empNo) {

this.empNo = empNo;

public String getEmpName() {

return empName;

}
public void setEmpName(String empName) {

this.empName = empName;

public String geteAddress() {

return eAddress;

public void seteAddress(String eAddress) {

this.eAddress = eAddress;

public String geteDate() {

return eDate;

public void seteDate(String eDate) {

this.eDate = eDate;

Go to source package – default package –open Hibernate.cfg.xml

Hibernate.cfg.xml

<hibernate-configuration>

<session-factory>

<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property
name="hibernate.connection.url">jdbc:mysql://localhost:3306/feedbackdbs?zeroDateTimeBehav
ior=convertToNull</property>

<property name="hibernate.connection.username">root</property>

<property name="hibernate.connection.password">1234</property>

<mapping class ="mypack.empbook"/>

</session-factory>

</hibernate-configuration>

Right click on project empfeedback--- new jsp----Name –fb

fb.jsp

<%@page import="org.hibernate.*,org.hibernate.cfg.*,mypack.*" %>

<%!SessionFactory sf;

org.hibernate.Session hibSession;

%>

<%

sf=new Configuration().configure().buildSessionFactory();

hibSession=sf.openSession();

Transaction tx=null;

empbook gb=new empbook();

try{

tx= hibSession.beginTransaction();

String empname =request.getParameter("name");

String empaddress =request.getParameter("address");


String nowtime =""+new java.util.Date();

gb.setEmpName(empname);

gb.seteAddress(empaddress);

gb.seteDate(nowtime);

hibSession.save(gb);

tx.commit();

out.println("thanks for feedback ");

catch(Exception e)

{out.println(e);}

hibSession.close();

%>

Output:
Practical 10a
Develop an application to demonstrate Hibernate One-to-One Mapping Using Annotation

create database empdb;

use empdb;

create table emp (id int PRIMARY KEY AUTO_INCREMENT, firstName CHAR (20),
lastName CHAR (20));

StoreData.java

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.boot.registry.StandardServiceRegistry;

import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

import org.hibernate.metamodel.Metadata;

import org.hibernate.metamodel.MetadataSources;

public class StoreData

public static void main (String[] args)

StandardServiceRegistry ssr= new


StandardServiceRegistryBuilder().configure("hibernate.clg.xml").build();

Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();

SessionFactory factory;

factory = meta.getSessionFactoryBuilder().build();
Session session =factory.openSession();

org.hibernate.Transaction t=session.beginTransaction();

Employee e1=new Employee();

e1.setId (1);

e1.setFirstName ("ram");

e1.setLastName ("patel");

session.save (e1);

t.commit();

System.out.println ("successfully saved");

factory.close();

session.close();

Employee.java

public class Employee

private int id;

private String firstName,lastName;

public int getId() {

return id;

}
public void setId(int id) {

this.id = id;

public String getFirstName() {

return firstName;

public void setFirstName(String firstName) {

this.firstName = firstName;

public String getLastName() {

return lastName;

public void setLastName(String lastName) {

this.lastName = lastName;

Hibernate.cfg

<?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/empdb?zeroDateTimeBehavior=c
onvertToNull</property>

<property name="hibernate.connection.username">root</property>

<property name="hibernate.connection.password">1234</property>

<mapping resource="employee.hbm.xml"/>

<mapping/>

</session-factory>

</hibernate-configuration>

Employee.hbm

<?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="Employee" table="emp"/>

<id name="id">

<generator class="assigned"></generator>

</id>

<property name="firstName"></property>

<property name="lastName"></property>

</hibernate-mapping>
Practical 10B

Aim: Develop Hibernate application to enter and retrieve course details with ORM
Mapping.

create database mydb2;

show databases;

use mydb2;

CREATE TABLE COURSE (id int PRIMARY KEY AUTO_INCREMENT ,Cname


CHAR(25), fees int);

Course.java

public class Course

private int id;

private String CName;

private int fees;

public Course(){}

public Course(String Cname,int fees)

this.CName=Cname;

this.fees=fees;

public int getId() {

return id;

}
public void setId(int id) {

this.id = id;

public String getCName() {

return CName;

public void setCName(String CName) {

this.CName = CName;

public int getFees() {

return fees;

public void setFees(int fees) {

this.fees = fees;

hibernate.hbm.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="Course" table="course">

<meta attribute="class-description">

This class contains the course detail.

</meta>

<id name="id" type="int" column="id">

<generator class="native"/>

</id>

<property name="CName" column="Cname" type="String"/>

<property name="fees" column="fees" type="int"/>

</class>

</hibernate-mapping>

ManageCourse.java

import java.util.Iterator;

import java.util.List;

import javax.enterprise.inject.New;

import javax.transaction.HeuristicMixedException;

import javax.transaction.RollbackException;
import javax.transaction.Transaction;

import org.hibernate.HibernateException;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;

public class ManageCourse

private static SessionFactory factory;

private static ManageCourse New;

public static void main(String[] args){

try {

factory = new Configuration().configure().buildSessionFactory ();

catch (Throwable ex){

System.err.println ("Failed to create sessionFactory object."+ex);

throw new ExceptionInInitializerError (ex);

ManageCourse ME=New ManageCourse();

/* add few course records in database */

int CID1=ME.addCourse("java",10000);

int CID2=ME.addCourse("Net",10000);
/*list down all the corses*/

ME.listCourse ();

/*update course records */

ME.updateCourse (1,5000);

/*delete an course records from the database */

ME.deleteCourse(2);

/*list down new list of the courses*/

ME.listCourse ();

/*method to CREATE an course in the database */

public Integer addCourse(String Came, int fees) throws RollbackException,


HeuristicMixedException

Session session=factory.openSession();

Transaction tx=null;

Integer courseID=null;

try

{
tx=(Transaction) session.beginTransaction();

Course c=new Course (Came,fees);

courseID=(Integer) session.save(c) ;

tx.commit();

}catch (HibernateException e){

if (tx!= null) tx.rollback();

e.printStackTrace ();

finally {

session.close ();

return courseID;

/*method to READ All courses*/

public void listCourse (){

Session session=factory.openSession();

Transaction tx=null;

try

tx=(Transaction) session.beginTransaction();

List course =session.createQuery ("FROM Course ").list ();

for (Iterator iterator =course.iterator();iterator.hasNext ();){

Course c=(Course) iterator.next();


System.out.print ("Course Name: " + c.getCName ());

System.out.println ("fees:" +c.fees());

tx.commit ();

catch (HibernateException e){

if (tx!=null) tx.rollback ();

e.printStackTrace ();

}finally {

session.close ();

/* method to update fees for an course */

public void updateCourse(Integer CourseID,int fees){

Session session =factory.openSession();

Transaction tx=null;

try {

tx=(Transaction) session.beginTransaction();

Course c=(Course)session.get(Course.class, CourseID);

c.fees(fees);

session.update(Course);

tx.commit ();

}catch(HibernateException e){

if (tx!=null) tx.rollback();
e.printStackTrace ();

}finally {

session.close();}

/*method to DELETE an course from the records */

public void deleteCourse(Integer CourseID){

Session session =factory.openSession();

Transaction tx=null;

try {

tx=session.beginTransaction();

Course course =(Course)session.get(Course.class, CourseID);

session.delete(course);

tx.commit ();

catch (HibernateException e){

if (tx!=null) tx.rollback();

e.print StackTrace();

}finally{

session.close();

}
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/mydb2?zeroDateTimeBehavior=c
onvertToNull</property>

<property name="hibernate.connection.username">root</property>

<mapping resource="hibernate.hbm.xml"/>

</session-factory>

</hibernate-configuration>
Practical 10C
Aim:Develop a five page web application site using any two or three Java EE Technologies

create database studentdb;

show databases;

use studentdb;

CREATE TABLE student (id int PRIMARY KEY,name CHAR(25), class CHAR(25), age
int);

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>
<h1> Student Details Applications </h1>
<a href="jspinsert.jsp">Insert Record </a><br>
<a href="jspdelete.jsp">delete Record </a><br>
<a href="jspupdate.jsp">update Record </a><br>
<a href="jspselect.jsp">select Record </a><br>
</form>
</body>
</html>

jspinsert.jsp

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form action="insertservlet" method="GET" >
<h2>Enter id :</h2>
<input type="text" name="t1"><br>
<h2>Enter name :</h2>
<input type="text" name="t2"><br>
<h2>Enter class :</h2>
<input type="text" name="t3"><br><br>
<h2>Enter age :</h2>
<input type="text" name="t4">
<input type="submit" value="submit" />
</form>
</body>
</html>

Insertservlet

import java.beans.Statement;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns = {"/insertservlet"})
public class insertservlet extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet Registerservlet</title>");
out.println("</head>");
out.println("<body>");
Class.forName("com.mysql.jdbc.Driver");
Connection
com=DriverManager.getConnection("jdbc:mysql://localhost:3306/studentdb","root","123
45");

String a,b,c,d;
String Query="insert into student Values(?,?,?,?)";
Statement st= (Statement) com.createStatement();
PreparedStatement ps;
ps=com.prepareStatement(Query);
a=Integer.ParseInt(request.getParameter("t1"));
b=request.getParameter("t2");
c=request.getParameter("t3");
d= Integer.ParseInt(request.getParameter("t4"));
ps.setInt(1,a);
ps.setString(2,b);
ps.setString(3,c);
ps.setInt(4,d);
ps.executeUpdate();
out.println("Record inserted successfully");
com.close();

}
catch(Exception e)
{
System.out.println(e);
}

out.println("</body>");
out.println("</html>");
}

Run the program check insert is working . run index.html file

jspdelete.jsp

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form action="deleteservlet" method="GET" >
<h2>Enter id :</h2>
<input type="text" name="t1"><br>

<input type="submit" value="submit" />


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

deleteservlet.java

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns = {"/deleteservlet"})
public class deleteservlet extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
/* 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 deleteservlet</title>");
out.println("</head>");
out.println("<body>");

Class.forName("com.mysql.jdbc.Driver");
Connection
com=DriverManager.getConnection("jdbc:mysql://localhost:3306/studentdb","root","1234");

int a;

String Query="DELETE FROM students WHERE id= ?";


java.sql.Statement st=com.createStatement();
PreparedStatement ps;
ps=com.prepareStatement(Query);
a=Integer.parseInt(request.getParameter("t1"));
ps.setInt(1,a);
ps.executeUpdate();
out.println("Record delete successfully");
com.close();

}
catch(Exception e)
{
System.out.println(e);
}

out.println("</body>");
out.println("</html>");
}

Run the program check inserts, delete is working.


Run index.html file

jspupdate

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form action="updateservlet" method="GET" >
<h2>Enter id :</h2>
<input type="text" name="t1"><br>
<h2>Enter name :</h2>
<input type="text" name="t2"><br>
<h2>Enter class :</h2>
<input type="text" name="t3"><br><br>
<h2>Enter age :</h2>
<input type="text" name="t4">
<input type="submit" value="submit" />
</form>
</body>
</html>

updateservlet.java

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns = {"/updateservlet"})
public class updateservlet extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
/* 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 updateservlet</title>");
out.println("</head>");
out.println("<body>");

Class.forName("com.mysql.jdbc.Driver");
Connection
com=DriverManager.getConnection("jdbc:mysql://localhost:3306/studentdb","root","1234");

String b,c;int a,d;

String Query="update students set name=?, class=?, age=? where id=?";


java.sql.Statement st=com.createStatement();
PreparedStatement ps;
ps=com.prepareStatement(Query);
a=Integer.parseInt(request.getParameter("t1"));
b=request.getParameter("t2");
c=request.getParameter("t3");
d=Integer.parseInt(request.getParameter("t4"));

ps.setInt(1,a);
ps.setString(2,b);
ps.setString(3,c);
ps.setInt(4,d);
ps.executeUpdate();
out.println("Record updated successfully");
com.close();
}
catch(Exception e)
{
System.out.println(e);
}

out.println("</body>");
out.println("</html>");
}

Run the program check inserts, delete, update is working. Run index.html file

jspselect.jsp
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Connection"%>
<%@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>

<%
try{

Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/studentdb","root","1234");
PreparedStatement stmt = con.prepareStatement("select * from students");

ResultSet rs = stmt.executeQuery();
out.println("Id\t Name\t class \t age \n");
out.println("<br>");
while(rs.next())
{
out.println(rs.getInt(1)+"\t");
out.println(rs.getString(2)+"\t");
out.println(rs.getString(3)+"\t");
out.println(rs.getInt(4)+"\t");
out.println("<br>");
}

}catch(Exception e)
{
out.println(e);
}

%>

Run the program check inserts, delete, update, select is working. Run index.html file
Practical 11

Aim: Write a program to implement calculator web service

Step 1 select java web application

Open Netbeans 8/8.2 --- file --- new project --- java web (left) --- web application(right)

Give name – calcwebservice

Step 2 select web service

Right click on project name calcwebservice –new –other –web service


Step 3

Go to Design page ---- add operation


calservice.java

package mypack;

import javax.jws.WebService;

import javax.jws.WebMethod;

import javax.jws.WebParam;

@WebService(serviceName = "calcservice")

public class calcservice {

@WebMethod(operationName = "hello")

public String hello(@WebParam(name = "name") String txt) {

return "Hello " + txt + " !";

@WebMethod(operationName = "Addition")

public Integer Addition(@WebParam(name = "a") int a, @WebParam(name = "b") int b) {

//TODO write your implementation code here:

return a+b;

@WebMethod(operationName = "Subtract")

public Integer Subtract(@WebParam(name = "a") int a, @WebParam(name = "b") int b) {

//TODO write your implementation code here:


return a-b;

@WebMethod(operationName = "multiply")

public Integer multiply(@WebParam(name = "a") int a, @WebParam(name = "b") int b) {

//TODO write your implementation code here:

return a*b;

@WebMethod(operationName = "divide")

public Integer divide(@WebParam(name = "a") int a, @WebParam(name = "b") int b) {

//TODO write your implementation code here:

return a/b;

Step 4 run

Right click on project name calcwebservice--- deploy

Right click on calservice---test web service

You might also like