Anda di halaman 1dari 59

Practical No.

1(A)
Aim:Create a simple calculator application using servlet.
HTMLCode:
<html>
<head>
<title>simple calculator</title>
</head>
<body>
<form action="scalculator" method="post">
first number:<input type="text" name="n1">
<br>
second number:<input type="text" name="n2">
<br>
operation:<input type="text" name="opera">
(*use only operator like:+ - * / %)
<br>
<input type="submit" value="calculate">
</form>
</body>
</html>

SERVLETCode:

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

public class scalculator extends HttpServlet


{
public void doPost(HttpServletRequest req , HttpServletResponse res) throws
ServletException, IOException
{
PrintWriter out =res.getWriter();
res.setContentType("text/html");

int num1 =Integer.parseInt(req.getparameter("n1"));


int num2 =Integer.parseInt(req.getparameter("n2"));
String op =req.getParameter("opera");

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3
switch(op)
{
case "+":
out.println("addition ="+(num1+num2));
break;
case "-":
out.println("difference ="+(num1-num2));
break;
case "*":
out.println("product ="+(num1*num2));
break;
case "/":
out.println("division ="+(num1/num2));
break;
case "%":
out.println("modulus ="+(num1%num2));
break;
default:
out.println("error: invalid input" ));
}
}
}
Output:

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3
Practical No. 1(B)
Aim: Create a servlet for a login page. If the username and password
are correct then it says message “Hello ” else a message “login failed”.
HTMLCode:
<html>
<head>
<title>login</title>
</head>
<body>
<form action="logpage" method="post">
username:<input type="text" name="name">
<br>
password:<input type="password" name="psswd">
<br>
<input type="submit" value="login">
</form>
</body>
</html>

SERVLETCode:

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

public class logpage extends HttpServlet


{
@override
public void doPost(HttpServletRequest req , HttpServletResponse res) throws
ServletException,IOException
{
PrintWriter out =res.getWriter();
res.setContentType("text/html");

String uname =req.getParameter("name");


String psswrd=req.getParameter("psswd");

if("admin".equals(uname) && "system123".equals(psswrd))

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3
{
out.println("login successful");
}
else
{
out.println("login failed");
}
}
}
Output:

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3
Practical No. 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.
HTML Code:
<html>
<body>
<form method="post" action="NewServlet">
Username:<input type="text" name="user" >
<br>
Password:<input type="password" name="pass">
<br>
Name:<input type="text" name="name">
<br>
City:<input type="text" name="city">
<br>
Mobile no:<input type="text" name="mobile">
<br>
<input type="submit" value="Register">
</form>
</body>
</html>

SERVLET CODE:

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3
public class NewServlet extends HttpServlet
{
public void doPost(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
PrintWriter out=res.getWriter();
res.setContentType("Text/html");
String u =req.getParameter("user");
String p =req.getParameter("pass");
String n =req.getParameter("name");
String c =req.getParameter("city");
long m=Long.parseLong(req.getParameter("mobile"));
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/
Regdb74","root","root");
String sql="insert into Register values(?,?,?,?,?)";

PreparedStatement ps=con.prepareStatement(sql);
ps.setString(1,u);
ps.setString(2,p);
ps.setString(3,n);
ps.setString(4,c);
ps.setLong(5,m);

int row=ps.executeUpdate();
out.println("<b> "+row+" Inserted successfully</b>");
}catch(Exception s)
{
out.println(s);
}
}
}

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3
Database connection:

Output:

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3
Practical No. 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.
HTML CODE:
<html>
<body>
<form method="get" action="loginpage">
Username<input type="text" name="username">
<br>
password<input type="password" name="pass">
<input type="submit" value="Login">
</form>
</body>
</html>

Loginpage:
public class loginpage extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
String v =req.getParameter("username");
String p =req.getParameter("pass");

if(p.equals("ckt123"))
{
RequestDispatcher
rd=req.getRequestDispatcher("WelcomeServlet");
rd.forward(req,res);
}
else
{
out.println("sorry wrong username or password error !");
RequestDispatcher rd=req.getRequestDispatcher("index.html");
rd.include(req,res);

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3
}
}
}

Welcome.java

