You are on page 1of 53

Program-1

Write a JavaScript that shows how a variables type can be changed onthe-fly.

<html>
<body>
<script type="text/javascript">
var a=10;
document.write(typeof(a));
a=12.5;
document.write("<br>");
document.write(typeof(a));
a='c';
document.write("<br>");
document.write(typeof(a));
a=true;
document.write("<br>");
document.write(typeof(a));
a="Chriag";
document.write("<br>");
document.write(typeof(a));
</script>
</body>
</html>

<html>
<script>
var a,b,c
a=5
b='a'
c=a+b
document.write("Adding number and words : " + c )
document.write("<br>");
a=5
b=10.5
Prepared By : Nitin Chikani

Page 1

c=a+b
document.write("Adding int and float : " + c )
document.write("<br>");
a=5
b=10.5
c=b/a
document.write("Division float and int : " + c )
</script>
</html>

Program-2
Write a JavaScript that demonstrates the use of +=,-=,*=,/= operators.

<html>
<body>
<script type="text/javascript">
var a=10;
document.write("Initial Value Of A Is: "+a);
document.write("<br>");
a+=10;
document.write("a+=10 : "+a);
document.write("<br>");
a-=10;
document.write("a-=10 : "+a);
document.write("<br>");
a*=10;
document.write("a*=10 : "+a);
document.write("<br>");
a/=10;
document.write("a/=10 : "+a);
</script>
</body>
Prepared By : Nitin Chikani

Page 2

</html>
<html>
<head>
<script type="text/javascript">
function fun()
{

document.write("1.Addition</br>");
document.write("2.Subtraction</br>");
document.write("3.Multiplication</br>");
document.write("4.Division</br>");
do
{
var a,b;
a = prompt("Enter value of a:");
b = prompt("Enter value of b:");
a = parseInt(a);
b = parseInt(b);
var ch;
ch = prompt("Enter your choice:");
document.write("</br>.............<b>OUTPUT</b>...........</br>");
switch(parseInt(ch))
{
case 1:
document.write("Addition:"+(a+=b)+"</br>");
break;
case 2:
document.write("Subtraction:"+(a-=b)+"</br>");
break;
case 3:
document.write("Multiplication:"+(a*=b)+"</br>");
break;
case 4:
document.write("Division:"+(a/=b)+"</br>");
break;
default:
document.write("Enter proper choice</br>");
}
Prepared By : Nitin Chikani

Page 3

document.write("Do u want to continue?...Press y....");


var s;
v = prompt("Enter Value:");
}while(v == 'y');
}
</script>
</head>
<body onload="fun()">
</body>
</html>

Program-3
Create a Form in HTML with two fields, minimum and maximum, write
JavaScript to validate that only numeric value is entered in both, and the value
entered in minimum is less than the value entered in maximum.

<html>
<head>
<script language="javascript">
function minnum(form)
{
var input;
input=document.myform.min.value;
if(parseInt(input)!=input)
{
alert("please enter a numeric value");
document.myform.min.value='';
}
var m1;
m1=document.myform.max.value;
if(parseInt(input)>parseInt(m1))
Prepared By : Nitin Chikani

Page 4

{
alert("Enter minimum value");
}

}
function maxnum(form)
{
var input1;
input1=document.myform.max.value;
if(parseInt(input1)!=input1)
{
alert("please enter a numeric value");
document.myform.max.value='';
}
}

</script>
</head>
<body>
<form name="myform">
<h4>MAX</h4>
<input type="text" value="" name="max" size=20 onBlur='maxnum(this.form)'>
<h4>MIN</h4>
<input type="text" value="" name="min" size=20 onBlur='minnum(this.form)'>
<br>
</body>
</html>

Prepared By : Nitin Chikani

Page 5

Program-4
Write a JavaScript that finds out multiples of 10 in 0 to 10000. On the click
of button start the timer and stop the counter after 10 seconds. Display on the
screen how many multiples of 10 are found out within stipulated time.

<html>
<head>
<title>(Type a title for your page here)</title>
<script type="text/javascript">
function func1( )
{
setTimeout ( "doSomething()", 10000 );
}
function doSomething( )
{
var i = 1;
for(i=1;i<10000;i++)
if(i%10==0)
document.write(i + ' , ');
}
</script>
</head>
<body >
<form name=f1>
<input type="button" name="clickMe" value="Start!"
onclick="func1()"/>
</form>
</body>
</html>

Prepared By : Nitin Chikani

Page 6

Program-5
Write a JavaScript to generate two random numbers and find out maximum
and minimum out of it.

<html>
<head>
<title>(Type a title for your page here)</title>
<script type="text/javascript">
function generate()
{
var my_num1=Math.random();
var my_num2=Math.random();
document.write('<br>First Random Number:' + my_num1);
document.write('<br>Second Random Number:' + my_num2);
if (my_num1 < my_num2)
{
document.write('<br><br>Minimum Number:' + my_num1);
document.write('<br>Maximum Number:' + my_num2);
}
else
{
document.write('<br><br>Minimum Number:' + my_num2);
document.write('<br>Maximum Number:' + my_num1);
}
}
</script>
</head>
<body >
<form name=f1>
<input type=button value='Display' onClick='generate()';>
</form>
</body>
</html>

Prepared By : Nitin Chikani

Page 7

<html>
<head>
<script language="Javascript">
function check()
{
var no1=Math.random();//generating 1st random number
var no2=Math.random();//generating 2nd random number
document.write(no1+"\r\n");//printing of 1st number
document.write("\n"+no2);//printing of 2nd number
if(no1>no2)
{
document.write("\nNumber One is Greater!!!\n"+no1);
}
else
{
document.write("\nNumber Two is Greater!!!\n"+no2);
}
}//end of function
</script>
</head>
<body onLoad="check()">
</body>
</html>

Prepared By : Nitin Chikani

Page 8

Program-6
Write a JavaScript to remove the highest element from the array and
arrange the array in ascending order.

