0% found this document useful (0 votes)
45 views

Wake To Reality - Java

The document describes creating a simple JSP application that displays values obtained from intrinsic objects like request, response, out, configuration, application, page, session and pageContext. The index.jsp page uses these intrinsic objects to print information like local address from request, servlet name from configuration, server info from application etc. It also sets an attribute in pageContext and prints its class name.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views

Wake To Reality - Java

The document describes creating a simple JSP application that displays values obtained from intrinsic objects like request, response, out, configuration, application, page, session and pageContext. The index.jsp page uses these intrinsic objects to print information like local address from request, servlet name from configuration, server info from application etc. It also sets an attribute in pageContext and prints its class name.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

Practical 1

Create a Servlet application to perform calculator basic operations or

Create simple Servlet application to demonstrate working of calculator

index.html

<html>

<head>

<title>TODO supply a title</title>

<meta charset="UTF-8">

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

</head>

<body>

<form method=post action="ca">

NO-1 <input type=text name="t1">

NO-2 <input type=text name="t2"> <br> <br>

<input type=submit value="+" name="btn">

<input type=submit value="-" name="btn">

<input type=submit value="*" name="btn">

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

</form>

</body>

</html>

ca.servlet

package ty;

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

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

@Override

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

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

try (PrintWriter out = response.getWriter())

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

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

int c=0;

String op=request.getParameter("btn");

if (op.equals("+"))

c=a+b;

else if (op.equals("-"))

c=a-b;

else if (op.equals("*"))

c=a*b;

else if (op.equals("/"))

c=a/b;

out.println("<b>"+a+op+b+" = "+c+"<b>");

Output :
Q.1 b) Create a servlet for a login page. If the username and password are correct
then it says message “Hello ” else a message “login failed”.

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="ls" method="post">

UserName : <input type="text" name="uname"><br>

Password : <input type="password" name="pw"> <br>

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

</form>

</body>

</html>

ls.servlet

package ty;

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class ls extends HttpServlet {

@Override

public void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

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

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

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

String password=request.getParameter("pw");

String msg="";

if (username .equals("admin") && password.equals("admin123"))

msg="Hello "+username;

else

msg="Login failed";

out.println("<b>"+msg+"<b>");

Output :
Q.1 c) Create a registration servlet in Java using JDBC. Accept the details such
as Username, Password, Email, and Country from the user using HTML Form
and store the registration details in the database.

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="RegistrationServlet" method="post">
User name : <input type="text" name="uname"> <br>
Password : <input type="password" name="pw"><br>
Email Id : <input type="text" name="email"> <br>
Country : <select name="coun">
<option>select...
<option> India
<option> Bangladesh
<option> Bhutan
<option> Canada
</select> <br>
<input type="submit" value=" Register">
</form>
</body>
</html>

RegistrationServlet.java
import java.io.*;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class RegistrationServlet extends HttpServlet
{@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
IOException, ServletException
{ Connection con=null;
PreparedStatement ps=null;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String username=request.getParameter("uname");
String password=request.getParameter("pw");
String emailid=request.getParameter("email");
String country=request.getParameter("coun");
try
{ Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/registerdb","root","root123");
out.println("connection done successfully...");
ps=con.prepareStatement("insert into register values (?,?,?,?)");
ps.setString(1,username);
ps.setString(2,password);
ps.setString(3,emailid);
ps.setString(4,country);
ps.execute();
out.print("Data insserted successfully!!!!");
}
catch(ClassNotFoundException | SQLException e) { out.println(e); }
out.println("<b>"+"<b>");
}
}

OUTPUT:
PRACTICAL 2

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

Index.html
<html>

<head>

<title>TODO supply a title</title>

<meta charset="UTF-8">

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

</head>

<body>

<form method="Post" action="vs">

User Name: <input type="text" name ="un"><br>

Password: <input type="password" name ="pw"><br>

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

</form>

</body>

</html>

vs.servlet

package ty;

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

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

@Override

public void doPost(HttpServletRequest req, HttpServletResponse res)

