Java Prax
Java Prax
calculatorServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import static java.lang.System.out;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
Output-
PRACTICAL 1(B)
Aim- Create a servlet for a login page. If the username and password are correct then it
says message “Hello <username>” else a message “login failed”.
Source Code-
index.html
<html>
<head>
<title>User login</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="userloginServlet" method="post">
Enter your name: <input type="text" name="uname"><br>
Enter your password:<input type="text" name="pwd"><br><br>
<input type="submit" value="login">
<input type="reset" value="clear all">
</form>
</body>
</html>
userloginServlet.java
public class userloginServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
String s1 = request.getParameter("uname");
String s2 = request.getParameter("pwd");
String right_name="admin";
String right_password="abc";
if(s1.equals(right_name))
{
if(s2.equals(right_password))
{
out.println("Hello "+right_name);
}
}
else
out.println("Login Failed ");
} }
Output-
PRACTICAL 1(C)
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.
Source Code-
index.html
<html>
<head>
<title>Storing in a database from a form</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action='dbstore2servlet' method='post'><br>
Name: <input type="text" name='username'><br>
Age: <input type="text" name="userage"><br>
E-mail:<input type="text" name="useremail"><br>
Country:<select name='usercountry'>
<option>India
<option>France
<option>Russia
<option>Belgium
<option>South Korea
</select><br><br>
<input type="submit" value="submit to store">
</form>
</body>
</html>
dbstore2servlet.java
try (PrintWriter out = response.getWriter()) {
try {
String n=request.getParameter("username");
String a=request.getParameter("userage");
String e=request.getParameter("useremail");
String c=request.getParameter("usercountry");
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con;
try {
con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/dbstore2database","root","");
PreparedStatement ps=con.prepareStatement("insert into dbstore2table values(?,?,?,?)");
ps.setString(1,n); ps.setString(2,a); ps.setString(3,e); ps.setString(4,c);
int i=ps.executeUpdate();
if(i>0)
{out.println("you have successfully registered"); } }
Output-
PRACTICAL 2(A)
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.
Source Code-
index.html
<?html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="cookieservlet" method="post">
Name: <input type="text" name="username">
Password:<input type="password" name="userpass">
<input type="submit" value="go">
</form></body></html>
Cookieservlet.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
String n=request.getParameter("username");
String p=request.getParameter("userpass");
if(p.equals("servlet"))
{
RequestDispatcher rd=request.getRequestDispatcher("/cookieservlet2");
rd.forward(request, response);
}
else
{
out.println("Username or Password Incorrect");
RequestDispatcher rd=request.getRequestDispatcher("/index.html");
rd.include(request,response);
}}}
Cookieservlet2.java
protected void processRequest(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
String n=request.getParameter("username");
out.println("Welcome "+n);
Output-
PRACTICAL 2(B)
Aim- Create a servlet that uses Cookies to store the number of times a user has visited
servlet.
Source Code-
index.html
<html>
<head>
<title>cookies</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="cookiesservlet">
Enter your name:<input type="text" name="txtName"><br>
<input type="submit" value="click">
</form>
</body>
</html>
Cookiesservlet.java
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 cookiesservlet</title>");
out.println("</head>");
out.println("<body bgcolor=pink>");
String uname=request.getParameter("txtName");
out.println("<h1>welcome "+uname+"</h1>");
Cookie ck1=new Cookie ("username",uname);
Cookie ck2=new Cookie("visit","1");
response.addCookie(ck1);
response.addCookie(ck2);
out.println("<h1><a href=cookiesservlet2>Click to visit second </a></h1>");
out.println("</body>");
out.println("</html>");
}
Cookiesservlet2.java
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 cookiesservlet2</title>");
out.println("</head>");
out.println("<body bgcolor=green>");
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 Number "+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=cookiesservlet3>Click to visit the third page</a></h1> ");
out.println("<h1><a href=cookiesservlet4>Click to visit the fourth page</a></h1> ");
out.println("<h1><a href=cookiesservlet5>Click to visit the fifth page</a></h1> ");
out.println("</body>");
out.println("</html>");
}}
Output-
PRACTICAL 2 (C)
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.
Source Code-
index.html
<html>
<head>
<title>Session</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="sessionServlet1" method="get">
enter user ID
<input type="text" name="txtName"><br>
<input type="reset">
<input type="submit">
</form></body></html>
sessionServlet1.java
public class sessionServlet1 extends HttpServlet {
}
out.println("<h1> session ID "+hs.getId()+"</h1>");
out.println("<h1> Logged in at "+new java.util.Date(hs.getCreationTime())+"</h1>");
out.println("<h1><a href=sessionServlet2>Click to visit the second page</a></h1> ");
out.println("<h1><a href=cookiesservlet4>Click to visit the fourth page</a></h1> ");
out.println("<h1><a href=cookiesservlet5>Click to visit the fifth page</a></h1> ");
out.println("<h1><a href=logoutservlet2>Click to Terminate</a></h1> ");
out.println("</body>");
out.println("</html>");
}
}
sessionServlet2.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class sessionServlet2 extends HttpServlet {
QuestionAnswerServlet2.java
public class QuestionAnswerServlet2 extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
try {
Class.forName("com.mysql.jdbc.Driver");
try {
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/zakjavadb", "root",
"root");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select answer from quiz_table");
int count=0;
int qno=0;
while(rs.next())
{
if(rs.getString(1).equals(request.getParameter(""+(++qno))))
{count++;
out.println("<h1>Correct!</h1>");
}
else
{ out.println("<h1>Incorrect!</h1>"); } }
out.println("Your total score is: " +count+"</h1>");
} catch (SQLException ex) {
Logger.getLogger(QuestionAnswerServlet2.class.getName()).log(Level.SEVERE,
null, ex);
}
} catch (ClassNotFoundException ex) {
out.println("" +ex); }}}
Output-
PRACTICAL 4(A)
Aim-Develop a simple JSP application to display values obtained from the use of intrinsic
objects of various types.
Source Code-
Intrinsic_objects_jsp.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Use of Intrinsic Objects</title>
</head>
<body>
<h1> Request Object</h1><br>
Query String <%= request.getQueryString() %><br>
Context Path <%= request.getContextPath() %><br>
Remote Host <%= request.getRemoteHost() %><br><br>
<h1>Response Object</h1><br>
Character Encoding Type <%= response.getCharacterEncoding() %><br>
Content Type <%= response.getContentType() %><br>
Locale <%= response.getLocale() %><br><br>
<h1>Session Object </h1><br>
ID<%= session.getId() %><br>
Creation Time <%= new java.util.Date(session.getCreationTime()) %><br>
Last Access Time <%= new java.util.Date(session.getLastAccessedTime()) %><br><br>
<h1>Use of Out Object</h1><br>
<% out.println("This is an example "); %><br><br>
<h1>Use of Config Object</h1><br>
<%=config.getServletName() %><br><br>
</body></html>
Output-
PRACTICAL 4(B)
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).
Source 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>
<h1>Registration Form with Validations</h1>
<form action="validate.jsp" method="post">
<table style="width: 30%"
<tr>
<td>Enter Full Name
<td><input type="text" name="fullname">
</tr>
<tr>
<td>Enter Age
<td><input type="text" name="age">
</tr>
<tr>
<td>Enter E-mail
<td><input type="text" name="email">
</tr>
<tr>
<td>Enter Gender
<td><input type="radio" name="gender" value="male">Male
<td><input type="radio" name="gender" value="female">Female
</tr>
<tr>
<td>Enter Hobbies
<td><input type="checkbox" name="hb" value="Singing">Singing
<input type="checkbox" name="hb" value="Reading">Reading
<input type="checkbox" name="hb" value="Acting">Acting
</tr>
</table><br>
<input type="submit" value="Click to submit ">
</body>
</html>
validate.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<%!
int ageInNumbers;
String EMAIL_REGEX="^[\\w-\\+]+(\\.[\\w]+)*@[\\w-]+(\\.[\\w]+)*(\\.[a-z]{2,})$";
%>
<%
String name=request.getParameter("fullname");
String age=request.getParameter("age");
String email=request.getParameter("email");
String gender=request.getParameter("gender");
String hb[]=request.getParameterValues("hb");
String nothing="";
if(name.equals(nothing))
{
out.println("<font color=red> Please fill all the fields! </font><br>");
}
if(!email.matches(EMAIL_REGEX))
{
out.println("<font color=red> Please enter the correct email address!
</font><br>");
}
ageInNumbers=Integer.parseInt(age.trim());
if(ageInNumbers<18&&ageInNumbers>60)
{
out.println("<font color=red> Please enter the correct age! </font><br>");
}
%>
<br><br>
Your entered information is <br>
Full Name <%= name %><br>
Age <%= age %><br>
E-mail <%= email %><br>
Gender <%= gender %><br>
Hoobies
<%
if(hb!=null && hb.length!=0)
{
for(int i=0;i<hb.length;i++)
{
out.println(hb[i]);
}
}
%>
Output-
PRACTICAL 4(C)
Aim-Create a registration and login JSP application to register and authenticate the user
based on username and password using JDBC.
Source Code-
index.html
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<a href="login.html">LOGIN</a><br>
<a href="register.html">REGISTER</a>
</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>
<form action="loginJSP.jsp" method="post">
NAME:<input type="text" name="userid">
PASSWORD:<input type="text" name="password1">
confirm password:<input type="text" name="password2">
<input type="submit" value="submit">
</form>
</body></html>
loginJSP.jsp
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.*"%>
<%@page import="java.sql.Statement"%>
<%@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>
<%
String uname=request.getParameter("userid");
String pwd1=request.getParameter("password1");
String pwd2=request.getParameter("password2");
if(pwd1.equals(pwd2))
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=
DriverManager.getConnection("jdbc:mysql://localhost:3306/login_reg_4(c)_database","roo
t","root");
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>
<form action="register.jsp" method="post"><br>
USER NAME<input type="text" name="uname"><br>
PASSWORD <input type="text" name="pass1"><br>
confirm password <input type="text" name="pass2"><br>
<input type="submit" value="submit">
</form>
</body>
</html>
register.jsp
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Connection"%>
<%@page import="javax.sql.*"%>
<%@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 user =request.getParameter("uname");
String password1 =request.getParameter("pass1");
String password2 =request.getParameter("pass2");
if(password1.equals(password2))
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=
DriverManager.getConnection("jdbc:mysql://localhost:3306/login_reg_4(c)_database","roo
t","root");
PreparedStatement ps=con.prepareCall("insert into login_reg_table values(?,?,?)");
ps.setString(1,user);
ps.setString(2,password1);
ps.setString(3,password2);
ps.executeUpdate();
out.println("registered successfully");
}
else { out.println("registered not successfully done"); }
%>
<br><a href="login.html">LOGIN</a><br>
<a href="index.html">HOME</a><br>
</body> </html>
Output-
register.html
login.html
update.jsp
<%@page import="java.sql.ResultSet"%>
<%@page import="java.lang.System.* "%>
<%--@page import="java.lang.System.out" --%>
<%@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>
<%
String eno=request.getParameter("eno");
String name=request.getParameter("ename");
String age=request.getParameter("age");
String desg=request.getParameter("desg");
String sal=request.getParameter("salary");
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/zakjavadb","root","root");
PreparedStatement ps=con.prepareStatement("update update_table set
name=?,age=?,desg=?,salary=? where eno=?");
ps.setString(1,name);
ps.setString(2,age);
ps.setString(3, desg);
ps.setString(4, sal);
ps.setString(5,eno);
ps.executeUpdate();
%>
</body>
</html>
Output-
Table before updating
(ii)
index2.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>5A2</title>
</head>
<body>
<%
application.setAttribute("author","zak");
application.setAttribute("site","The Underrated Marvel ");
%>
<a href="display2.jsp">Click </a>
</body>
</html>
display2.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1> Author Name ${applicationScope.author} <br></h1>
<h1> Book Name ${applicationScope.site}</h1>
</body>
</html>
Output-
PRACTICAL 5(C)
Aim-Create a JSP application to demonstrate the use of JSTL.
Source Code-
(i)Displaying table from Database Using JSTL
db_page.jsp
<%@page import="java.io.* ,java.util.*,java.sql.*" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
<%@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>
<sql:setDataSource var="db" driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/zakjavadb" user="root" password="root"/>
<sql:query dataSource="${db}" var="rs">
select * from student2;
</sql:query>
<table border="1" width="100%">
<tr>
<th>Student ID
<th>First Name
<th>Last Name
<th>Age
</tr>
<c:forEach var="table" items="${rs.rows}">
<tr>
<td><c:out value="${table.id}"/>
<td><c:out value="${table.first_name}"/>
<td><c:out value="${table.last_name}"/>
<td><c:out value="${table.age}"/>
</tr>
</c:forEach>
</table>
</body>
</html>
Output-
delete_jstl.jsp
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
<%@page import =" javax.servlet.http.*,javax.servlet.*"contentType="text/html"
pageEncoding="UTF-8"%>
<%@page import="java.io.*,java.util.*,java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<sql:setDataSource var="db" driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/zakjavadb" user="root" password="root"/>
<c:set var="id" value="8212"/>
<sql:update dataSource="${db}" var="count">
delete from student2 where id=?
<sql:param value="${id}"/>
</sql:update>
<sql:query dataSource="${db}" var="rs">
select * from student2;
</sql:query>
<table border="1" width="100%">
<tr>
<th>Student ID
<th>First Name
<th>Last Name
<th>Age
</tr>
<c:forEach var="table" items="${rs.rows}">
<tr>
<td><c:out value="${table.id}"/>
<td><c:out value="${table.first_name}"/>
<td><c:out value="${table.last_name}"/>
<td><c:out value="${table.age}"/>
</tr>
</c:forEach>
</table>
</body>
</html>
Output-
PRACTICAL 6(A)
Aim-Create a Currency Converter application using EJB.
Source code-
Index.html
<!DOCTYPE html>
<html>
<head><title>Currency Converter</title>
</head>
<body>
<form action="CCServlet" >
Enter Amount To Convert <input type="text" name="amt"><br>
Select Conversion Type<br>
<input type="radio" name="type" value="r2d" checked>Rupees to Dollar<br>
<input type="radio" name="type" value="d2r" >Dollar to Rupees<br>
<input type="reset" ><br><input type="submit" value="CONVERT" >
</form>
</body>
</html>
CCServlet.java
package mypack;
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 mybeans.CCBean;
public class CCServlet extends HttpServlet {
@EJB CCBean obj;
protected void processRequest(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
double amt = Double.parseDouble(request.getParameter("amt"));
if(request.getParameter("type").equals("r2d"))
{
out.println("<h1>"+amt+ " Rupees = "+obj.r2Dollar(amt)+" Dollors</h1>");
}
if(request.getParameter("type").equals("d2r"))
{
out.println("<h1>"+amt+ " Dollors = "+obj.d2Rupees(amt)+" Rupees</h1>");
}}}
CCBean.java
package mybeans;
import javax.ejb.Stateless;
@Stateless
public class CCBean {
public CCBean(){}
public double r2Dollar(double r){ return r/65.65; }
public double d2Rupees(double d){ return d*65.65; }
}
Output-
PRACTICAL 6(B)
Aim-Develop a Simple Room Reservation System Application Using EJB.
Source 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>
<h1>Enter Details for Room Reservation </h1>
<form method="post" action="ReservServ1">
Customer Name:<input type="text" name="cname"/>
Address:<input type="text" name="cadd"/>
Phone No:<input type="text" name="cphno"/>
Room Type:
<select name="roomtype">
<option id="g">General
<option id="d">Deluxe
<option id="s">Suite
</select><br>
Check-In date: <input type="text" name="chkindate"/>
Check-Out date: <input type="text" name="chkoutdate"/>
Payment Mode:
<select name="paymode">
<option id="cash">Cash
<option id="credit">Credit Card
</select><br>
<input type="submit" value="Click to Reserve"/>
<input type="reset" value="Clear All">
</form>
</body>
</html>
ReservationBean.java
package ejb;
import java.util.ArrayList;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
@Stateless
@LocalBean
public class ReservationBean {
public String welcome(String customer)
{ return "Hello "+" "+customer.toUpperCase()+" "+"Welcome to our Hotel"; }
public String roomtype(String roomtype)
{
return "You have selected "+roomtype.toUpperCase()+" "+"Room";
}
public String payment(String roomtype)
{
System.out.println(roomtype);
if(roomtype.equalsIgnoreCase("SUITE"))
return "You have to pay Rs 8000";
else if(roomtype.equalsIgnoreCase("DELUXE"))
return "You have to pay Rs 4000";
else
return "You have to pay Rs 2000";
}
public ArrayList<String> reserv(String customer, String addr, String ph, String checkin,
String checkout, String roomtype, String paymode)
{
ArrayList<String> a=new ArrayList();
a.add(customer);
a.add(addr);
a.add(ph);
a.add(checkin);
a.add(checkout);
a.add(roomtype);
a.add(paymode);
return a;
}
}
ReservServ1.java
package Servlet;
import ejb.ReservationBean;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ReservServ1 extends HttpServlet {
@EJB ReservationBean bean;
protected void processRequest(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String cname,cadd,cphno,roomtype,chkindate,chkoutdate,paymode;
cname=request.getParameter("cname");
cadd=request.getParameter("cadd");
cphno=request.getParameter("cphno");
roomtype=request.getParameter("roomtype");
chkindate=request.getParameter("chkindate");
chkoutdate=request.getParameter("chkoutdate");
paymode=request.getParameter("paymode");
PrintWriter out=response.getWriter();
int i=0;
ArrayList<String> list1=bean.reserv(cname, cadd, cphno, chkindate, chkoutdate,
roomtype,paymode);
try
{
bean.reserv(cname, cadd, cphno, chkindate, chkoutdate, roomtype, paymode);
out.println(bean.welcome(cname)+"<br/>");
out.println(bean.roomtype(roomtype) +"<br/>");
out.println(bean.payment(roomtype) +"<br/>");
out.println("Customer Details:");
int n=list1.size();
out.println("<table border=1>");
out.println("<tr><th>Name</th><th>Address</th><th>Phone
No</th><th>Check-Indate</th><th>Check-Out date</th><th>Room type</th><th>Payment
Mode</th></tr>");
out.println("<tr>");
for(i=0;i<n;i++)
{
out.println("<td>");
out.println(list1.get(i));
out.println("</td>");
}
out.println("</tr></table>");
out.println("<br/>Click <a href='index.jsp'> here </a> to go back");
}
finally
{
out.close();
}
}
Output-
PRACTICAL 6(C)
Aim- Develop simple shopping cart application using EJB [Stateful Session Bean]
Source Code-
Index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="javax.naming.directory.InitialDirContext"%>
<%@page import="javax.naming.InitialContext"%>
<%@page import="java.util.Iterator"%>
<%@page import="java.util.List"%>
<%@page import="ejb.ShoppingCart"%>
<!DOCTYPE html>
<%!
private static ShoppingCart cart;
public void jspInit()
{
try{
InitialContext ic=new InitialContext();
cart=(ShoppingCart)ic.lookup("java:global/ShoppingCart/ShoppingCart");
}
catch(Exception e)
{
System.out.println("Could not create bean");
}
cart.initialize("Guest");
}
%>
<%
if(request.getParameter("txtcustname")!=null)
cart.initialize(request.getParameter("txtcustname"));
else
cart.initialize("Guest");
%>
<%
if (request.getParameterValues("btnremove")!=null)
{
String books[]=request.getParameterValues("chkbook");
if(books!=null)
{
for(int i=0;i<books.length;i++)
cart.removebook(books[i]);
}}
if(request.getParameter("btnadd")!=null)
{
String books[]=request.getParameterValues("chkbook");
if(books!=null)
{
for(int i=0;i<books.length;i++)
cart.addbook(books[i]);
}
}
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Shopping Cart</h1>
<form name="frmbooks" method="post">
Customer:
<input type="text" name="txtcustname" value="<
%request.getParameter("txtcustname");%>"/><br/>
Book Titles:<br/>
<input type="checkbox" name="chkbook" value="C Programming"/>C
Programming<br/>
<input type="checkbox" name="chkbook" value="C++ Programming"/>C++
Programming<br/>
<input type="checkbox" name="chkbook" value="Java Programming"/>Java
Programming<br/>
<input type="checkbox" name="chkbook" value="HTML"/>HTML<br/>
<input type="submit" value="Add" name="btnadd"/>
<input type="submit" value="Remove" name="btnremove"/>
<input type="submit" value="Show" name="btnshow"/>
<br/>
<table border="1">
<tr>
<td>Basket
</tr>
<%
if(request.getParameter("btnshow")!=null)
{
List<String>booklist=cart.getContents();
Iterator iterator=booklist.iterator();
while(iterator.hasNext())
{
String title=(String)iterator.next();
%>
<tr>
<td><%=title %>
</tr>
<%
}}
%>
</table>
</form>
</body>
</html>
ShoppingCart.java
package ejb;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Local;
import javax.ejb.Remove;
import javax.ejb.Stateful;
/**
*
* @author PC28
*/
@Stateful
public class ShoppingCart
{
List<String>contents;
String custname;
Connection con=null;
ResultSet rs;
Statement st=null;
public void initialize(String person)
{
if(person!=null)
{
custname=person;
try{
try {
Class.forName("com.mysql.jdbc.Driver");
try {
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/zakdb","root","1234");
}
catch(Exception e){
System.out.println("Connection Failed");
}
}
contents=new ArrayList<String>();
}
public void addbook(String title)
{
try{
st=con.createStatement();
st.executeUpdate("insert into cart values('"+custname+"','"+title+"')");
}
catch(Exception e)
{
System.out.println("Failed to insert values to the database ");
}
}
public void removebook(String title)
{
try{
st=con.createStatement();
st.executeUpdate("'delete from cart where username='"+custname+"'and
itemname='"+title+"'");
}
catch(Exception e ){
System.out.println("Deletion failed");
}
}
public List<String>getContents()
{
try
{
st=con.createStatement();
rs=st.executeQuery("select * from cart where username='"+custname+"'");
while(rs.next())
{
contents.add(rs.getString("itemname"));
System.out.println(rs.getString("itemname"));
}
}
catch(Exception e)
{
System.out.println("Selection Failed");
}
return contents;
}
@Remove
public void remove()
{
contents=null;
}
}
Output-
PRACTICAL 7(A)
Aim-Develop simple EJB application to demonstrate Servlet Hit count using Singleton
Session Beans.
Source Code-
CntServletHitBeans.java(session bean)
package ejb;
import javax.ejb.Singleton;
@Singleton
public class CntServletHitsBean {
private int hitcnt;
public int getHitCnt()
{
return hitcnt++;
}
}
ServletClient.java
The servlet client.java file should be created in the same folder as the index.jsp that is
Web pages folder
package servlet;
import ejb.CntServletHitsBean;
import java.io.IOException;
import java.io.PrintWriter;
import static java.lang.System.out;
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 java.sql.*;
import javax.ejb.Stateless;
@Stateless
public class MarksEntry {
public void entry (String srollno,String sname,String p1,String p2,String p3,String p4,String
p5)
{
Connection con=null;
Statement st=null;
ResultSet rs=null;
try{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/
student_database","root","1234");
st=con.createStatement();
st.executeUpdate("insert into marks
values('"+srollno+"','"+sname+"','"+p1+"','"+p2+"','"+p3+"','"+p4+"','"+p5+"')");
}
catch(Exception e)
{System.out.println(e);
}
}
public String submit(String name)
{
return name.toUpperCase()+" s record is submitted";
}}
MarkentryServ.java(servlet page)
package Servlet;
import ejb.MarksEntry;
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 org.jboss.weld.util.bytecode.DescriptorUtils;
@WebServlet(name = "MarkentryServ", urlPatterns = {"/MarkentryServ"})
public class MarkentryServ extends HttpServlet {
@EJB MarksEntry bean;
protected void processRequest(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
String id,name,p1,p2,p3,p4,p5;
id=request.getParameter("txtno");
name=request.getParameter("txtname");
p1=request.getParameter("txtp1");
p2=request.getParameter("txtp2");
p3=request.getParameter("txtp3");
p4=request.getParameter("txtp4");
p5=request.getParameter("txtp5");
bean.entry(id, name, p1, p2, p3, p4, p5);
out.println(bean.submit(name));
}
}}
Output-
After putting the values and clicking submit .”the user name will appear in upper case:
PRACTICAL 8(A)
Aim-Develop a simple Inventory Application Using JPA.
Source 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>
<h1>Welcome to ShopAnything Store</h1>
Display <a href="display.jsp"> Click Here </a><br>
Update <a href="update.jsp"> Click Here </a><br>
Delete <a href="deletedb.jsp"> Click Here </a>
Insert<a href="insert.jsp"> Click Here </a>
</body>
</html>
Insert.jsp
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form action="insertdb.jsp" method="post">
<h1> Insert a product</h1>
<table border="2">
<tr>
<td>Enter product Name </td>
<td> <input type="text" name="pname"></td>
</tr>
<tr>
<td>Enter product Quantity </td>
<td> <input type="text" name="quantity"></td>
</tr>
</table><br><br>
<input type="submit" value="submit to insert">
</form>
<font color="red">
<c:if test="${not empty param.errMsg}">
<c:out value="${param.susMsg}"/><br>
</c:if>
</font>
<a href="index.jsp">Go Back</a>
</body>
</html>
Insertdb.jsp
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<%@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>
<c:if test="${empty param.pname or empty param.quantity}">
<c:redirect url="insert.jsp">
<c:param name="errMsg" value="Please Enter all the fields to insert a product"/>
</c:redirect>
</c:if>
<sql:setDataSource var="dbsource" driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/zakdb" user="root" password="root"/>
<sql:update dataSource="${dbsource}" var="result">
insert into product (pname,quantity)values(?,?);
<sql:param value="${param.pname}"/>
<sql:param value="${param.quantity}"/>
</sql:update>
<c:if test="${result>=1}">
<font size="5" color="green">Congratulations!Data Inserted!
</font>
<c:redirect url="insert.jsp">
<c:param name="susMsg" value="Congratulations! Data inserted successfully!">
</c:param></c:redirect>
</c:if> </body></html>
Update.jsp
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<%@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>
<sql:setDataSource var="dbsource" driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/zakdb" user="root" password="root"/>
<sql:query dataSource="${dbsource}" var="result">
select * from product where id=?;
<sql:param value="${param.id}"/>
</sql:query>
<form action="updatedb.jsp" method='post'>
<table border='0' width='40%'>
<caption>Update Product</caption>
<tr>
<th>Product Name</th>
<th>Quantity </th>
</tr>
<c:forEach var="row" items="${result.rows}">
<tr>
<td><input type="hidden" value="${param.id}" name="id"/></td>
<td><input type="text" value="${row.pname}" name="pname"/></td>
<td><input type="text" value="${row.quantity}" name="quantity"/></td>
<td><input type="submit" value="Update"/></td>
</tr>
</c:forEach>
</table>
<a href="index.jsp">Go Home</a>
</form></body></html>
Updatedb.jsp
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<%@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>
<sql:setDataSource var="dbsource" driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/zakdb" user="root" password="root"/>
<sql:update dataSource="${dbsource}" var="count">
update product set pname=?, quantity=? where id='${param.id}'
<sql:param value="${param.pname}"/>
<sql:param value="${param.quantity}"/>
</sql:update>
<c:if test="${count>=1}">
<font size='5' color='green'>Congratulations!Data Updated!</font>
<a href="index.jsp">Go Home</a>
</c:if> </body></html>
Deletedb.jsp
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<%@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>
<sql:setDataSource var="dbsource" driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/zakdb" user="root" password="root"/>
<sql:update dataSource="${dbsource}" var="count">
delete from product where id='${param.id}';
</sql:update>
<c:if test="${count>=1}">
<font size="5" color='green'>Congratulations!Data Deleted successfully</font>
<a href="index.jsp">Go Home </a>
</c:if> </body></html>
Output-
Index.jsp
Display.jsp
Update.jsp
Insert.jsp
Deletedb.jsp
PRACTICAL 9(B)
Aim-Develop a Hibernate application to store Feedback of Website Visitor in MySQL
Database
Source Code-
Index.html
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="insert.jsp">
<h3>Enter your name</h3>
<input type="text" name="txtName">
<h3>Enter your Feedback</h3>
<textarea cols="15" rows="15" name="txtFeed"></textarea>
<input type="submit" value="submit"/>
</form>
</body>
</html>
Insert.jsp
<%@page import="mypack.VisitBean"%>
<%@page import="org.hibernate.Transaction"%>
<%@page import="org.hibernate.cfg.Configuration"%>
<%@page import="org.hibernate.SessionFactory"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%!
SessionFactory sf;
org.hibernate.Session hibSession;
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
sf=new Configuration().configure().buildSessionFactory();
hibSession=sf.openSession();
Transaction tx=null;
VisitBean eb=new VisitBean();
try
{
tx=hibSession.beginTransaction();
eb.setName(request.getParameter("txtName"));
eb.setFeedback(request.getParameter("txtFeed"));
hibSession.save(eb);
tx.commit();
out.println("<h1>record inserted successfully ");
out.println("<a href='fetch.jsp'>Click here</a>");
}
catch(Exception e)
{
out.println(e);
}
%>
</body>
</html>
VisitBean.java
package mypack;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.*;
@Entity
@Table(name="visitor")
public class VisitBean implements Serializable {
@Id
@GeneratedValue
@Column(name="id")
private String id;
@Column(name="vname")
private String name;
@Column(name="feedback")
private String feedback;
public VisitBean(){}
public VisitBean(String name, String feedback){
this.name=name;
this.feedback=feedback;
}
public String getId()
{
return id;
}
public String getName()
{
return name;
}
public String getFeedback()
{ return feedback; }
public void setId(String id1)
{ id=id1; }
public void setName(String name1)
{ name=name1; }
public void setFeedback(String f)
{ feedback=f; } }
Fetch.jsp
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
<%@page import =" javax.servlet.http.*,javax.servlet.*"contentType="text/html"
pageEncoding="UTF-8"%>
<%@page import="java.io.*,java.util.*,java.sql.*" %>
<!DOCTYPE html>
<html> <head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head> <body>
<sql:setDataSource var="db" driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/visitordb" user="root" password="1234"/>
<sql:query dataSource="${db}" var="rs">
select * from visitor;
</sql:query>
<table border="1" width="75%">
<tr>
<th>Visitor Id
<th>Visitor Name
<th>Visitor Feedback
</tr>
<c:forEach var="table" items="${rs.rows}">
<tr>
<td><c:out value="${table.id}"/>
<td><c:out value="${table.vname}"/>
<td><c:out value="${table.feedback}"/>
</tr>
</c:forEach>
</table>
</body>
</html>
Output-
PRACTICAL 9(C)
Aim-Develop a Hibernate application to store and retrieve employee details in MySQL
Database.
Source Code-
Index.html
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="insert.jsp">
<table border="1">
<tr><td>Enter Employee Name</td>
<td><input type="text" name="txtName"></td></tr>
<tr><td>Enter Employee Designation</td>
<td><input type="text" name="txtDes"></td></tr>
<tr><td>Enter Employee Department</td>
<td><input type="text" name="txtDept"></td></tr>
<tr><td>Enter Employee Salary</td>
<td><input type="text" name="txtSal"></td></tr>
<tr><td><input type="reset"></td>
<td><input type="submit" value="register"></td></tr>
</table>
</form>
</body>
</html>
Insert.jsp
<%@page import="mypack.EmpBean"%>
<%@page import="org.hibernate.Transaction"%>
<%@page import="org.hibernate.cfg.Configuration"%>
<%@page import="org.hibernate.SessionFactory"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%!
SessionFactory sf;
org.hibernate.Session hibSession;
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
sf=new Configuration().configure().buildSessionFactory();
hibSession=sf.openSession();
Transaction tx=null;
EmpBean eb=new EmpBean();
try
{
tx=hibSession.beginTransaction();
eb.setName(request.getParameter("txtName"));
eb.setDesg(request.getParameter("txtDes"));
eb.setDept(request.getParameter("txtDept"));
eb.setSal(request.getParameter("txtSal"));
hibSession.save(eb);
tx.commit();
out.println("<h1>record inserted successfully ");
out.println("<a href='fetch.jsp'>Click here</a>");
}
catch(Exception e)
{
out.println(e);
}
%>
</body>
</html>
EmpBean.java
package mypack;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.*;
@Entity
@Table(name="emptab")
public class EmpBean implements java.io.Serializable
{
@Id
@GeneratedValue
@Column(name="EmpId")
private String no;
@Column (name="EmpName")
private String name;
@Column (name="EmpDesg")
private String desg;
@Column (name="EmpDept")
private String dept;
@Column (name="EmpSal")
private String sal;
public EmpBean()
{}
public EmpBean(String en, String ed1, String ed2, String es)
{
this.name=en;
this.dept=ed2;
this.desg=ed1;
this.sal=es;
}
public String getNo()
{ return no; }
public String getName()
{ return name;}
public String getDesg()
{ return desg; }
public String getDept()
{ return dept; }
public String getSal()
{ return sal;}
public void setNo(String n)
{ no=n; }