<html>
<head>
<script type="text/javascript">
var a=new Array();
function funadd()
{
a.push(parseInt(document.frm.txtdata.value));
document.getElementById("pera").innerHTML=a;
document.frm.txtdata.value="";
document.frm.txtdata.focus();
}
function funremove()
{
var l=a.length;
for(i=0;i<=l;i++)
{
for(j=i+1;j<l;j++)
{
if(a[i]>a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
alert("The deleted element is: "+a.splice(l-1,1));
document.getElementById("msg").innerHTML="<b><u>Sorted Array:</u></b>";
document.getElementById("sortdata").innerHTML=a;
}
</script>
Prepared By : Nitin Chikani

Page 9

</head>
<body>
<form name=frm>
<input type="text" id="txtdata">
<input type=button value="ADD" onclick="funadd();">
<input type=button value="REMOVE" onclick="funremove();">
</br>
</br>
<b><u>Elements In Array:</u></b>
</form>
<p id=pera></p>
<p id=Msg></p>
<p id=sortdata></p>
</body>
</html>

<html>
<head>
<title>(Type a title for your page here)</title>
<script type="text/javascript">
function generate()
{
var myarray=[25, 8, 7, 41]
myarray.sort
(
function(a,b)
{
return b - a
}
)
alert ( myarray );
}
</script>
</head>
<body >
Prepared By : Nitin Chikani

Page 10

<form name=f1>
<input type=button value='Click for Sorting' onClick='generate()';>
</form>
</body>
</html>

Program-7
Write a JavaScript to convert Celsius to Fahrenheit.

<html>
<head>
<script language="javascript">
function convert(form,name)
{
if(name=="cel")
{
var f=5/9*(form.cel.value-32);
form.fer.value=f;
}
else
{
var c=9/5*(form.fer.value+32);
form.cel.value=c;
}

}
</script>
</head>
<body>
<form>
Celcious :<input type="text" name="cel" onblur="convert(this.form,this.name)">
<br/><br/>Ferenhit :<input type="text" name="fer"
onblur="convert(this.form,this.name)">

Prepared By : Nitin Chikani

Page 11

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

<script type="text/javascript">
function convert(Totalvalue)
{
var Far=(Totalvalue-32) * 5 / 9;
document.write(Totalvalue + ' Celsius = ' + Far + ' Farenheit');
}
</script>

<body onload="convert(102)">
</body>

<html>
<head>
<script language ="Javascript">
function convert()
{
if(t1.value!= "")//check if first value is not null
{
var tmp=parseFloat(t1.value)*33.8;//convert it to float
t2.value=tmp;//storing of above calculation into t2
}
else//if first value is null
{
t2.value="";
t1.focus();//only focus on 1st textbox
alert("Enter Value := ");
}
}//end of function

Prepared By : Nitin Chikani

Page 12

</script>
</head>

Program-8
Write a JavaScript to find a string from the given text. If the match is found
then replace it with another string.

<html>
<head>
<script type="text/javascript">
function findout(form)
{
var str=new String(form.string1.value);
form.string1.value=str.replace(form.find.value,form.replac.value);
}
</script>
</head>
<body >
<form>
Enter a Text : <input type="text" name="string1" size=50><br/><br/>
Word to find : <input type="text" name="find" ><br/>
Word to Replace : <input type="text" name="replac"><br/>
<input type="button" value="REPLACE" onClick="findout(this.form)">
</form>
</body>
</html>

<HTML>
<HEAD>
<TITLE> STRING </TITLE>
<SCRIPT LANGUAGE="javascript">
var i;
var j,f;
Prepared By : Nitin Chikani

Page 13

var myString;
var sString;
var strl,fl;
var temp=new Array();
function str_find()
{
myString=(document.getElementById("txt1").value);
sString=(document.getElementById("txt2").value);
strl=myString.length;
fl=sString.length;
for(i=0;i<strl;i++)
{
temp[i]=myString.substring(i,fl+i);
}
for(i=0;i<temp.length;i++)
{
if(temp[i]==sString)
{
f=0;
break;
}
else
f=1;
}
if(f==0)
alert("Found..");
else
alert("Not Found..");
}
</SCRIPT>
</HEAD>
<BODY>
<FONT FACE="Bookman Old Style"><H2>
4].Write a JavaScript to find a string from the given text.</H2></FONT><HR>
<BR><BR><BR>
<TABLE ALIGN="CENTER">
Prepared By : Nitin Chikani

Page 14

<TR>
<TD><B>Enter String : </B></TD>
<TD><INPUT TYPE="Text" ID="txt1" SIZE="30%" ALIGN="right"></TD>
</TR>
<TR>
<TD><B>Enter String To Search : </B></TD>
<TD><INPUT TYPE="Text" ID="txt2" SIZE="30%"></TD>
</TR>
<TR></TR><TR></TR><TR></TR><TR></TR><TR></TR><TR></TR><TR></TR>
<TR>
<TD COLSPAN="2" align="center"><INPUT TYPE="button" VALUE=" SEARCH"
onClick="str_find()"><TD>
</TR>
</TABLE>
</BODY>

</HTML>
Program-9
Write a JavaScript to show a pop up window with a message Hello and
background color lime and with solid black border.

<html>
<head>
<style>
.rb { border : 10px solid black}
</style>
<script>
function check()
{
var opop=window.createPopup();
var a,b;
if(openwin.name.value=="")
{
Prepared By : Nitin Chikani

Page 15

alert("Enter Your Name");


openwin.name.focus();
}
else
{ a=window.open("", "mywindow", "location=1,status=1,
scrollbars=1,height=500,width=600 style=\"border : 10px \"");
a.document.write("Wel Come "+openwin.name.value.toUpperCase());
a.document.write('<br><input type="button" onClick="self.close()"
value="CLOSE"></p>');
a.document.body.bgColor='lime';
a,document.body.border=10;
b=a.document.body;
b.style.borderWidth=25;
b.style.borderStyle='solid';

}
}
</script>
</head>
<body class="rb">
<form name="openwin">
Enter Name<input type="text" name="name" value="" style="color:red"><br>
<input type="button" name="open" value="Open New Window" style="color:green"
onClick="check();">
</form>
</body>
</html>

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


<html>
<head>
<title>JavaScript Popup Example</title>
</head>
<script type="text/javascript">
function poponload()
{
Prepared By : Nitin Chikani

Page 16

testwindow = window.open("", "mywindow",


"location=1,status=1,scrollbars=1,width=300,height=100,border:2px solid #ffffff;");
testwindow.moveTo(200, 200);
testwindow.document.write('<h1>HELLO!</h1>');
testwindow.document.bgColor = "#BFFF00";
}
</script>
<body onload="poponload()">
<h1>JavaScript Popup Example 3</h1>
</body>
</html>

Program-10
Write a Servlet to display Hello World on browser.

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Ex10Http extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse res)
throws IOException,ServletException
{
PrintWriter out = res.getWriter();
res.setContentType("text/html");
out.println("Hello World....");
}
}

Prepared By : Nitin Chikani

Page 17

Program-11
Write a Servlet to display all the headers available from request.

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import javax.servlet.annotation.*;
/** Shows all the request headers sent on the current request. */
@WebServlet("/RequestHeaders")
public class ShowRequestHeaders extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Servlet Example: Showing Request Headers";
out.println("<HTML>\n" +
"<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=\"CENTER\">" + title + "</H1>\n" +
"<B>Request Method: </B>" +
request.getMethod() + "<BR>\n" +
"<B>Request URI: </B>" +
request.getRequestURI() + "<BR>\n" +
"<B>Request Protocol: </B>" +
request.getProtocol() + "<BR><BR>\n" +
"<TABLE BORDER=1 ALIGN=\"CENTER\">\n" +
"<TR BGCOLOR=\"#FFAD00\">\n" +
"<TH>Header Name<TH>Header Value");
Enumeration headerNames = request.getHeaderNames();
while(headerNames.hasMoreElements()) {
String headerName = (String)headerNames.nextElement();
out.println("<TR><TD>" + headerName);
out.println(" <TD>" + request.getHeader(headerName));
}
out.println("</TABLE>\n</BODY></HTML>");
}
Prepared By : Nitin Chikani