throws ServletException, IOException {

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

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

String username=req.getParameter("un");

String password=req.getParameter("pw");

if(password.equals("ser"))

req.setAttribute("s1username",username);

req.setAttribute("s1password",password);

RequestDispatcher rd= req.getRequestDispatcher("/wc");

rd.forward(req, res);

else

out.print("Incorrect password");

RequestDispatcher rd= req.getRequestDispatcher("/index.html");

rd.include(req, res);

wc.servlet

package ty;

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class wc extends HttpServlet {

@Override

public void doPost(HttpServletRequest req, HttpServletResponse res)

throws ServletException, IOException {

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

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

res.setContentType("text/html");

String s2username = (String)req.getAttribute("s1username");

String s2password = (String)req.getAttribute("s2password");

out.println("Welcome "+s2username);

Output :
Q.2 b) Create a servlet that uses Cookies to store the number of times a user has
visited servlet.

index.html

<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form method="Post" action="coo">
<input type="submit" value="button">
</form>
</body>
</html>
coo.servlet
package ty;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class coo extends HttpServlet {
private int i=1;
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
String k=String.valueOf(i);
Cookie c = new Cookie("visit",k);
response.addCookie(c);
int j=Integer.parseInt(c.getValue());
if(j==1)
{
out.println("This is the first time you are visiting this page");
}
else
{ synchronized(coo.this)
{ out.println("You visited this page "+i+" times");
}
}
i++;
}
}
}

Output :
Practical 4 a)

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

index.jsp

<%@page import="java.io.PrintWriter"%>

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

<% PrintWriter wrt =response.getWriter();

wrt.print("use of the Response Object Writer example "); %><br> <br>

<strong>use of Request Object -locale example:

</strong><%=request.getLocalAddr().toString() %> <br> <br>

<strong>use of Out object prints :

< %out.print("this is an example");%> <br> <br>

<strong>Use of Configuration object - servlet name:</strong>

<%=config.getServletName()%> <br> <br>

<strong>Use of Application object - server info:</strong>

<%=application.getServerInfo()%> <br> <br>

<strong>Use of page object - page name:</strong>


<%=page.getClass().getName()%> <br> <br>

<strong>Use of Session object - creation time:</strong>

<%=session.getCreationTime()%> <br> <br>

<% pageContext.setAttribute("Test","Test Value");%>

<strong>Use of Page Context object - class name:</strong>

<%=pageContext.getClass().getName()%> <br> <br>

</body>

</html>

Output :
Q.4 c) Create a registration and login JSP application to register and authenticate
the user based on username and password using JDBC. Or

Develop a JSP application to allow the user to modify the registration details
after the valid authentication.

login.html
<html>
<body>
<h1>Login Page</h1>
<form action="login.jsp">
Enter User Name<input type="text" name="txtName"><br>
Enter Password<input type="password" name="txtPass"><br>
<input type="submit" value="~~~LOGIN~~"><input type="reset">
</form>
</body>
</html>

index.html
<html>
<head>
<title>New User Registration Page</title>
</head>
<body>
<form action="Registration.jsp">
<h1>New User Registration Page</h1>
Enter User Name<input type="text" name="txtName"><br>
Enter Password<input type="password" name="txtPass1"><br>
Re-Enter Password<input type="password" name="txtPass2"><br>
Enter Email<input type="text" name="txtEmail"><br>
Enter Country Name<select name="txtCon">
<option>India</option>
<option>France</option>
<option>England</option>
<option>Argentina</option>
</select><br>
<input type="submit" value="REGISTER"><input type="reset">
</form>
</body>
</html>