public class WelcomeServlet extends HttpServlet


{
public void doGet(HttpServletRequest req,HttpServletResponse res)throws
ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
String User=req.getParameter("username");
out.println("welcome"+User);
}
}

Output:

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3
Practical No. 2(B)
Aim:Create a servlet that uses Cookies to store the number of times a
user has visited Servlet.
HTML Code:
<html>
<body>
<form method="get" action="cookie">
<input type="submit" value="Hit">
</form>
</body>
</html>

SERVLET Code:
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 cookie extends HttpServlet


{
static int i=1;
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{

PrintWriter out=res.getWriter();
res.setContentType("text/html");
String k=String.valueOf(i);

Cookie c=new Cookie("visit",k);


c.setMaxAge(3000);
res.addCookie(c);
int j=Integer.parseInt(c.getValue());

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3
if(j==1)
{
out.println("Welcome new visitor");
}
else
{
out.println("You visited "+i+"times");
}
i++;
}
}
Output:

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3
Practical No. 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.
HTML Code:
<html>
<body>
<form method="get" action="SessionDemo">
<input type="submit" value="Hit">
</form>
</body>
</html>

SERVLET Code:

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
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 SessionDemo extends HttpServlet


{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{

PrintWriter out=res.getWriter();
res.setContentType("text/html");
HttpSession mySession=req.getSession(true);

int count=1;
String head;

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3
if(mySession.isNew())
{
head="You are new user <br> this is the first time you have
visited";
}
else
{
head="you are old user";
int oldcount=(Integer)mySession.getAttribute("counter");
if(oldcount!=0)
{
count=oldcount+1;
}
}

mySession.setAttribute("counter", count);
out.println("<h3>"+head+"<br>");
out.println("<b>Session_Id:</b>"+mySession.getId()+"<br>");
out.println("<b>Creation_time:</b>"+new
Date(mySession.getCreationTime())+"<br>");
out.println("<b>Last_Accessed-Time:</b>"+ new
Date(mySession.getLastAccessedTime())+"<br>");
out.println("you visited this page<h1>"+count+"</h1>");

if(count==5)
{
mySession.removeAttribute(“counter”);
mySession.invalidate();
}

}
}

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3
Output:

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3
Practical No. 3(A)
Aim:Create a Servlet application to upload and download a file
Uploading file:

HTML CODE:
<html>
<head>
<title>UPLOADING A FILE</title>
</head>
<body>
<form method="post" action="uploadServlet" enctype="multipart/form-data"
>
file to upload:<input type="file" name="inputfile" >
destination folder :<input type="text" name="destination"
value="D:/java50">
<input type="submit" value="upload">
</form>
</body>
</html>

SERVLET CODE:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

@MultipartConfig

public class uploadServlet extends HttpServlet


{
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOExceptio

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
String path=req.getParameter("destination");

Part filepart=req.getPart("inputfile");
String filename=filepart.getSubmittedFileName();
out.println("<br><br>filename: "+filename);
OutputStream os=null;
InputStream is=null;

try
{
os=new FileOutputStream(new File(path+File.separator+filename));
is=filepart.getInputStream();
int i=0;
while((i=is.read())!= -1)
{
os.write(i);
}
out.println("<br>file uploaded successfully");
}catch(Exception e)
{
out.println(e);
}
}
}

Output:

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3
Downloading file:

HTML CODE:
<html>
<head>
<title>downlaod files</title>
</head>
<body>
<h1>Downloading files</h1>
<a href="DownloadServlet?filename=abc.txt">document</a>
</body>
</html>

SERVLET CODE:

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

public class DownloadServlet extends HttpServlet


{
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
PrintWriter out=res.getWriter();
res.setContentType("APPLICATION/OCTET-STREAM");
String filename=req.getParameter("filename");

ServletContext context=getServletContext();
InputStream is=context.getResourceAsStream("/"+filename);
// ServletOutputStream os=res.getOutputStream();

res.setHeader("Content-Disposition","attachement;filename=\""+filena
me+"\"");

int i;

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3
while((i=is.read())!=-1)
{
out.write(i);
}
is.close();
out.close();
}
}