Page 18

/** Since this servlet is for debugging, have it


* handle GET and POST identically.
*/
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}

Program-12
Write a Servlet to display parameters available on request.

-----------HTML CODE-------------<HTML><HEAD><TITLE>Collecting Parameters</TITLE></HEAD>


<BODY BGCOLOR="#FDF5E6">
<H1 ALIGN="CENTER">Collecting Parameters</H1>
<FORM ACTION="http://localhost:8081/CNP/params">
First Parameter: <INPUT TYPE="TEXT" NAME="param1"><BR>
Second Parameter: <INPUT TYPE="TEXT" NAME="param2"><BR>
Third Parameter: <INPUT TYPE="TEXT" NAME="param3"><BR>
<CENTER><INPUT TYPE="SUBMIT"></CENTER>
</FORM>
</BODY>
</HTML>
-----------SERVLET------------------import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
/** Simple servlet that reads parameters from the
* form data.
*/
public class Params extends HttpServlet {
Prepared By : Nitin Chikani

Page 19

public void doGet(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Reading Request Parameters";
out.println("<HTML>\n" +
"<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=\"CENTER\">" + title + "</H1>\n" +
"<UL>\n" +
" <LI><B>param1</B>: "
+ request.getParameter("param1") + "\n" +
" <LI><B>param2</B>: "
+ request.getParameter("param2") + "\n" +
" <LI><B>param3</B>: "
+ request.getParameter("param3") + "\n" +
"</UL>\n" +
"</BODY></HTML>");
}
}

Program-13
Write a Servlet to display all the attributes available from request and
context.

import javax.servlet.*;
import java.util.*;
import java.io.*;
import javax.servlet.http.*;
public class RequestParameters implements Servlet
{
public void init(ServletConfig config) throws ServletException
{
}

Prepared By : Nitin Chikani

Page 20

public void destroy(){}


public void service(ServletRequest request, ServletResponse response) throws
ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("Server Port : " + request.getServerPort());
out.println("<BR> Server Name : " + request.getServerName());
out.println("<BR> Protocol : " + request.getProtocol());
out.println("<BR> Character Encoding : " + request.getCharacterEncoding());
out.println("<BR> Content Type : " + request.getContentType());
out.println("<BR> Content Length : " + request.getContentLength());
out.println("<BR> Remote Address : " + request.getRemoteAddr());
out.println("<BR> Remote Host : " + request.getRemoteHost());
Enumeration parameters = request.getParameterNames();
while(parameters.hasMoreElements())
{
String ParaName= (String) parameters.nextElement();
out.println("Parameter Name : " + ParaName);
out.println("Parameter Value: " + request.getParameter(ParaName));
out.println("<BR>");
}
Enumeration attributes = request.getAttributeNames();
while(attributes.hasMoreElements())
{
String attName = (String) attributes.nextElement();
out.println("<BR> Attribute Name : " + attName);
out.println("<BR> Attribute Value : " + request.getAttribute(attName));
out.println("<BR>");
}
}
public String getServletInfo(){return null;}
public ServletConfig getServletConfig(){return null;}
}

Prepared By : Nitin Chikani