login.jsp
<%@page contentType="text/html" import="java.sql.*"%>
<html><body>
<h1>Registration JSP Page</h1>
<%
String uname=request.getParameter("txtName");
String pass1=request.getParameter("txtPass");
ResultSet rs=null;
try{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/login","root","root123");
Statement stmt=con.createStatement();
rs=stmt.executeQuery("select password from pass1 where uname='"+uname+"'");
rs.next();
if(pass1.equals(rs.getString(1)))
{
out.println("<h1>~~~LOGIN SUCCESSFULLL~~~</h1>");
}
else
{
out.println("<h1>password does not match!!!!!</h1>");
%>
<jsp:include page="index.html"></jsp:include>
<%
}
}catch(Exception e){
out.println("<h1>User does not exist!!!!!</h1>");
%>
<jsp:include page="index.html"></jsp:include>
<%
}
%>
</body>
</html>
Registration.jsp
<%@page contentType="text/html" import="java.sql.*"%>
<html><body>
<h1>Registration JSP Page</h1>
<%
String uname=request.getParameter("txtName");
String pass1=request.getParameter("txtPass1");
String pass2=request.getParameter("txtPass2");
String email=request.getParameter("txtEmail");
String ctry=request.getParameter("txtCon");
if(pass1.equals(pass2))
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/reg","root","root123");
PreparedStatement stmt=con.prepareStatement("insert into login values(?,?,?,?)");
stmt.setString(1,uname);
stmt.setString(2,pass1);
stmt.setString(3,email);
stmt.setString(4,ctry);
int row=stmt.executeUpdate();
if(row==1)
{
out.println("Registration Successful");}
else
{
out.println("Registration FAILED!!!!");
%>
<jsp:include page="index.html"></jsp:include>
<%
}
}catch(Exception e){out.println(e);}
}
else
{
out.println("<h1>Password Mismatch</h1>");
%>
<jsp:include page="index.html"></jsp:include>
<% }
%>
</body>
</html>
PRACTICAL 5

Q.5 a) Create an html page with fields, eno, name, age, desg, salary. Now on
submit this data to a JSP page which will update the employee table of database
with matching eno

Index.html
<!DOCTYPE html>
<html>
<body>
<form action="UpdateEmp.jsp" >
Enter Employee Number<input type="text" name="eno" ><br>
Enter Salary to update<input type="text" name="salary" ><br>
<input type="reset" ><input type="submit">
</form>
</body>
</html>

UpdateEmp.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>
<body>
<h1>Updating Employee Record</h1>
<%
String eno=request.getParameter("eno");
String salary = request.getParameter("salary");
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con
=DriverManager.getConnection("jdbc:mysql://localhost:3306/empdb","root","root123");
PreparedStatement stmt = con.prepareStatement("select * from emp where eno=?");
stmt.setString(1, eno);
ResultSet rs = stmt.executeQuery();
if(rs.next()){
out.println("<h1> Employee "+rs.getString(2)+" Exist </h1>");
PreparedStatement pst= con.prepareStatement("update emp set salary=? where eno=?");
pst.setString(1, salary);
pst.setString(2, eno);
pst.executeUpdate();
out.println("<h1>Employee Record updated !!!!!</h1>");
}
else{
out.println("<h1>Employee Record not exist !!!!!</h1>");
}
}catch(Exception e){out.println(e);}
%>
</body>
</html>
Q.5 b) Create a JSP page to demonstrate the use of Expression language.

index.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h3>welcome to index page</h3>
<%
session.setAttribute("user","Admin");
%>
<%
Cookie ck=new Cookie("name","mycookie");
response.addCookie(ck);
%>
<form action="ExpressionLanguage.jsp">
Enter Name:<input type="text" name="name" /><br/><br/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>

ExpressionLanguage.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
Welcome, ${ param.name }
Session Value is ${ sessionScope.user }
Cookie name is , ${cookie.name.value}

</body>
</html>

ELArithemeticOperator.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%-- arithmetic op --%>
5*5+4: ${5*5+4} <br>
1.4E4+1.4: ${1.4E4+1.4}<br>
10 mod 4: ${10 mod 4}<br>
15 div 3: ${15 div 3}<br>
</body>
</html>
ELLogicalOperator.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%-- LogicalOperator --%>
<h2>Logical Operator</h2>
true and true: ${true and true}<br>
true && false: ${true && false}<br>
true or true: ${true or true}<br>
true || false: ${true || false}<br>
not true: ${not true}<br>
!false: ${!false}
</body>
</html>
ELRelationalOperator.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%-- RelationalOperator --%>
<h2>Relational Operator</h2>
10.0==10: ${10.0==10} <br>
10.0 eq 10: ${10.0 eq 10} <br>
((20*10)!= 200): ${((20*10)!= 200)} <br>
3 ne 3: ${3 ne 3} <br>
3.2>=2: ${3.2>=2} <br>
3.2 ge 2: ${3.2 ge 2} <br>
2<3: ${2<3} <br>
4 lt 6: ${4 lt 6} <br>
2 <= 4: ${2 <= 4} <br>
4 le 2: ${4 le 2}
</body>
</html>

