0% found this document useful (0 votes)
36 views65 pages

Tyit Ej Practical Journal

Uploaded by

farisk004
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views65 pages

Tyit Ej Practical Journal

Uploaded by

farisk004
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

PRACTICAL 1

1a. Create a simple calculator application using servlet.

Code:

index.html
<html><head><title>Calculator App</title></head>
<body>
<form action="CalculatorServlet" >
Enter First Number <input type="text" name="txtN1" ><br>
Enter Second Number <input type="text" name="txtN2" ><br>
Select an Operation
<input type="radio" name="opr" value="+">ADDTION
<input type="radio" name="opr" value="-">SUBSTRACTION
<input type="radio" name="opr" value="*">MULTIPLY
<input type="radio" name="opr" value="/">DIVIDE <br>
<input type="reset">
<input type="submit" value="Calculate" >
</form></body>
</html>

CalculatorServlet.java
package mypack;
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 CalculatorServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html><head><title>ServletCalculatorServlet</title></head><body>");
double n1 = Double.parseDouble(request.getParameter("txtN1"));
double n2 = Double.parseDouble(request.getParameter("txtN2"));
double result =0;
String opr=request.getParameter("opr");
if(opr.equals("+")) result=n1+n2;
if(opr.equals("-")) result=n1-n2;
if(opr.equals("*")) result=n1*n2;
if(opr.equals("/")) result=n1/n2;
out.println("<h1> Result = "+result);
out.println("</body></html>");
}
}
Output:
1b. 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”

Code:

index.html
<html><head><title>Login Form</title></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
package mypack;
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class LoginServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html><head><title>Servlet LoginServlet</title></head>");
String uname = request.getParameter("txtId");
String upass = request.getParameter("txtPass");
if(uname.equals("admin") && upass.equals("12345"))
{
out.println("<body bgcolor=blue >");
out.println("<h1> Welcome !!! "+uname+"</h1>");
}
else
{
out.println("<body bgcolor=red >");
out.println("<h1> Login Fail !!! </h1>");
}
out.println("</body></html>");
}}
Output:
1c. 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.

MySql queries

create database LoginDB;


use LoginDB;
create table user(username varchar(20) PRIMARY KEY, password varchar(20), email
varchar(20), country varchar(20));

• Add jar file → mysql-connector-java-8 jar file

Code:

index.html
<html><head><title>Registration Page</title></head>
<body>
<form action="RegisterServlet" >
<H1>Welcome to Registration page</H1>
Enter User Name <input type="text" name="txtUid"><br>
Enter Password <input type="password" name="txtPass"><br>
Enter Email <input type="text" name="txtEmail" ><br>
Enter Country<input type="text" name="txtCon" ><br>
<input type="reset" ><input type="submit" value="REGISTER" >
</form>
</body>
</html>

RegisterServlet.java
package mypack; import java.io.*;
import java.sql.*; import javax.servlet.*;
import javax.servlet.http.*;
public class RegisterServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String id = request.getParameter("txtUid");
String ps = request.getParameter("txtPass");
String em =request.getParameter("txtEmail");
String co =request.getParameter("txtCon");
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=
DriverManager.getConnection("jdbc:mysql://localhost:3306/logindb",”root”,”1234”);
PreparedStatement pst = con.prepareStatement("insert into user values(?,?,?,?)");
pst.setString(1,id);
pst.setString(2,ps);
pst.setString(3,em);
pst.setString(4,co);
int row = pst.executeUpdate();
out.println("<h1>"+row+ " Inserted Succesfullyyyyy");
}
catch(Exception e){out.println(e);
}
}
}
Output:
PRACTICAL 2

2a. 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.

Code:

index.html
<html><head><title>Login Form</title></head>
<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>
</html>

LoginServlet.java
package mypack;
import java.io.IOException;
import java.io.PrintWriter; i
mport javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.RequestDispatcher;
public class LoginServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)throws
ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html><head>");
out.println("<title>Servlet LoginServlet</title></head>");
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("<body bgcolor=red >");
out.println("<h1> Login Fail !!! </h1>");
RequestDispatcher rd = request.getRequestDispatcher("index.html");
rd.include(request, response);
}
out.println("</body>");
out.println("</html>");
}
}