Page 21

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
/** Shows all the request headers sent on the current request. */
public class prog13 extends HttpServlet {
public void doGet(HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String title = "Servlet Example: Showing Request Headers";
String docType ="<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
"Transitional//EN\">\n";
out.println(docType + "<HTML>\n" + "<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=\"CENTER\">" + title + "</H1>\n" +
"<B>Request Method: </B>" +
req.getMethod() + "<BR>\n" +
"<B>Request URI: </B>" +
req.getRequestURI() + "<BR>\n" +
"<B>Request Protocol: </B>" +
req.getProtocol() + "<BR><BR>\n" +
"<TABLE BORDER=1 ALIGN=\"CENTER\">\n" +
"<TR BGCOLOR=\"#FFAD00\">\n" +
"<TH>Header Name<TH>Header Value");
Enumeration headerNames = req.getHeaderNames();
while(headerNames.hasMoreElements())
{
String headerName = (String)headerNames.nextElement();
out.println("<TR><TD>" + headerName);
out.println(" <TD>" + req.getHeader(headerName));
}
out.println("</TABLE>\n<h2>Mail:mca.nikhilprajapati@gmail.com</h2></BODY></HTM
L>");
}
/** Since this servlet is for debugging, have it
Prepared By : Nitin Chikani

Page 22

* handle GET and POST identically.


*/
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}

Program-14
Write a Servlet which displays a message and also displays how many
times the message has been displayed (how many times the page has been
visited).

//WEB.XML FILE
<web-app>
<servlet>
<servlet-name>prog_14</servlet-name>
<servlet-class>counter</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>prog_14</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
//M09005
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class counter extends HttpServlet
{
public void doGet(HttpServletRequest req , HttpServletResponse res) throws
IOException , ServletException
{
PrintWriter out = res.getWriter();
Prepared By : Nitin Chikani

Page 23

Cookie[]ck = req.getCookies();
if(ck != null)
{
for(int i=0; i<ck.length;i++)
{
Cookie c = ck[i];
String s = c.getName();
if(s.equals("diz"))
{
String val = c.getValue();
int v = Integer.parseInt(val);
v++;
val=String.valueOf(v);
Cookie nc = new Cookie("diz",val);
res.addCookie(nc);
out.println("Visit No:"+val);
return;
}
}
Cookie c1 = new Cookie("diz","0");
res.addCookie(c1);
out.println("Cookie is created ..refresh the page..");
}
}
}

Prepared By : Nitin Chikani

Page 24

Program-15
Assume that we have got three pdf files for the MCA-1 Syllabus, MCA-2
Syllabus and MCA-3 Syllabus respectively, Now write a Servlet which displays the
appropriate PDF file to the client, by looking at a request parameter for the year
(1, 2 or 3).

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ShowRequestPDF extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)throws
ServletException,IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String st = "Load PDF Files";
out.println("<title>"+ st +"</title><body><center>");
out.println("<FORM METHOD=POST>");
out.println("<select size=1 name=syll><BR><BR>");
out.println("<option>MCA1</option>");
out.println("<option>MCA2</option>");
out.println("<option>MCA3</option>");
out.println("</select><BR><BR>");
out.println("<INPUT TYPE=SUBMIT value=Show>");
out.println("</FORM>");
out.println("</center></body>");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws
ServletException, IOException
{
String st = request.getParameter("syll");
response.setContentType("application/pdf");
if(st.equals("MCA1"))
{
response.sendRedirect("MCA_I.pdf");
Prepared By : Nitin Chikani

Page 25

}
else if(st.equals("MCA2"))
{
response.sendRedirect("MCA_II.pdf");
}
else if(st.equals("MCA3"))
{
response.sendRedirect("MCA_III.pdf");
}
}
}

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Ex15 extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws IOException,ServletException
{
String a;
res.setContentType("application/pdf");
PrintWriter out=res.getWriter();
a=req.getParameter("pdfd");
//res.sendRedirect("http://localhost:8080/dc1.pdf");
if(a.equals("pdf1"))
{
res.sendRedirect("http://localhost:8080/dc1.pdf");
}
if(a.equals("pdf2"))
{
res.sendRedirect("http://localhost:8080/dc2.pdf");
}
if(a.equals("pdf3"))
{
res.sendRedirect("http://localhost:8080/dc3.pdf");
}
}
Prepared By : Nitin Chikani

Page 26

Program-16
Assume that the information regarding the marks for all the subjects of a
student in the last exam are available in a database, Develop a Servlet which
takes the enrollment number of a student as a request parameter and displays the
mark sheet for the student.

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class DisplayMarksheet extends HttpServlet
{
private String en;
public void init()
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //Loads Driver for Connection
}
catch(ClassNotFoundException nf)
{
//System.out.println(nf);
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<HTML>");
out.println("<HEAD>");
out.println("<TITLE> STUDENT MARKSHEET....</TITLE>");
out.println("</HEAD>");
out.println("<BODY BGCOLOR=#D8BFD8>");
out.println("<CENTER>");
Prepared By : Nitin Chikani

Page 27

out.println("<H1> Marksheet...</H1>");
out.println("<FORM METHOD=POST>");
out.println("Enrollment No.: <input type=TEXT name = T1 >");
out.println("<BR><BR><input type=submit value=SEARCH>");
out.println("</FORM>");
out.println("</CENTER>");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
//doGet(request, response);
en = request.getParameter("T1");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<center>");
String sql = "select enroll,scode,sname,grade";
sql = sql + " from marks";
sql = sql + " where enroll = " + en + ";";
try
{
Connection con = DriverManager.getConnection("jdbc:odbc:stud");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(sql);
out.println("<h1> Marksheet of SEM-III </h1>");
out.println("<BR><b> Enrollment No.:</b>" + en);
out.println("<BR><BR>");
out.println("<TABLE BORDER=1 COLOR=RED BGCOLOR=#F8F8FF>");
out.println("<TH ALIGN=CENTER> SUBJECT CODE </TH>");
out.println("<TH ALIGN=CENTER> SUBJECT NAME </TH>");
out.println("<TH WIDTH=15 ALIGN=CENTER> GRADE </TH>");
if(rs == null)
{
out.println("<h2> No Records.... </h2>");
}
else
{
while(rs.next())
{
Prepared By : Nitin Chikani

Page 28

out.println("<TR>");
out.println("<TD ALIGN=CENTER>");
out.println(rs.getString(2));
out.println("</TD>");
out.println("<TD ALIGN=CENTER>");
out.println(rs.getString(3));
out.println("</TD>");
out.println("<TD ALIGN=CENTER>");
out.println(rs.getString(4));
out.println("</TD>");
out.println("</TR>");
}
rs.close();
st.close();
con.close();
}
}
catch(SQLException sqlex)
{
out.println(sqlex);
}
catch(Exception e)
{
out.println(e);
}
out.println("</TABLE>");
out.println("</CENTER>");
out.println("<BODY>");
out.println("</BODY>");
out.println("</HTML>");
}
}