ELConditionalOperator.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h2>Conditional Operator</h2>
The result of 10>2 is: "${(10>1)?'greater':'lesser'}"
</body>
</html>

EmptyOperator.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<H1>Empty Operator Example</H1>
The Value for the Empty operator is:: ${empty "txxt"}
</body>
</html>

OUTPUT:
Q.5 c) Create a JSP page to demonstrate the use of Expression language.

index.html
<html><body>
<a href="setDemo.jsp"> SetDemo</a>
<a href="Maxif.html"> MaxIF</a>
<a href="forEachDemo.jsp"> ForEachDemo</a>
<a href="outDemo.jsp"> OutDemo</a>
<a href="URLDemo.jsp"> URLDemo</a>
<a href="choose_when_otherwise.jsp"> choose_when_otherwise</a>
</body></html>

setDemo.jsp
<%@taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<c:set var="pageTitle" scope="application"
value="Dukes Soccer League: Registration" />
${pageTitle}

Maxif.html
<form action ="IFDemo.jsp">
x=<input type="text" name="x" /><br>
y=<input type="text" name="y" /><br>
<input type="submit" value="Check Max" />
</form>

IFDemo.jsp
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="x" value="${param.x}"/>
<c:set var="y" value="${param.y}"/>
<c:if test="${x>y}">
<font color="blue"><h2>The Ans is:</h2></font>
<c:out value="${x} is greater than ${y}"/>
</c:if>
ForeachDemo.jsp
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:forEach begin="1" end="10" var="i">
The Square of <c:out value=" ${i}=${i*i}"/><br>
</c:forEach>

outDemo.jsp
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="name" value="John"/>
My name is: <c:out value= "${name}" />

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

choose_when_otherwise.jsp
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="income" value="${4000*4}"/>
Your Income is: <c:out value="${income}"/>
<c:choose>
<c:when test="${income <=1000}">
Income is not good
</c:when>
<c:when test="${income > 10000}">
Income is Very Good
</c:when>
<c:otherwise>
Income is undetermined
</c:otherwise>
</c:choose>

OUTPUT:
PRACTICAL 6

Q.6 a) Create a Currency Converter application using EJB.

Index.html
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html><head>
<meta http equiv="Content Type" content="text/html; charset=UTF-8">
<title>Currency Converter</title>
</head>
<body>
<h1>Currency Converter</h1>
<hr>
<p>Enter an amount to convert:</p>
<form method="post" action="ConvertCurrencyServlet">
<table style="width: 100%; padding: 0px; borderspacing: 0px; border:0px">
<tr><td> Convert: <br/>
<input type="text" name="amount" value="1" size="10" tabindex="1"/>
<div> Enter an amount </div>
</td>
</tr>
<tr><td> From this currency<br/>
<select name="From" size="3" tabindex="3">
<option value="USD">America (United States), Dollar(USD)</option>
<option value="INR">India, Rupee (INR)</option>
</select></tr>
<tr><td> To this currency:<br/>
<select name="To" size="3" tabindex="3"><option value="USD">America (United States), Dollar
(USD)</option>
<option value="INR">India, Rupee (INR)</option>
</select>
</td>
</tr>
<tr>
<td>
<input name="cmdSubmit" type="submit" value="submit" tabindex="4"/>
</td>
</tr>
</table>
</form>
</body>
</html>

ConvertCurrencyServlet.java
package servlet;

import ejb.CurrencyConverterBean;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
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;

@WebServlet(name = "ConvertCurrencyServlet", urlPatterns = {"/ConvertCurrencyServlet"})


public class ConvertCurrencyServlet extends HttpServlet {
@EJB
CurrencyConverterBean converterBean;

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
String amount = request.getParameter("amount");
if (amount != null && amount.length() > 0) {
BigDecimal d = new BigDecimal(amount);
BigDecimal convertedAmount = converterBean.convert(request.getParameter("From"),
request.getParameter("To"), d);
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Converted Currency</title>");
out.println("</head>");
out.println("<body>");
out.println(amount + " " + request.getParameter("From") + " = ");
out.println(convertedAmount + " " + request.getParameter("To"));
out.println("<br/>Click <a href='index.jsp'>here</a> to go back");
out.println("</body>");
out.println("</html>");
}
}
}
}