Output:

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3
Practical No. 3(B)
Aim:Develop Simple Servlet Question Answer Application using
Database.
HTML CODE:
<html>
<head>
<title>Online Quiz</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form method="post" action="Quiz">
<center><h1><u>JAVA QUIZ TEST</u></h1></center>

<h3>1. Java is .....programming language </h3>


(A)<input type="radio" name="q1" value="a">Object Oriented<br>
(B)<input type="radio" name="q1" value="b">Procedural Language<br>
(C)<input type="radio" name="q1" value="c">Assembly Language<br>
(D)<input type="radio" name="q1" value="d">None of above<br>
<br>
<h3>2. which is the immediate evaluation symbol in expression
language........</h3>

(A)<input type="radio" name="q2" value="a">#{expression}<br>


(B)<input type="radio" name="q2" value="b">${expression}<br>
(C)<input type="radio" name="q2" value="c">@{expression}<br>
(D)<input type="radio" name="q2" value="d">%{expression}<br>

<br>
<h3>3. JSTL stands for.......</h3>
(A)<input type="radio" name="q3" value="a">Java Standard Tag
Library<br>
(B)<input type="radio" name="q3" value="b">Java Server Tag Library<br>
(C)<input type="radio" name="q3" value="c">JavaServer Pages Standard Tag
Library<br>
(D)<input type="radio" name="q3" value="d">JSP Server Tag Library<br>
<br>

<h3>4. Deferred Evaluation expression can be value expression that can be


used to.......</h3>

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3
(A)<input type="radio" name="q4" value="a">read data<br>
(B)<input type="radio" name="q4" value="b">write data<br>
(C)<input type="radio" name="q4" value="c">both read and write data<br>
(D)<input type="radio" name="q4" value="d">None of above<br>
<br>
<h3>5. JSP stands for........</h3>

(A)<input type="radio" name="q5" value="a">JavaServer Pages<br>


(B)<input type="radio" name="q5" value="b">Java Standard Pages<br>
(C)<input type="radio" name="q5" value="c">Java Servlet Pages<br>
(D)<input type="radio" name="q5" value="d">None of above<br>
<br>

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


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

[Quiz.java]
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
import java.sql.DriverManager;

public class Quiz extends HttpServlet


{
public void doPost(HttpServletRequest req, HttpServletResponse res)throws
IOException, ServletException
{
PrintWriter out=res.getWriter();
res.setContentType("text/html");

int count=0;

String q1=req.getParameter("q1");
String q2=req.getParameter("q2");

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3
String q3=req.getParameter("q3");

String q4=req.getParameter("q4");
String q5=req.getParameter("q5");

if( q1==null && q2==null && q3==null && q4==null && q5==null)
{
out.println("<h3 style=color:red;>You did not attend any
question.</h3><h2>You are failed!!!!");
}
else
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/assignment"
,"root","root");
Statement st=con.createStatement();

ResultSet rs=st.executeQuery("select * from test");

while(rs.next())
{
String qno=rs.getString("qno");
String ans=rs.getString("ans");

if("q1".equals(qno) && q1!=null)


{
if(q1.equals(ans))
{
count++;
}
}

if("q2".equals(qno) && q2!=null)


{
if(q2.equals(ans))
{
count++;

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3
}
}

if("q3".equals(qno) && q3!=null)


{
if(q3.equals(ans))
{
count++;
}
}

if("q4".equals(qno) && q4!=null)


{
if(q4.equals(ans))
{
count++;
}
}

if("q5".equals(qno) && q5!=null)


{
if(q5.equals(ans))
{
count++;
}
}

if(count!=0)
{
out.println("<center><u><h1>Result</h1></center></u><br>");
out.println("<center><h1 style=color:green;>Congratulations!!! You
got "+count+" out of 5 marks.</h1></center>");
}
else
{
out.println("<center><u><h1>Result</h1></center></u><br>");
out.println("<center><h2 style=color:red;>Sorry!!! You are
failed!!!</h2></center>");
}

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3
}catch(Exception e)
{
out.println(e);
}
}
}
}

Output:

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3
DATABASE:--

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3
Practical No. 4(A)
Aim:Develop a simple JSP application to display values obtained from
the use of intrinsic/implicit objects of various types.

JSP Code:

Index.jsp

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


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>

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

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3
Output:

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3
Practical No. 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).