Prepared By : Nitin Chikani

Page 29

Program-18
Develop a Servlet to authenticate a user, where the loginid and password
are available as request parameters. In case the authentication is successful, it
should setup a new session and store the user's information in the session
before forwarding to home.jsp, which displays the user's information like full
name, address, etc.

<html>
<body>
Note : enter username=dev
Password=devdip
<form method="post" action="/myapp/servlet/pra18">
UserName : <input type="text" name="un"><br/>
Password : <input type="password" name="pw"><br/>
<input type="submit" value="Submit" >
</form>
</body>
</html>

<!__ put this file in myapp folder __>


<html>
<body>
<h1>Well Come To My Home Page</h1>
<%
HttpSession sessi=request.getSession();
%>
Name : <%= session.getAttribute("Name") %><br/>
SurName : <%= session.getAttribute("Sur") %><br/>
Adsress : <%= session.getAttribute("Add") %><br/>
</body>
</html>
// put this file in classes folder
import java.io.*;
Prepared By : Nitin Chikani

Page 30

import javax.servlet.*;
import javax.servlet.http.*;
public class pra18 extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException,ServletException
{
response.setContentType("text/html");
PrintWriter out=response.getWriter();
String user=request.getParameter("un");
String pass=request.getParameter("pw");

if(user.equals("dev") && pass.equals("devdip"))


{
out.println("<html>");
out.println("<body>");
out.println("<form>");
out.println("Name : <input type=text name=nam ><br/>");
out.println("Surname : <input type=text name=snam ><br/>");
out.println("Address : <input type=text name=add><br/>");
out.println("<input type=submit value=submit>");
}
else
{
response.sendRedirect("../p18.html");
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
IOException,ServletException
{
HttpSession session=request.getSession();
session.setAttribute("Name",request.getParameter("nam"));
Prepared By : Nitin Chikani

Page 31

session.setAttribute("Sur",request.getParameter("snam"));
session.setAttribute("Add",request.getParameter("add"));
response.sendRedirect("../home.jsp");
}
}
Program-19
Write a simple JSP page to display a simple message (It may be a simple
html page).

<html>
<head>
<title></title>
</head>
<body>
<%= "Hello.........!!!"%>
</body>
</html>

Program-20
Write a JSP page, which uses the include directive to show its header and
footer.

Header
-----<html>
<head>
<title></title>
</head>
<body>
<%="<center>Header::Welcome</center>"%>
Prepared By : Nitin Chikani

Page 32

</body>
</html>
-----Footer
-----<html>
<head>
<title></title>
</head>
<body>
<%="Footer: Date:"%>
<%= new java.util.Date()%>
</body>
</html>

Program-23
Develop a interest calculation application in which user will provide all
information in HTML form and that will be processed by servlet and response will be
generated back to the user.

<html>
<head>
<script language="javascript">
function check(form)
{
if(form.total.value=="")
{
form.total.value="Enter Valid Value";
}
if(form.rate.value=="")
{
form.rate.value="Enter Valid Value";
Prepared By : Nitin Chikani

Page 33

}
if(form.duration.value=="")
{
form.duration.value="Enter Valid Value";
}
}
</script>
</head>
<body>
<form action="/myapp/servlet/interest">
<center>
<big><blink>INTEREST CALCULATOR</blink></big><br/><br/>
<b>Total Amount :</b><input type="text" name="total"><br/>
<b>Interest Rate :<b><input type="text" name="rate" > %<br/>
<b>Duration :</b><input type="text" name="duration"
onBlur="check(this.form)">Months<br/>
<br/><input type="submit" value="Calculate" >
</center>
</body>
</html>
//interest.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class interest extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response) throws
IOException,ServletException
{
response.setContentType("text/html");
PrintWriter out=response.getWriter();
float total=Float.parseFloat(request.getParameter("total"));
float rate=Float.parseFloat(request.getParameter("rate"));
float duration=Float.parseFloat(request.getParameter("duration"));
Prepared By : Nitin Chikani

Page 34

float intr=(total*rate*duration)/100;
total=total+intr;
out.println("<html><body>");
out.println("<B><h3>your Interest Amount is "+intr);
out.println("And Total Amout will be "+total+"</h3><b>");
out.println("</body></html>");
}
}