WelcomeServlet.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class WelcomeServlet extends HttpServlet
{
public void doPost(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
res.setContentType("text/html");
try (PrintWriter out = res.getWriter())
{
String uname = request.getParameter("txtId");
String upass = request.getParameter("txtPass");
out.println("Welcome "+uname);
}
}
}
Output:
2b. Create a servlet that uses Cookies to store the number of times a user has visited
servlet.

Code:

index.html
<html>
<head>
<title>Cookie Demo</title>
</head>
<body>
<form action="cookie" >
Enter Your Name <input type="text" name="txtName"><br>
<input type="submit" value="~~~ Click to Enter ~~~">
</form>
</body>
</html>

cookie.java
package mypack;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ccokie extends HttpServlet
{
private int i=1;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String t1=request.getParameter("txtName");
out.print("<body bgcolor=yellow>");
out.print("<b> Welcome "+ t1);
out.print("<br>");
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(ccokie.this)
{ out.println("You visited this page "+i+" times");
}
}
i++;
}
}
Output:
2c. 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.

Code:

index.html
<html>
<head>
<title>session</title>
</head>
<body>
<form action="session" >
<input type="submit" value="~~~ Click to Enter ~~~">
</form>
</body>
</html>

session.java
package mypack;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class session extends HttpServlet
{
private int counter;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpSession hs = request.getSession(true);
out.println("<h1>Your Session ID "+hs.getId()+"</h1>");
if(session.isNew())
{
out.print("<h1>This is the first time you are visiting this page");
++counter;
}
else
{
synchronized(session.this)
{
if(counter==10)
{
session.invalidate();
counter=0;
request.getSession(false);
}
else
out.print("<h1>You have visited this page "+(++counter)+ " times");
}
}
}
}
Output:
PRACTICAL 3

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

Uploading a file

Code:

index.html
<html>
<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
package fileservletapp; import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.*;
@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;
byte[] b=new byte[1024];
while ((read = is.read(b)) != -1)
{
os.write(b, 0, read);
}
out.println("<br>file uploaded sucessfully...!!!");
}
catch(FileNotFoundException e){out.print(e);}
}
}

Downloading a file

Code:

index.html
<html>
<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
package filedownloadapp;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
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 os = response.getOutputStream();
response.setHeader("Content-Disposition","attachment; filename=\"" + filename + "\"");
// if comment this statement then it will ask you about the editor with which you want to open
the file
int i;
byte b[]=new byte[1024];
while ((i=is.read(b)) != -1) {
os.write(b);
}
is.close();
os.close();
}
}
Output:
3b. Develop Simple Servlet Question Answer Application using Database.

MySql queries
Database name: queansdb
Table name: queans
Fields:
o queno integer primary key
o question varchar 200
o opt1 varchar 100
o opt2 varchar 100
o opt3 varchar 100
o opt4 varchar 100
o anskey varchar 1

• Add jar file → mysql-connector-java-8 jar file

Code:

index.html
<html><head><title>Quiz Application</title></head>
<body>
<h1>Welcome to Quiz Servlet </h1>
<h1>
<a href="QuizServlet" >CLICK TO START QUIZ</a>
</h1>
</body>
</html>

QueAnsDBServlet.java
package dbapp;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
public class QueAnsDBServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try
{
out.print("<html><body><br>");
out.println("<form method='post' action='Marks'>");
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost/queansdb","root","tiger");
Statement st = con.createStatement();
String sql="select * from queans";
ResultSet rs = st.executeQuery(sql);
int i=0;
out.print("<center>Online Exam</center>");
while(rs.next())
{
i++;
out.print("<br><br><hr>"+rs.getInt(1)+" ");
out.print(rs.getString(2));
out.print("<br><input type=radio name="+i+" value=1>"+rs.getString(3));
out.print("<br><input type=radio name="+i+" value=2>"+rs.getString(4));
out.print("<br><input type=radio name="+i+" value=3>"+rs.getString(5));
out.print("<br><input type=radio name="+i+" value=4>"+rs.getString(6));
String ans="ans"+i;
out.println("<br><input type=hidden name="+ans+" value="+rs.getString(7)+">");
}
out.println("<br><input type=hidden name=total value="+i+">");
out.println("<input type=submit value=submit>");

out.println("</form>");
out.print("</body></html>");
}
catch(Exception e)
{
out.println("ERROR "+e.getMessage());
}
}
}
Marks.java
package dbapp;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class Marks extends HttpServlet
{ public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try
{ out.print("<html><body>");
int total=Integer.parseInt(request.getParameter("total"));
int marks=0;
for(int i=1; i<=total; i++)
{
String sel=request.getParameter(new Integer(i).toString());
String ans=request.getParameter("ans"+i);
if (sel.equals(ans)) marks++;
}
out.println("Total Marks : "+marks);
out.print("</body></html>");
}
catch(Exception e)
{
out.println("ERROR "+e.getMessage());
}
}
}
Output:
3c. Create simple Servlet application to demonstrate Non-Blocking Read Operation.