CurrencyConverterBean.java
package ejb;

import java.math.BigDecimal;
import javax.ejb.Stateless;

@Stateless
public class CurrencyConverterBean {
final private BigDecimal USD = new BigDecimal("0.0229137");
final private BigDecimal INR = new BigDecimal("46.589100");

public BigDecimal convert(String from, String to, BigDecimal amount) {


if(from.equals(to)) {
return amount;
} else {
BigDecimal toRate = findRate(to);
BigDecimal result = toRate.multiply(amount);
return result.setScale(2, BigDecimal.ROUND_UP);
}
}

public BigDecimal findRate(String to) {


BigDecimal returnValue = null;
if(to.equals("INR")) {
returnValue = INR;
}
if(to.equals("USD")) {
returnValue = USD;
}
return returnValue;
}
}
Q.6 b) Develop a Simple Room Reservation System Application

Using EJB.
CODE:

Index.html

<html>

<head>

<title>Room Reservation</title>

</head>

<body>

<form method="post" action="RoomClient">

<br> No of Rooms <input type=text name="t1">

<br> <input type="submit" name="btn" value="CheckIN">

<br> <input type="submit" name="btn" value="CheckOUT">

</form>

</body>

</html>

Step2: Create a session bean named as RoomBean in the package named ejb. Select the
option Stateless and click on Local Interface.

Here you will find two files created in the ejb package named as RoomBean.java and
RoomBeanLocal.java

RoomBeanLocal.java

package ejb;

import

javax.ejb.Local;

@Local