Program-24
Develop an application to demonstrate how the client (browser) can remember
the last time it visited a page and displays the duration of time since its last visit.
(Hint: use Cookie).

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
/** Servlet that uses session tracking to keep per-client
* access counts. Also shows other info about the session.
*/
public class gtu24 extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
HttpSession session = request.getSession();
Date d1 = new Date(session.getCreationTime());
Date d2 = new Date(session.getLastAccessedTime());
double d;
String heading;
Integer accessCount =
(Integer)session.getAttribute("accessCount");
if (accessCount == null) {
Prepared By : Nitin Chikani

Page 35

accessCount = new Integer(0);


heading = "Welcome, Newcomer";
} else {
heading = "Welcome Back";
accessCount = new Integer(accessCount.intValue() + 1);
}
// Integer is an immutable data structure. So, you
// cannot modify the old one in-place. Instead, you
// have to allocate a new one and redo setAttribute.
session.setAttribute("accessCount", accessCount);
PrintWriter out = response.getWriter();
String title = "Session Tracking Example";
out.println("<HTML>\n" +
"<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<CENTER>\n" +
"<H1>" + heading + "</H1>\n" +
"<H2>Information on Your Session:</H2>\n" +
"<TABLE BORDER=1>\n" +
"<TR BGCOLOR=\"#FFAE00\">\n" +
" <TH>Info Type<TH>Value\n" +
"<TR>\n" +
" <TD>Creation Time\n" +
" <TD>" +
d1 + "\n" +
"<TR>\n" +
" <TD>Time of Last Access\n" +
" <TD>" +
d2 + "</TD> \n" +
"<TR>" );
Dates dt = new Dates();
d = dt.DifferenceInSeconds(d2,d1);
out.println("<TD>Duration Since Last Access </TD>"+ "\n" +
"<TD>" + d + "(Seconds)</TD>"+ "\n" +
"<TR>\n"+
"<TD>Number of Previous Accesses\n" +
"<TD>" + accessCount + "\n" +
"</TABLE> \n" +
"</CENTER></BODY></HTML>");
}
Prepared By : Nitin Chikani

Page 36

//Dates.java
import java.io.*;
import java.util.*;
public class Dates
{
public static double DifferenceInMonths(Date date1, Date date2)
{
return DifferenceInYears(date1, date2) * 12;
}
public static double DifferenceInYears(Date date1, Date date2)
{
double days = DifferenceInDays(date1, date2);
return days / 365.2425;
}
public static double DifferenceInDays(Date date1, Date date2)
{
return DifferenceInHours(date1, date2) / 24.0;
}
public static double DifferenceInHours(Date date1, Date date2)
{
return DifferenceInMinutes(date1, date2) / 60.0;
}
public static double DifferenceInMinutes(Date date1, Date date2)
{
return DifferenceInSeconds(date1, date2) / 60.0;
}
public static double DifferenceInSeconds(Date date1, Date date2)
{
return DifferenceInMilliseconds(date1, date2) / 1000.0;
}

Prepared By : Nitin Chikani

Page 37

public static double DifferenceInMilliseconds(Date date1, Date date2)


{
return Math.abs(GetTimeInMilliseconds(date1) - GetTimeInMilliseconds(date2));
}
private static long GetTimeInMilliseconds(Date date)
{
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return cal.getTimeInMillis() + cal.getTimeZone().getOffset(cal.getTimeInMillis());
}
}
//web_xml_entry
<servlet>
<servlet-name>gtu_24</servlet-name>
<servlet-class>gtu24</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>gtu_24</servlet-name>
<url-pattern>/24</url-pattern>
</servlet-mapping>

Prepared By : Nitin Chikani

Page 38