HTML Code:
index.html
<html><head><title>User Information Paage</title>
</head>
<body>
<form action="Validate.jsp">
Enter Your Name<input type="text" name="name" ><br>
Enter Your Age<input type="text" name="age" ><br>

Select Hobbies <input type="checkbox" name="hob" value="Singing">Singing


<input type="checkbox" name="hob" value="Reading">ReadingBooks
<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="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>

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3
<% if (obj.validate())
{ %>
<jsp:forward page="successful.jsp"/>
<% }
else
{%>
<jsp:include page="index.html"/>
<%=obj.getError() %>
<%}
%>
</body>

</html>

CheckerBean.java
package mypack;

public class CheckerBean


{

private String name, age, hob, email, gender, error;

//constructor()
public CheckerBean()
{error="";}

//getter() & setter()


public void setName(String n)
{name=n;}
public void setAge(String a)
{age=a;}
public void setHob(String h)
{hob=h;}
public void setEmail(String e)
{email=e;}
public void setGender(String g)
{gender=g;}
public void setError(String e)
{error=e;}
public String getName()

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3
{return name;}
public String getAge()
{return age;}
public String getHob()
{return hob;}
public String getEmail()
{return email;}
public String getGender()
{return gender;}
public String getError()
{return error;}

public boolean validate()


{
boolean res=true;
if(name==null)
{
error+="<br>Please Enter Name....";
res=false;
}
if(age==null || age.length()>2)
{
error+="<br>Age Invalid";
res=false;
}
return res;
}
}
Output:

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3
Practical No. 4(C)
Aim:Create a registration and login JSP application to register and
authenticate the user based on username and password using JDBC.

HTML Code:

index.html
<html>
<head>
<title>jsp register</title>
</head>
<body>
<form action="jspregister.jsp" method="post">
Name:<input type="text" name="name">
<br>
Age:<input type="text" name="age">
<br>
Gender:<input type="radio" name="g" value="male">Male
<input type="radio" name="g" value="female">Female
<br>
Address:<input type="text" name="add”>
<br>
Phone :<input type="text" name="mob">
<br>
Email:<input type="text" name="mail">
<br>
Password:<input type="password" name="pass">
<br>
<input type="submit" value="Register">
</form>
</body>
</html>
jspregister.jsp

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


<html>
<body>

<%=" Registration Form"%>