Code:

index.html

<html>
<body>
<a href="NonBlockingServlet">Non Blocking Servlet</a>
</body>
</html>

ReadingListener.java
package nonblkapp;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.*;
public class ReadingListener implements ReadListener
{
ServletInputStream input = null;
AsyncContext ac = null;
ReadingListener(ServletInputStream in, AsyncContext c)
{
input = in;
ac = c;
}
@Override
public void onDataAvailable()
{
}
public void onAllDataRead()
{ ac.complete();
}
public void onError(Throwable t)
{ ac.complete();
t.printStackTrace();
}
}
ReadingNonBlockingServlet.java
package nonblkapp;
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
@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));
}
}

NonBlockingServlet.java
package nonblkapp;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
@WebServlet(name = "NonBlockingServlet", urlPatterns = {"/NonBlockingServlet"})
public class NonBlockingServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String filename = "booklist.txt";
ServletContext c = getServletContext();
InputStream is = c.getResourceAsStream("/"+filename);
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String path = "http://" + request.getServerName() + ":" + request.getServerPort() +
request.getContextPath() + "/ReadingNonBlockingServlet";
out.println("<h1>File Reader</h1>");
//out.flush();
URL url = new URL(path);
HttpURLConnection hc = (HttpURLConnection) url.openConnection();
hc.setChunkedStreamingMode(2); //2bytes at a time
hc.setDoOutput(true); // true if URL connection done
hc.connect();
String text = "";
System.out.println("Reading started...");
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(hc.getOutputStream()));
while ((text = br.readLine()) != null)
{
bw.write(text);
bw.flush();
out.println(text+"<br>");
out.flush();
try
{
Thread.sleep(1000);
}
catch (Exception ex)
{
out.print(ex);
}
}
bw.write("Reading completed...");
bw.flush();
bw.close();
}
}
Output:
PRACTICAL 4

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

Code:

<%@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>
Output:
4b. 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).

Code:

index.html
<html>
<body>
<form action="Validate.jsp">
Enter Your Name <input type="text" name="name"><br>
Enter Your Age <input type="text" name="age"><br>
Select Hobbies <input type="checkbox" name="hob" value="Singing">Singing
<input type="checkbox" name="hob" value="Reading">Reading Books
<input type="checkbox" name="hob" value="Football">Playing Football<br>
Enter E-mail<input type="text" name="email"><br>
Select Gender <input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="other">Other<br>
<input type="hidden" name="error" value="">
<input type="submit" value="Submit Form">
</form >
</body>
</html>

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

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


<!DOCTYPEhtml>
<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;
import java.beans.*;
import java.io.Serializable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CheckerBean
{
String name,hob,email,gender,error;
int age;
public CheckerBean()
{
name="";
hob="";
email="";
gender="";
error="";
age=0;
}
public void setName(String n)
{
name=n;
}
public String getName()
{
return name;
}
public void setAge(int a)
{
age=a;
}
public int getAge()
{
return age;
}
public void setHob(String h)
{
hob=h;
}
public String getHob()
{
return hob;
}
public void setEmail(String e)
{
email=e;
}
public String getEmail()
{
return email;
}
public void setGender(String g)
{
gender=g;
}
public String getGender()
{
return gender;
}
public String getError()
{
return error;
}
public boolean validate()
{
boolean res=true;
if(name.trim().equals(""))
{
error+="<br>Enter First Name";
res=false;
}
if(age<0||age>99)
{
error+="<br>Age Invalid";
res=false;
}
String emailregex="^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9
-]+)*(\\.[A-Za-z]{2,})$";
Boolean b=email.matches(emailregex);
if(!b)
{
error+="<br>email Invalid";
res=false;
}
return res;
}
}
Output:
Q4)c).Create a registration and login JSP application to register and authenticate the
user based on username and password using JDBC.