public interface RoomBeanLocal {

public int checkin(int no);

public int checkout(int no);


RoomBean.java

package ejb;

import javax.ejb.Stateless;

import java.sql.*;

@Stateless

public class RoomBean implements RoomBeanLocal {

public int checkin(int no) {

try

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

Connection
con=DriverManager.getConnection("jdbc:mysql://localhost/roomdb","root","tiger");

String sql1 = "select * from room";

Statement st=con.createStatement();

ResultSet rs=st.executeQuery(sql1);

rs.next();

int total=rs.getInt(1);

int occ=rs.getInt(2);

int free=total-occ;

System.out.println(total);

System.out.println(free);

if (free>=no)

String sql2="update room set occ=?";

PreparedStatement ps=con.prepareStatement(sql2);

ps.setInt(1, occ+no);
int res=ps.executeUpdate(); return res;

else return 0;

catch(Exception e)

return 0;

public int checkout(int no) {

try

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

Connection
con=DriverManager.getConnection("jdbc:mysql://localhost/roomdb","root","tiger");

String sql1 = "select * from room";

Statement st=con.createStatement();

ResultSet rs=st.executeQuery(sql1);

rs.next();

int total=rs.getInt(1);

int occ=rs.getInt(2);

if (occ>=no)

String sql2="update room set occ=?";

PreparedStatement ps=con.prepareStatement(sql2);

ps.setInt(1, occ-no);
int res=ps.executeUpdate();

return res;

else return 0;

catch(Exception e)

return 0;

Step 3: Create a Servlet file named as RoomClient. Do not click on web.xml (Deployment
Descriptor)

package servlet;

import ejb.RoomBeanLocal;

import java.io.*;

import javax.ejb.EJB;

import javax.servlet.*;

import javax.servlet.http.*;

import javax.servlet.annotation.*;

@WebServlet(name = "roomclient", urlPatterns = {"/roomclient"})

public class roomclient extends HttpServlet {

@EJB RoomBeanLocal obj;

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

try {

int no=Integer.parseInt(request.getParameter("t1"));
String b=request.getParameter("btn");

int res=0;

if(b.equals("CheckIN"))

res=obj.checkin(no);

if (res==1)

out.println(no + " rooms check-in");

if(b.equals("CheckOUT"))

res=obj.checkout(no);

if (res==1)

out.println(no + " rooms check-out");

if(res==0)

out.println("Not possible to do Check IN / OUT");

out.println("<br><br><a href=index.html> Back </a>");

finally {

out.close();

}
OUTPUT:
Q.6 c) Develop simple shopping cart application using EJB [Stateful Session
Bean].
CODE:

Step 1 creating application

File -> new project-> java web->web application -> Prac6CShoppingCartApp -> select Use
dedicated folder for storing libraries -> finish

Step 2: Creating a stateful session bean

Source package -> new -> other -> enterprise java beans -> session bean -> next -> new session bean
-> ejb name: ->ShoppingCart -> package: -> ejb -> session type option -> Stateful -> finish.

ShoppingCart.java

package ejb;

import java.sql.*;

import java.util.*;

import javax.ejb.*;

@Stateful

public class ShoppingCart

{ List<String> contents;

String customerName;

private Connection conn = null;

private ResultSet rs;

private Statement stmt = null;

private String query = null;

public void initialize(String person)

{ if (person != null) {

customerName = person;

try {

Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/cartdb", "root",
"tiger");

} catch(ClassNotFoundException | IllegalAccessException | InstantiationException |


SQLException e) {

System.err.println("Sorry failed to connect to the Database." + e.getMessage());

contents = new ArrayList<>();

public void addBook(String title) {

try {

stmt = conn.createStatement();

query = "INSERT INTO cart VALUES('" + customerName + "','" + title + "')";

stmt.executeUpdate(query);

} catch(SQLException e) {

System.err.println("Sorry failed to insert values from the database table. " + e.getMessage());

public void removeBook(String title) {

try {

stmt = conn.createStatement();

query = "DELETE FROM cart WHERE UserName='" + customerName + "' AND


ItemName='" + title + "'";

stmt.executeUpdate(query);

} catch(SQLException e) {

System.err.println("Sorry failed to delete values from the database table. " + e.getMessage());

}
}

public List<String> getContents() {

try {

stmt = conn.createStatement();

query = "SELECT * FROM cart WHERE UserName='" + customerName + "'";

rs = stmt.executeQuery(query);

while(rs.next()) {

contents.add(rs.getString("ItemName"));

} catch(SQLException e) {

System.err.println("Sorry failed to select values from the database table. " + e.getMessage());

return contents;

@Remove()

public void remove() {

contents = null;

Step 3: creating a web client using index.jsp

Right click on wewb pages -> new -> JSP -> filename -> index -> finish.

<%@page import="java.util.Iterator, java.util.List, javax.naming.InitialContext,


ejb.ShoppingCart"%>

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

<!DOCTYPE html>

<%!

private static ShoppingCart cart;


public void jspInit() {

try {

InitialContext ic = new InitialContext();

cart = (ShoppingCart) ic.lookup("java:global/Prac6CShoppingCartApp/ShoppingCart");

} catch (Exception ex) {

System.out.println("Could not create cart bean." + ex.getMessage());

%>

<%

if(request.getParameter("txtCustomerName") != null) {

cart.initialize(request.getParameter("txtCustomerName"));

} else {

cart.initialize("Guest");

if (request.getParameter("btnRmvBook") != null) {

String books[] = request.getParameterValues("chkBook");

if (books != null) {

for (int i=0; i<books.length; i++) {

cart.removeBook(books[i]);

if (request.getParameter("btnAddBook") != null) {

String books[] = request.getParameterValues("chkBook");

if (books != null) {
for (int i=0; i<books.length; i++) {

cart.addBook(books[i]);

%>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Shopping Cart</title>

</head>

<body style="background-color: pink;">

<h1 style="text-align: center;">Books For Sale</h1><br>

<form method="post">

Customer Name: <input type="text" name="txtCustomerName" value=<%=


request.getParameter("txtCustomerName")%> /><br>

<b>Book Titles</b><br>

<input type="checkbox" name="chkBook" value="Struts 2.0 For Beginners">Struts


2.0 For Beginners<br>

<input type="checkbox" name="chkBook" value="Oracle 11g For


Professionals">Oracle 11g For Professionals<br>

<input type="checkbox" name="chkBook" value="Hibernate 3 For


Beginners">Hibernate 3 For Beginners<br>

<input type="checkbox" name="chkBook" value="Java Persistence API In EJB 3


For Beginners">Java Persistence API In EJB 3 For Beginners<br>

<br>

<input type='submit' value='Add To My Basket' name='btnAddBook'>


<input type='submit' value='Remove From My Basket'
name='btnRmvBook'><br><br><br>

<%

if(cart!=null)

out.print("<b>Basket</b><br>");

List<String> bookList = cart.getContents();

Iterator iterator = bookList.iterator();

while (iterator.hasNext())

String title = (String) iterator.next();

%>

<%= title %><br>

<%

%>

</form>

</body>

</html>

Step 4:

Create database and database table

Services -> create database -> cartdb ->select cartdb - > right click -> create table -> cart ->
UserName varchar 35

ItemName varchar 50

Finish.
Step 5.

Add mysql connector to the library under project tab. Step 6:

build and run the application.

OUTPUT:
PRACTICAL 7

Q.7 a) Develop simple EJB application to demonstrate Servlet Hit count using
Singleton Session Beans. 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">
<meta http-equiv="Refresh" content="0; URL=ServletClient">
</head>
<body>
<div>TODO write content</div>
</body>
</html>

CountServletHitsBean.java

package ejb;
import javax.ejb.Singleton;
@Singleton
public class CountServletHitsBean {
private int hitCount;
public synchronized int getCount()
{
return hitCount++;
}
}

ServletClient.java

package servlet;
import ejb.CountServletHitsBean;
import java.io.*;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
@WebServlet(name = "ServletClient", urlPatterns = {"/ServletClient"})
public class ServletClient extends HttpServlet {
@EJB CountServletHitsBean obj;
@Override
protected void service (HttpServletRequest req, HttpServletResponse res) throws ServletException,
IOException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.print("<b>Number of times this Servlet is accessed </b>: "+obj.getCount());
}
}
7c.Develop simple Marks Entry Application to demonstrate accessing
Databaseusing EJB.
Code:-
CODE:
Step 1:
Create web application as pract7CMarksApp.
Step 2:
Create database marksdbStep 3:

Create tables marks in marksdb database as:

create table marks (id int primary key auto_increment, sname varchar(35), marks1int,
marks2 int, marks3 int);step 4:
index.jsp
<%@page import="ejb.MarksEntryBean"%>

<%@page import="javax.naming.InitialContext"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%!

private static MarksEntryBean obj;public


void jspInit()
{
try
{
InitialContext ic=new InitialContext();

obj=(MarksEntryBean)ic.lookup("java:global/Pract7CMarksApp/MarksEntryBean ");
}

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

%>

<%

if(request.getParameter("InsertMarks")!=null)

String sname;

int marks1, marks2, marks3;

sname = request.getParameter("sname");

marks1=Integer.parseInt(request.getParameter("m1"));

marks2=Integer.parseInt(request.getParameter("m2"));

marks3=Integer.parseInt(request.getParameter("m3"));

obj.addMarks(sname,marks1,marks2,marks3);

out.print("Marks entered successfully..!!!!");

%>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>JSP Page</title>

</head>

<body>

<h2>Enter Details</h2>

<form name="result" method="post">

Enter student's name: <input type='text' name="sname" /><br>

Enter subject 1 marks: <input type=’text’ name=”m1” /><br>


Enter subject 2 marks: <input type=’text’ name=”m2” /><br>

Enter subject 3 marks: <input type=’text’ name=”m3” /><br>

<input type=’submit’ name=”InsertMarks” /><br>

</form>

</body>

</html>

Step 4:

Create stateful java bean as select source package -> session bean -> class name ->

MarksEntryBean -> package -> ejb -> bean type-> stateful -> don’t select Local /

Remote -> finish.

Package ejb;

Import java.sql.*;

Import javax.ejb.Stateful;
@Stateful

Public class MarksEntryBean {

String sname;

Int m1,m2,m3;

Connection con=null;

Statement st=null;

String query=””;

Public void addMarks(String sname,int m1,int m2,int m3)

Try

Class.forName(“com.mysql.jdbc.Driver”);
Con=DriverManager.getConnection(“jdbc:mysql://localhost:3306/marksdb”, “root”,”tiger");
st=con.createStatement();
query="insert into marks (sname,marks1,marks2,marks3) values
('"+sname+"','"+m1+"','"+m2+"','"+m3+"')";
st.executeUpdate(query); System.out.print("Marks
entered sucessfully!!");

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

You might also like