Program-28
Develop a program to perform the database driven operation like insert,
Delete, Update and select. To perform the above operations create one table
named Employee.
Field Name
Field Type
EmpId
Integer
Empname
Varchar
Emp_desig
Varchar
Emp_J_Date
Varchar
Emp_Salary
Numeric

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class DbOperations extends HttpServlet
{
private String Name, desig, j_date;
private int id, emp_sal;
private String msg, action;
public void init()
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");//Loads Driver...
}
catch(ClassNotFoundException nf)
{
//System.out.println(nf);
}
}
public void sendEmployeeForm(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
{
PrintWriter out = response.getWriter();
out.println("<BR> <H2> Employee Form </H2></BR>");
out.println("<BR> Please Enter Details </BR>");
out.println("<BR> <FORM Method = POST>");
out.println("<TABLE>");
Prepared By : Nitin Chikani

Page 39

out.println("<TR><TD> Employee ID :</TD><TD><INPUT TYPE = TEXT Name =


eid></TD></TR>");
out.println("<TR><TD> Employee Name :</TD><TD><INPUT TYPE = TEXT Name =
ename></TD></TR>");
out.println("<TR><TD> Employee Designation :</TD><TD><INPUT TYPE = TEXT
Name = edesig></TD></TR>");
out.println("<TR><TD> Employee Joining Date :</TD><TD><INPUT TYPE = TEXT
Name = ejdate></TD></TR>");
out.println("<TR><TD> Employee Salary :</TD><TD><INPUT TYPE = TEXT Name =
esal></TD></TR>");
out.println("</TABLE>");
out.println("<TABLE>");
out.println("<TR><TD> <INPUT TYPE = SUBMIT Value = Insert name=val></TD>");
out.println("<TD><INPUT TYPE = SUBMIT Value = Delete name=val></TD>");
out.println("<TD><INPUT TYPE = SUBMIT Value = Update name=val></TD>");
out.println("<TD><INPUT TYPE = SUBMIT Value = Search name=val></TD>");
out.println("<TD><INPUT TYPE = RESET Value = Clear></TD></TR>");
out.println("</TABLE>");
out.println("</FORM>");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String mysql = null;
sendPageHeader(response);
id = Integer.parseInt(request.getParameter("eid"));
Name = request.getParameter("ename");
desig = request.getParameter("edesig");
j_date = request.getParameter("ejdate");
emp_sal = Integer.parseInt(request.getParameter("esal"));
try
{
action = request.getParameter("val");
PrintWriter out = response.getWriter();
Connection con = DriverManager.getConnection("jdbc:odbc:Employee");
Statement st = con.createStatement();
mysql = "Select * From empInfo ";
mysql = mysql + " Where Empname = '" + id + "'";
ResultSet rs = st.executeQuery(mysql);
out.println("Parameter Value = " +action);
Prepared By : Nitin Chikani

Page 40

if(action.toString()=="Insert")
{
if(rs.next())
{
rs.close();
msg = " Duplicate Employee ... Enter other name ...";
}
else
{
rs.close();
mysql = "Insert into empInfo";
mysql = mysql + "(EmpId,Empname,Emp_desig,Emp_J_Date,Emp_Salary)";
mysql = mysql + " Values ("+ id + ",'";
mysql = mysql + Name + "','";
mysql = mysql + desig + "','";
mysql = mysql + j_date + "',";
mysql = mysql + emp_sal +")";
out.println(mysql+"<BR>");
int i = st.executeUpdate(mysql);
if(i==1)
{
msg = " Successfully Added One Employee..." + Name;
}
}
}
else if(action.toString()=="Update")
{
}
st.close();
con.close();
}catch(SQLException se)
{
PrintWriter pw = response.getWriter();
pw.println("<BR> <B> SQL Statement : ===> " + mysql + " </B>");
pw.println("<BR> <B> Some Error ==> " + se.toString() + " </B>");
pw.println("<HR><BR>");
}
sendPageFooter(response);
}
Prepared By : Nitin Chikani

Page 41

public void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
sendPageHeader(response);
sendEmployeeForm(request,response);
sendPageFooter(response);
}
public void sendPageHeader(HttpServletResponse res) throws ServletException,
IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<HTML>");
out.println("<HEAD>");
out.println("<TITLE> Employee Database Driven Operation </TITLE>");
out.println("</HEAD>");
out.println("<BODY>");
out.println("<CENTER>");
}
public void sendPageFooter(HttpServletResponse res) throws ServletException,
IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("</TABLE>");
out.println("</CENTER>");
out.println("</BODY>");
out.println("</HTML>");
}
}

Prepared By : Nitin Chikani

Page 42

Program-29
Develop a Java application to perform the database driven operation like
insert, Delete, Update and selection using PreparedStatement. To perform the
above operations use the table from above exercise.

import java.sql.*;
import java.util.Scanner;
public class gtu29 {
public static void main(String a[])
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch(ClassNotFoundException cnf)
{
System.out.println("Error : "+cnf);
}
String mysql = null;
int ch=0;
while(ch!=5)
{
System.out.println("\n====== MAIN MENU ===============\n");
System.out.println("1. Insert");
System.out.println("2. Update");
System.out.println("3. Delete");
System.out.println("4. Search");
System.out.println("5. Exit");
System.out.print("Enter Your Choice :");
Scanner s = new Scanner(System.in);
ch = s.nextInt();
try
{
Connection con = DriverManager.getConnection("jdbc:odbc:Employee");
PreparedStatement st;
int i;
switch(ch)
{
case 1:
Prepared By : Nitin Chikani

Page 43

mysql = "insert into empInfo values(?,?,?,?,?)";


st = con.prepareStatement(mysql);
st.setInt(1, 1004);
st.setString(2,"Pandya Chaitanya");
st.setString(3,"Manager");
st.setString(4,"20-01-2010");
st.setInt(5,15000);
st.executeUpdate();
i = st.executeUpdate();
if(i == 1)
{
System.out.println("Inserted.....");
}
break;
case 2:
mysql = "UPDATE empInfo SET Emp_Salary = ? WHERE empid = ?";
st = con.prepareStatement(mysql);
st.setInt(1,5000);
st.setInt(2,1004);
st.executeUpdate();
i = st.executeUpdate();
if(i == 1)
{
System.out.println("Updated.....");
}
break;
case 3:
mysql = "delete from empInfo where EmpId = ?";
st = con.prepareStatement(mysql);
st.setInt(1,1004);
st.executeUpdate();
i = st.executeUpdate();
if(i >= 1)
{
System.out.println("Deleted.....");
}
break;
case 4:
mysql = "select * from empInfo where empid = ?";
st = con.prepareStatement(mysql);
Prepared By : Nitin Chikani

Page 44

st.setInt(1,1004);
ResultSet rs = st.executeQuery();
System.out.println("Empid \t EmpName \t EmpDesig \t EmpJ_Date \t
Salary");
while(rs.next())
{
System.out.print(rs.getInt(1));
System.out.print("\t"+rs.getString(2));
System.out.print("\t"+rs.getString(3));
System.out.print("\t"+rs.getString(4));
System.out.print("\t"+rs.getInt(5)+"\n"));
}
break;
case 5:
System.exit(0);
}
}
catch(SQLException se)
{
System.out.println("Error in SQL : "+se);
}
}
}
}

Program-30
Write a Java application to invoke a stored procedure using a
CallableStatement. For this a stored procedure called incrementSalary may be
developed to increase all the employees salary by a percentage specified in the
parameter.

//incrementsalary.sql
set serveroutput on
create or replace procedure IncSal(percent IN NUMBER)
is
BEGIN
UPDATE employee
Prepared By : Nitin Chikani

Page 45

SET empsal = empsal + (empsal*(percent/100));


commit;
END IncSal;
/
//JAVA File
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class p30 extends HttpServlet
{
public void init() throws ServletException
{
try
{
// Loads Driver
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch(Exception e)
{
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out=response.getWriter();
String query;
try
{
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@://localhost:1521/orcl","scott","t
iger");
Statement st= con.createStatement();

Prepared By : Nitin Chikani

Page 46

String operation=request.getParameter("button");
//out.println(operation);

if(operation.equals("Update"))
{
float inc=Float.parseFloat(request.getParameter("inc"));
query="{ call IncSal(?) }";
CallableStatement cst=con.prepareCall(query);
cst.setFloat(1,inc);
cst.execute();
out.println("Incremented successfully");
}
if(operation.equals("View"))
{
query="select * from employee";
ResultSet rs=st.executeQuery(query);
out.println("<html>");
out.println("<body>");
out.println("<center>");
out.println("<h1> Employee Information </h1>");
out.println("<br><br>");
out.println("<table border=1 color=red bgcolor=yellow>");
out.println("<th> EmpId </th>");
out.println("<TH> EmpName </th>");
out.println("<TH> EmpDesignation </th>");
out.println("<TH> EmpJoining Date </th>");
out.println("<TH> EmpSalary </th>");
if(rs==null)
{
out.println("<h2> No Records </h2> ");
}
else
Prepared By : Nitin Chikani

Page 47

{
while(rs.next())
{
out.println("<tr>");
out.println("<td>");
out.println(rs.getString("empid"));
out.println("</td>");
out.println("<td>");
out.println(rs.getString("empname"));
out.println("</td>");
out.println("<td>");
out.println(rs.getString("empdes"));
out.println("</td>");
out.println("<td>");
out.println(rs.getString("empjd"));
out.println("</td>");
out.println("<td>");
out.println(rs.getString("empsal"));
out.println("</td>");
out.println("</tr>");
}
rs.close();
st.close();
con.close();
}

out.println("</table>");
out.println("</body>");
out.println("</html>");
}
catch(Exception e)
{
out.println(e);
}
Prepared By : Nitin Chikani

Page 48

}
}
//JSP file
<HTML>
<HEAD>
</HEAD>
<BODY>
<h1>Increment Salary of Employee Table percent wise</h1>
<FORM action="/myapp/servlet/p30">
<TABLE>
<TR><TD>Increment percentage:<td><input type="text" name="inc"> %
<TR><TD><INPUT TYPE="radio" name="button" value="Update">:Increment
Salary
<TD><INPUT TYPE="radio" name="button" checked value="View">View
<tr><td align="center"><input type="submit" value="GO">
<td><input type="reset" value="reset">
</TABLE>
</FORM>
</BODY>
</HTML>

Program-31
Write a JSP page which uses tags availabe from the standard tag library
JSTL.

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


<BR><B>C:OUT TAG</B><BR>
<c:out value="Hello World"/>
<BR>
<BR><B>C:FOREACH TAG</B><BR>
<UL>
<c:forEach var="i" begin="1" end="5" step="1">
<LI> ${i}
</c:forEach>
Prepared By : Nitin Chikani

Page 49

</UL>
<BR><B>C:FORTOKENS TAG</B><br>
<UL>
<c:forTokens var="color"
items="(red (orange) yellow)(green)((blue) violet)"
delims="()">
<LI>${color}
</c:forTokens>
</UL>
<BR><B>C:IF TAG</B><BR>
<UL>
<c:forEach var="i" begin="1" end="10">
<LI>${i}
<c:if test="${i > 7}">
(greater than 7)
</c:if>
</c:forEach>
</UL>
<BR><B>C:CHOOSE TAG</B><BR>
<UL>
<c:forEach var="i" begin="1" end="10">
<LI>${i}
<c:choose>
<c:when test="${i < 4}">
(small)
</c:when>
<c:when test="${i < 8}">
(medium)
</c:when>
<c:otherwise>
(large)
</c:otherwise>
</c:choose>
</c:forEach>
</UL>
<BR><B>C:SET,C:REMOVE TAGS</B><BR><BR>
<c:set var="map" value="<%= new java.util.HashMap() %>"
scope="request"/>
<c:set target="${map}" property="partialTitle"
value="<read-it>Core</read-it>"/>
Prepared By : Nitin Chikani

Page 50

<c:set target="${map}" property="fullTitle">


<c:out value="${map.partialTitle}"/> <BR> Servlets and
JSP Volume 2
</c:set>
${map.fullTitle}
<c:set var="authors"
value="Marty Hall, Larry Brown, Yaakov Chaikin"
scope="request"/>
<c:set var="authors">Authors</c:set>
<br>
${authors}: ${requestScope.authors}
<br><c:remove var="authors"/>
${pageScope.authors}: ${requestScope.authors}
<BR>
<BR><B>C:IMPORT TAG </B><BR><BR>
<c:import url="http://localhost:8081/CNP/first.jsp" var="dat"/>
${dat}
<BR><BR><B>C:URL,C:PARAM TAGS</B><BR><BR>
<c:url value="/BGColor.jsp" var="inputUrl">
<c:param name="bgColor" value="yellow"/>
</c:url>
${inputUrl}
<BR><BR><B>C:REDIRECT TAG</B><BR><BR>
<%--<c:redirect url="/BGColor.jsp">--%>You can check this by removing comment tag.
<%--<c:param name="bgColor" value="papayawhip"/>--%>
<%--</c:redirect>--%>
<BR><BR><B>C:CATCH TAG</B><BR><BR>
<c:catch var="myException">
<% int x = 1 / 0; %>
</c:catch>
${myException.message}
<%-- first.jsp --%>
<html>
<head>
<title>Simple JSP Program </title>
</head>
<body>
Prepared By : Nitin Chikani

Page 51

<%out.println("Hello World");
%>
</body>
</html>
<%-- BGColor.jsp --%>
<HTML>
<HEAD>
<TITLE>Color Testing</TITLE>
</HEAD>
<%
String bgColor = request.getParameter("bgColor");
if ((bgColor == null) || (bgColor.trim().equals(""))) {
bgColor = "YELLOW";
}
%>
<BODY BGCOLOR="<%= bgColor %>">
<H2 ALIGN="CENTER">Testing a Background of "<%= bgColor %>"</H2>
</BODY></HTML>

Program-35
Write a JSP Page to use JSP's Page directives.

<html>
<head>
<title>Page Directives </title>
</head>
<body>
<h2>
<%@ page import="java.util.*"%>
<% Date d = new Date();
out.println("Today is : "+d);
%>
</h2>
</body>
</html>

Prepared By : Nitin Chikani

Page 52

Program-36 Write a JSP Page to use JSP scripting.


<html>
<head>
<title>JSP Scripting </title>
</head>
<%
String bgColor = null;
if ((bgColor == null)) {
bgColor = "LIGHTGRAY";
}
%>
<BODY BGCOLOR="<%= bgColor %>">
<H1>A Random Number</H1>
<%= Math.random() %>
<H1>JSP Expressions</H1>
Current time: <%= new java.util.Date() %>
</body>
</html>

Prepared By : Nitin Chikani

Page 53

You might also like