Create MySql queries

create database LoginDB;

use LoginDB;

create table user(username varchar(20) PRIMARY KEY, password varchar(20), email


varchar(20), country varchar(20));

insert into user values ('admin','admin','[email protected]','India');

select * from user;

• Add jar file → mysql-connector-java-8 jar file

index.html

<html><head><title>New User Registration Page</title></head>


<body>
<form action="Register.jsp" >
<h1> New User Registration Page</h1>
Enter User Name <input type="text" name="txtName" ><br>
Enter Password <input type="password" name="txtPass1" ><br>
Re-Enter Password<input type="password" name="txtPass2" ><br>
Enter Email<input type="text" name="txtEmail" ><br>
Enter Country Name <input type="text" name="txtCon" ><br>
<input type="reset" ><input type="submit" value="REGISTER" >
</form>
</body>
</html>

Register.jsp

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


<html><body>
<h1>Registration JSP Page</h1>
<%
String uname=request.getParameter("txtName");
String pass1 = request.getParameter("txtPass1");
String pass2 = request.getParameter("txtPass2");
String email = request.getParameter("txtEmail");
String ctry = request.getParameter("txtCon");
if(pass1.equals(pass2)){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/logindb","root,"root");
PreparedStatement stmt = con.prepareStatement("insert into user values (?,?,?,?)");
stmt.setString(1, uname); stmt.setString(2, pass1);
stmt.setString(3, email); stmt.setString(4, ctry);
int row = stmt.executeUpdate();
if(row==1) { out.println("Registration Successful"); }
else {
out.println("Registration FFFFFAAAIIILLLL !!!!");
%><jsp:include page="index.html" ></jsp:include>
<%
}
}catch(Exception e){out.println(e);}
}
else
{
out.println("<h1>Password Mismatch</h1>");

%>
<jsp:include page="index.html" ></jsp:include>
<% }
%>
</body>
</html>
Output:
PRACTICAL 5

5a. 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.

MySql queries

Create MySql queries

create database empdb;

use empdb;

create table emp(eno integer(10) PRIMARY KEY, name varchar(20), age integer(5),
designation varchar(20),sal integer(10));

insert into emp values (101,'Kiara',26,'HR',50000);


insert into emp values (102,'Amit',24,'analist',40000);

select * from emp;

• Add jar file → mysql-connector-java-8 jar file

Code:

index.html
< html>
<body>
<form action="UpdateEmp.jsp" >
Enter Employee Number<input type="text" name="txtEno" ><br>
Enter Salary to update<input type="text" name="txtSal" ><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>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Updating Employee Record</h1>
<%
String eno=request.getParameter("txtEno");
String sal = request.getParameter("txtSal");
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con
=DriverManager.getConnection("jdbc:mysql://localhost:3306/empdb","root","root");
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 sal=? where eno=?");
pst.setString(1, sal);
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>
</body>
</html>
Output:
5b. Create a JSP page to demonstrate the use of Expression language.

Code:

index.jsp
<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>

ExpressionLanguage.jsp
<body>
Welcome, ${ param.name }
Session Value is ${ sessionScope.user }
Cookie name is , ${cookie.name.value}
</body>

ArithemeticOperator.jsp
<body>
Welcome, ${ param.name }
Session Value is ${ sessionScope.user }
Cookie name is , ${cookie.name.value}
</body>

RelationalOperator.jsp
<body>
<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>
Output:
5c. Create a JSP application to demonstrate the use of JSTL.

• Add jar file → jstl-1.2.jar in libraries and execute it

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>
<form action="jstlDemo.jsp" method ="post">
First Name<input type="text" name="fn"><br>
Last Name<input type="text" name="ln"><br>
<input type="submit" value="check jstl">
</form>
</body>
</html>

jstlDemo.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
First Name <b><c:out value= "${param.fn}"></b></c:out><br>
Last Name <b><c:out value= "${param.ln}"></b></c:out>
<hr>
use of if statement
<c:set var="mycount" value="25"/>
<c:if test="${mycount==25}">
<b><c:out value="Your count is 25"></b></c:out>
</c:if>
<br>use of foreach statement<br>
<c:forEach var="count" begin="101" end="110">
<c:out value="${count}">
</c:out>
</c:forEach>
</body>
</html>
Output:
PRACTICAL 6