<%

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3
String un=request.getParameter("name");
int age=Integer.parseInt(request.getParameter("age"));
String gen=request.getParameter("g");
String add=request.getParameter("add");
long phone=Long.parseLong(request.getParameter("mob"));
String mail=request.getParameter("mail");
String passwd=request.getParameter("pass");

Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/registration
04","root","root");
PreparedStatement ps = con.prepareStatement("insert into jspregister
values(?,?,?,?,?,?,?)");

ps.setString(1,un);
ps.setInt(2,age);
ps.setString(3,gen);
ps.setString(4,add);
ps.setLong(5,phone);
ps.setString(6,mail);
ps.setString(7,passwd);
int row = ps.executeUpdate();
System.out.println(row);

if(row==1)
{%>
<jsp:forward page="logpage.jsp"/>
<%}
else
{%>
<jsp:include page="index.html"/>
<%}
%>
</body>
</html>

Logpage.html
<%@page contentType="text/html" pageEncoding="UTF-8" import="java.sql.*" %>
<html>
<body>

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3
<form action="loginval.jsp">
Username:<input type="text" name="un">
<br>
Password:<input type="password" name="passwd">
<br>
<input type="submit" value="Login">
</form>
</body>
</html>
Loginval.jsp
<%--
Document :loginval
Created on : 6 Oct, 2018, 1:44:41 PM
Author : CKT
--%>
<%@page import="java.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 un = request.getParameter("un");
String passwd=request.getParameter("passwd"); %>
<%
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/registration
04","root","root");
PreparedStatementps = con.prepareStatement("select name,password from
jspregister where name=? and password=?");

ps.setString(1,un);
ps.setString(2,passwd);
ResultSet rs =ps.executeQuery();
if(rs.next())
{%>
<jsp:forward page="success.html"/>
<%}
else
{%>
<jsp:include page="logpage.jsp"/>
Login unsuccessfull !!!!

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3
<%}
con.close();
%>
</body>
</html>
Success.html
<html>
<body>
<h1><b>Login successfull !!!!</b></h1>
</body>
</html>

Output:

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3
Practical No. 5(A)
Aim:Create an html page with fields, eno, name, age, desg, salary.
Now on submit this data to a JSP page which will update the employee
table of database with matching eno.

Creating and inserting values in table:

create table employee04(enovarchar(10) PRIMARY KEY, ename varchar(50), salary


varchar(50),age varchar(50) ) ;
insert into employee04 values('101','priyanka','22000','22');
insert into employee04 values('102','jyoti','25000','19') ;
insert into employee04 values('103','pooja','21000','22');
insert into employee04 values('104','bilkish','21000','22') ;
insert into employee04 values('105','yogita','19500','22') ;

index.html
<html>
<body>
<form action="UpdateEmp04.jsp" >
Enter Employee Number<input type="text" name="txtEno" >
<br>
Enter Name<input type="text" name="txtName" >
<br>
Enter age<input type="text" name="txtAge" >
<br>
Enter Salary<input type="text" name="txtSal" >
<br>
<input type="reset" ><input type="submit" value="update " >
</form>
</body>
</html>

UpdateEmp04.jsp

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


<html><body>
<h1>Employee Record Update</h1>
<%
String eno=request.getParameter("txtEno");

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3
String name=request.getParameter("txtName");
String age = request.getParameter("txtAge");
String sal = request.getParameter("txtSal");

try{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/empd
b","root",
"root");
PreparedStatement stmt = con.prepareStatement("select * from
employee04 where eno=?");
stmt.setString(1, eno);
ResultSetrs = stmt.executeQuery();

if(rs.next())
{
out.println("<h1>~~~ Employee "+name+" Exist ~~~ </h1>");
PreparedStatement pst1= con.prepareStatement("update
employee04 set salary=? Where eno=?");
PreparedStatement pst2= con.prepareStatement("update
employee04 set age=? Where eno=?");
pst1.setString(1, sal);
pst1.setString(2, eno);
pst2.setString(1, age);
pst2.setString(2, eno);
pst1.executeUpdate();
pst2.executeUpdate();
}

else

out.println("<h1>Employee Record not exist !!!!!</h1>");


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

</body>

</html>

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3
Output:

After Updating:

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3
Practical No. 5(B)
Aim:Create a JSP page to demonstrate the use of Expression language.
Index.jsp

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


<% application.setAttribute("author","ABC");
session.setAttribute("city","mumbai");
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form action="show.jsp">
Enter First Name<input type="text" name="fname"><br>
Enter Last Name<input type="text" name="lname" ><br>
<input type="submit" value="Check EL">
</form>
</body>
</html>

show.jsp

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


<% pageContext.setAttribute("color","pink");%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body bgcolor="${pageScope.color}">
<b> Welcome ${param.fname} ${param.lname} </b><br>
<h3> Accessing Application Object </h3>
<p>
<b> Author Name:${applicationScope.author}</b>
</p>
<br>

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3
<h3> Accessing Session Object </h3>
<p>
<b> Author City:${sessionScope.city}</b>
</p>
<br>
<h3> Basic operations using EL </h3>
is 1 less than 2 ? ${1<2} <br>
addition:: ${6+3} <br>
multiplication:: ${9*3} <br>
<h3> Information about browser u are using</h3>
${header["user-agent"]}
</body>
</html>
Output:

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3
Practical No. 5(C)
Aim:Create a JSP application to demonstrate the use of JSTL.
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">
Enter First Name<input type="text" name="fname"><br>
Enter Last Name<input type="text" name="lname" ><br>
<input type="submit" value="Check JSTL Tags">
</form>
</body>
</html>

jstlDemo.jsp

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


<%@tagliburi="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Welcome to JSTL</title>
</head>
<body>
First Name:<c:out value="${param.fname}"/><br>
Last Name:<c:out value="${param.lname}"/><br>
use of if statement
<br>
<c:setvar="mycount" value="25"/>
<c:if test="${mycount==25}">
<b><c:out value="Your count is 25"/></b>
</c:if>
<br>

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3
Exception catching Example
<c:catchvar="myException">
<%int num=9/0;%>
</c:catch>
<b> The exception is: ${myException}</b>
</body>
</html>

Output:

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3
Practical No. 6
Aim:Create a Currency Converter application using EJB.
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 CC;

import java.io.IOException;
import java.io.PrintWriter;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import avax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import mybeans.CCBean;

public class CCServlet extends HttpServlet


{
@EJB CCBeanobj;

public void doGet(HttpServletRequest req, HttpServletResponse res)


throwsServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3
double amt = Double.parseDouble(request.getParameter("amt"));

if(req.getParameter("type").equals("r2d"))
{
out.println("<h1>"+amt+ " Rupees = "+obj.r2Dollor(amt)+"
Dollors</h1>");
}
if(req.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;
}

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3
Output:

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3
Practical No:7
Aim: Develop simple EJB application to demonstrate Servlet Hit
count using Singleton Session Beans.

Index.html
<html>
<head>
<title>Singleton Hit</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form method="post" action="ServletClient">
<input type="submit" value="HIT Me">
</form>
</body>
</html>

Path for Creating Bean:-


Right click on your web App→New→Other→Enterprise Bean→Session
Bean→Select Singleton Checkbox

CountHit.java

package ejb;

import javax.ejb.Singleton;

@Singleton
public class CountHit
{
private int hitCount;

public synchronized int incrementAndGetHitCount()


{
Return hitCount++;
}
}

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3
Create a servlet ServletClient

import ejb.CountHit;

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;

public class ServletClient extends HttpServlet

@EJB CountHit hit;

public void doGet(HttpServletRequest req, HttpServletResponse res)throws


IOException, ServletException

res.setContentType("text/html");

PrintWriter out=res.getWriter();

out.println("<h1 style=color:blue;>Number of times this servlet is accessed : "+


hit.incrementedandgetCount()+"</h1>");

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3
Output:

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3
Practical No:8
Aim: Develop simple shopping cart application using EJB [Stateful
Session Bean].

Shopping.jsp
<%@page import="mysayali.ShoppingCartLocal"%>
<%@page import="java.util.List"%>
<%@page import="javax.naming.InitialContext"%>

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


<%! private static ShoppingCartLocal con;
public void jspInit()
{
try
{
InitialContext ic=new InitialContext();

con=(ShoppingCartLocal)ic.lookup("java:global/currency/ShoppingCart");
}catch(Exception e)
{
System.out.println(e);
}
}
%>
<% if(request.getParameter("addBook")!=null)
{
String book=request.getParameter("t1");

con.addBook(book);

out.println("Added book successfully");

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

{
String book=request.getParameter("t1");
con.removeBook(book);
out.println("removed book successfully");

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3
}%>

<html>

<head>

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

<title>JSP Page</title>

</head>

<body>

<form method="POST">

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

<input type="submit" value="addBook" name="addBook">

<input type="submit" value="removeBook" name="removeBook">

<%

List <String> values=con.getContents();

out.println("<br> Your shopping cart");

for(String val:values)

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

out.println("<br> your shopping cart size:-"+values.size());

%>

</form>

</body>

</html>

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3
Path for Creating Bean:-
Right click on your web App→New→Other→Enterprise Bean→Session
Bean→Select Statefull Checkbox
ShoppingCart.java[bean]
package mysayali;

import static java.lang.System.out;

import java.util.ArrayList;

import java.util.List;

import javax.ejb.Stateful;

@Stateful

public class ShoppingCart implements ShoppingCartLocal

List <String> contents=new ArrayList<>();

public void addBook(String title)

contents.add(title);

public void removeBook(String title)throws Exception

boolean res=contents.remove(title);

if(res==false)

throw new Exception(title+"not in cart");

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3
}

public List<String>getContents()

return contents;

ShoppingCartLocal.java[interface]
package mysayali;

import java.util.List;

import javax.ejb.Remote;

@Remote

public interface ShoppingCartLocal

public void addBook(String title);

public void removeBook(String title) throws Exception;

public List<String> getContents();

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3
Output:

Adding Book from Bookshop: Displaying Books in


cart:

Removing Book from Bookshop: Displaying Books in


cart:

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3
Name:MANASVI PATIL Class: TY.BSc.IT(B)
Roll no.:61 Batch no.:3
Practical No:9
Aim: Develop a Hibernate application to store Feedback of
Website Visitor in Database.

Path for creating java class:-


Right click on Source package directory→Select New→Java
Class→class name ::-Feedback & Package Name::-hibernate

Feedback.java
package hibernate;
import javax.persistence.*;
@Entity
@Table(name="feedback")
public class Feedback implements java.io.Serializable
{
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)

@Column(name="userno")
private Integer userNo;

@Column(name="username")
private String userName;

@Column(name="email")
private String Email;

@Column(name="feedback")
private String Feedback;

@Column(name="feedbackdate")
private String feedbackDate;

public Feedback()
{
}

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3
public Integer getUserNo()
{
return userNo;
}

public void setUserNo(Integer userNo)


{
this.userNo = userNo;
}

public String getUserName()


{
return userName;
}

public void setUserName(String userName)


{
this.userName = userName;
}

public String getEmail()


{
return Email;
}

public void setEmail(String Email)


{
this.Email = Email;
}

public String getFeedback()


{
return Feedback;
}

public void setFeedback(String Feedback)


{
this.Feedback = Feedback;
}

public String getFeedbackDate()

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3
{
return feedbackDate;
}

public void setFeedbackDate(String feedbackDate)


{
this.feedbackDate = feedbackDate;
}

Adding Jar:-
Right click on Source Package directory then select Add jar/…
Add Hibernate Jar to Library folder and mysql connector jar for
database connectivity.

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3
Path for creating hibernate.cfg.xml:-
Right click on Source Package directory then select New then click on
Other then Select Hibernate folder in that type of file Select Hibernate
Configuration Wizard.

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

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3
Index.html
<html>
<head><title>JSP Form</title></head>
<body>
<h3> Please Enter your Feedback Here:</h3>
<form action="ViewFeedback.jsp" method="post">
<table border="0" cellpadding="0" cellspacing="2">
<tr>
<td align="right"> User Name:</td>
<td><input name="username" maxlength="25" size="47"
/></td>
</tr>
<tr>
<td align="right"> E Mail:</td>
<td><input name="email" maxlength="25" size="47" /></td>
</tr>
<tr>
<td align="right">Feedback:</td>
<td><textarea rows="5" cols="40"
name="feedback"></textarea></td>
</tr>
<tr>
<td colspan="2" align="right">
<input type="submit" name="btnSubmit" value="Submit"
/></td>
</tr>
</table>
</form>
</body>
</html>

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3
ViewFeedback.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"
import="org.hibernate.SessionFactory, org.hibernate.cfg.Configuration,
org.hibernate.Session, org.hibernate.Transaction, java.util.List,
java.util.Iterator,hibernate.Feedback"%>

<!DOCTYPE html>
<html>
<body>
<%! SessionFactory sf;
org.hibernate.Session hibSession;
%>

<%
sf=new Configuration().configure().buildSessionFactory();
hibSession=sf.openSession();
Transaction tx=null;
Feedback fb=new Feedback();
try
{
tx=hibSession.beginTransaction();
String un=request.getParameter("username");
String e=request.getParameter("email");
String f=request.getParameter("feedback");
String feedbackdate =""+new java.util.Date();
fb.setUserName(un);
fb.setEmail(e);
fb.setFeedback(f);
fb.setFeedbackDate(feedbackdate);
hibSession.save(fb);
tx.commit();
out.println("<h1><b>Thank u for your valuable Feedback<h1><b>");

}catch(Exception e)
{
out.println(e);
}
hibSession.close();
%>
</body>
</html>
OUTPUT:-
Name:MANASVI PATIL Class: TY.BSc.IT(B)
Roll no.:61 Batch no.:3
mySql::-

Index. jsp ViewFeedback.jsp

Name:MANASVI PATIL Class: TY.BSc.IT(B)


Roll no.:61 Batch no.:3

Anda mungkin juga menyukai