6a. Create a Currency Converter application using EJB.

Code:

index.html
<html><head>
<title>Currency Converter</title>
</head>
<body>
<form action="CCServlet" >
Enter Amount <input type="text" name="amt"><br>
Select Conversion Type
<input type="radio" name="type" value="r2d" checked>Rupees to Dollar
<input type="radio" name="type" value="d2r" >Dollor to Rupees<br>
<input type="reset" ><input type="submit" value="CONVERT" >
</form>
</body>
</html>

CCServlet.java
package mypack;
import java.io.*;
import javax.servlet.*;
importjavax.servlet.htp.*;
import javax.ejb.EJB;
import mybeans.CCBean;
public class CCServlet extends HttpServlet {
@EJB CCBean obj;
public void doGet(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.r2Dollor(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 r2Dollor(double r)
{ return r/65.65;
}
public double d2Rupees(double d)
{
return d*65.65;
}
}
Output:
6b. Develop a Simple Room Reservation System Application Using EJB.

MySql queries

create table roombook(RoomId varchar(4) PRIMARY KEY, RoomType varchar(20), charges


float, cust varchar(20), mob varchar(20) , status varchar(10));

insert into roombook values('1001','Delux',5000.00,'richa','564576867','Not Booked');


insert into roombook values('1002','Suit',6000.00,'rich','5645768677','Not Booked');
insert into roombook values('1003','Super Delux',7000.00,'ria','5645768677','Not Booked');
insert into roombook values('1004','Super Delux',2000.00,'kia','5645768677','Not Booked');
insert into roombook values('1006','Delux',3000.00,'kiara','5645768677','Not Booked');
select * from roombook;

• Add jar file → mysql-connector-java-8 jar file

Code:

index.html

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

RBServlet.java

package mypack;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.ejb.EJB;
import mybeans.RRBean;
public class RBServlet extends HttpServlet {
@EJB RRBean obj;
public void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException{
PrintWriter out=response.getWriter();
String rt=request.getParameter("txtType");
String cn=request.getParameter("txtCust");
String cm=request.getParameter("txtMob");
String msg = obj.roombook(rt, cn, cm);
out.println(msg);
}}
RRBean.java
package mybeans;
import javax.ejb.Stateless;
import java.sql.*;
@Stateless
public class RRBean {
public RRBean(){}
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/ejb?useSSL=false","root","root");
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 cust=? where
RoomId=? ");
PreparedStatement stm2 = con.prepareStatement("update roombook set mob=? 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;
}}
Output:
PRACTICAL 7

7a. Develop simple EJB application to demonstrate Servlet Hit count using Singleton
Session Beans.

Code:

index.html
<html>
<head>
<meta http-equiv="Refresh" content="0; URL=ServletClient">
</head>
<body>
</body>
</html>

CountServletHitsBean
package servlet;
import javax.ejb.Singleton;

@Singleton
public class CountServletHitsBean {
private int hitcount;

public int incrementAndGetHitCount()


{
return hitcount++;
}

ServletClient
package servlet;

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;
@WebServlet(name= "ServletClient", urlPatterns={"/ServletClient"})
public class ServletClient extends HttpServlet {
@EJB CountServletHitsBean CounterBean;

@Override
protected void service(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 ServletClient</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Number of times this servlet is accessed:" +
CounterBean.incrementAndGetHitCount()+"</h1>");
out.println("</body>");
out.println("</html>");
}
}

Output:
7b. Develop simple visitor Statistics application using Message Driven Bean [Stateless
Session Bean]

Visitorservlet.java
try{
for(int i=1;i<=4;i++){
String message="Sending "+ i +"Visitor";
context.createProducer().send(myDestination, message);
}
out.println("All Message are send");
}catch(Exception ex){
out.println("Error "+ex.getMessage());
}

message bean
try{
TextMessage tm=(TextMessage)message;
System.out.println("Recieved Message"+tm.getText());
}catch(JMSException ex){
System.out.println("Error "+ex. getMessage());
}
Output:-
Q.7 c) Develop simple Marks Entry Application to demonstrate accessing Database using
EJB.

Create database bscit;


use bscit;
Create tables students values(rollno int primary key, sname varchar(35), marks1 int,
marks2 int, marks3 int);

• Add jar file → mysql-connector-java-8 jar 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>
<center>
<h2>Enter Students Details</h2>
<form name="result" method="post" action="insert.jsp">
Enter student's Roll no: <input type='text' name="t1" /><br>
Enter student's Name: <input type='text' name="t2" /><br><br>
Subjects:<br><br>
Enter JAVA marks: <input type='text' name="m1" /><br>
Enter EJ marks: <input type='text' name="m2" /><br>
Enter LINUX marks: <input type='text' name="m3" /><br>
<input type='submit' name="InsertMarks" /><br>
</form>
</center>
</body>
</html>

insert.jsp

<%@page import="com.test.DatabaseOperations"%>
<%@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{
int rollno=Integer.parseInt(request.getParameter("t1"));
String sname = request.getParameter("t2");
int marks1=Integer.parseInt(request.getParameter("m1"));
int marks2=Integer.parseInt(request.getParameter("m2"));
int marks3=Integer.parseInt(request.getParameter("m3"));
DatabaseOperations d1=new DatabaseOperations();
d1.AddMarks(rollno, sname, marks1, marks2, marks3);

out.print("<h1>Marks entered successfully..!!!!<h1>");


}catch(Exception ex){
out.println(ex.getMessage());
}
%>
</body></html>

create stateless java bean name as DatabaseOperations -> package -> com.test -> bean
type-> stateless -> select Local -> finish.

DatabaseOperations.java

@Override
public void AddMarks(int rollno, String sname, int marks1, int marks2, int marks3)throws
Exception{
{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/bscit?useSSL=false",
"root","root");
PreparedStatement ps = con.prepareStatement("Insert into students values(?,?,?,?,?)");
ps.setInt(1, rollno);
ps.setString(2, sname);
ps.setInt(3, marks1);
ps.setInt(4, marks2);
ps.setInt(5, marks3);
ps.executeUpdate();

}
DatabaseOperationsLocal.java

void AddMarks(int rollno, String sname, int marks1, int marks2, int marks3)throws Exception;
Output:
PRACTICAL 8

Q8a Develop a simple Inventory Application Using JPA.

Create database in mysql

use bscit;
create table inventory(sku int(5) Primary Key, ItemName varchar(50), ItemPrice int(6),
Itemqty int(5));

• Add jar file → mysql-connector-java-8 jar file

index.html

<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<center>
<form action="AddInventory" method="post">
<table>
<tr>
<td colspan="2" align="center"><b> Add the item in Inventory<b></td>
</tr>

<tr>
<td> SKU </td>
<td> <input type="number" name="sku"></td>
</tr>
<tr>
<td> Item name: </td>
<td> <input type="text" name="itemname" maxlength="25" size="40"></td>
</tr>

<tr>
<td> Price: </td>
<td> <input type="number" name="itemprice" maxlength="25" size="40"></td>
</tr>
<tr>
<td> Quantity </td>
<td> <input type="number" name="itemqty" maxlength="25" size="40"></td>
</tr>
<tr>
<tr>
<td colspan="2"><b><input type="Submit" name="AddInventory"
value="AddInventory"><b></td>
</tr>
</table>

</form>
</center>
</html>
Note:--
Now create PU with proper data and provider also data source name
"jdbc:sqlserver://localhost:3306;bscit?useSSL=false";

Then create Entity class from database where we have to add table which is created in
MySQL within the package name as com.test

After this create servlet as AddInventory.java within the package name as com.test

AddInventory.java

EntityManagerFactory
entityManagerFactory=Persistence.createEntityManagerFactory("Practical8aaPU");
EntityManager entityManager=entityManagerFactory.createEntityManager();
EntityTransaction entityTransaction=entityManager.getTransaction();
Inventory i1=new Inventory();
i1.setSku(Integer.parseInt(request.getParameter("sku")));
i1.setItemName(request.getParameter("itemname"));
i1.setItemPrice(Integer.parseInt(request.getParameter("itemprice")));
i1.setItemqty(Integer.parseInt(request.getParameter("itemqty")));
entityTransaction.begin();
entityManager.persist(i1);
entityTransaction.commit();
out.println("<h1>Record is added successfully </h1>");
out.println("</body>");
out.println("</html>");
Output:-

You might also like