Sei sulla pagina 1di 24

2008

C G I P
CGI PROGRAMMING LABORATOARY
[ MySQL, Perl, PHP and JAVA Servlet ]
[ This document covers the common Gateway Interface Programming Laboratory programs included for the 7th semester of Information and Computer Science and Engineering course. ]

Purohit Shrinivasacharya
Assistant Professor, Dept. of Information Science and Engineering, Siddaganga Institute of Technology, Tumkur - 03

CGI PROGRAMMING LAB


Subject Code: ISL78 Hours/Week: 03 I.A. Marks: 25 Exam Hours: 03 Exam Marks: 50

Develop and execute the following programs using HTML and PERL. Create Database using MYSQL wherever necessary. 1. a) Program to display various Server Information like Server Name, Server Software, Server protocol, CGI Revision etc. b) Program to accept UNIX command from a HTML form and to display the output of the command executed. a) Program to accept the User Name and display a greeting message. b) Program to keep track of the number of visitors visited the web page and displays the counter with proper headings. Program to display a greeting based on the access time of the Web server. Also to verify whether the webmaster is currently logged in. Program to display a digital clock which displays the current time of the server. Program to display the current contents of the table in a database. Program to insert new name and age information entered by the user into the database.

2. 3. 4. 5. 6.

Develop and execute the following programs using HTML and PHP. Create Database using MYSQL wherever necessary. 7. 8. 9. Program to query the database and to display the result on a web page. Program to accept book information viz. Accession number, title, authors, edition and publication from a web page and to store those in a database. Program to search a book for a title given by the user on a web page and display the search results with proper headings.

Develop and execute the following programs using HTML and JAVA Servlets. 10. 11. 12. 13. 14. 15. a) Program to accept user name and display a greeting message. b) Program to change the background color of the page based on the color selected by the user. Program to display a greeting based on the access time of the server. Program to create and display a cookie. Program to create a session and display session information viz. session ID, creation time and last accessed. Program to request server information viz. Request Method, URI, Protocol and Remote address. Program to accept User name and address and display them in a web page by passing parameters.

Note: One exercise must be asked in the examination. The assignment of the exercise must be based on lots.

Purohit Shrinivasacharya

Dept. Of ISE, SIT

CGI PROGRAMMING LAB

PERL PROGRAMS CONFIGURATION


Steps to Configurations : Apache Configuration 1. Open file /etc/httpd/conf/httpd.conf following and uncomment. and perform/verify the

ScriptAlias /cgi-bin/ "/var/www/cgi-bin/ <Directory "/var/www/cgi-bin"> AllowOverride None Options None Order allow,deny Allow from all </Directory>

2. #service httpd start

{ or restart }

Steps to Execute the CGI PERL Programs : 1. Open vi and type perl program and save as <filename>.pl 2. Save the above file in the folder (i.e /var/www/cgi-bin) 3. Execute the following command #chmode filename 777 4. Open web browser and type the following URL http://localhost/cgi-bin/1a.pl 5. Check the output

I. PERL PROGRAMS
1A. Program to display various server information like server name, server software, server protocol, CGI revision etc.
#! /usr/bin/perl use CGI ':standard'; print header(), start_html(-title=>'Server Information',-bgcolor=>'#000000',text=>'#33ff00'), h1({-align=>'center'},'SERVER INFORMATION'), hr(), 'HERE IS SOME INFORMATION ABOUT THE SERVER:', ul( li('SERVER_NAME:',$ENV{'SERVER_NAME'}), li('SERVER_PORT:',$ENV{'SERVER_PORT'}), li('SERVER_PROTOCOL:',$ENV{'SERVER_PROTOCOL'}), li('SERVER_SOFTWARE:',$ENV{'SERVER_SOFTWARE'}), li('CGI_REVISION:',$ENV{'GATEWAY_INTERFACE'}), ), hr(), end_html();

Purohit Shrinivasacharya

Dept. Of ISE, SIT

CGI PROGRAMMING LAB

1B. Program to accept UNIX command from a html form and to display the output of the command executed. #! /usr/bin/perl
print header(), start_html(-title=>'Unix Command Executor',-bgcolor=>'#000000', -text=>'#33ff00'), h1({align=>"center"},'UNIX COMMAND EXECUTOR'), hr(), 'Please enter the unix command here...', br(), br(), start_form(-method=>'post',-action=>'/cgi-bin/lab_programs/1b.pl'), b('UNIX COMMAND:'), textfield(-name=>'comd',-value=>''), submit(-name=>'submit',-value=>'Execute'), hr(), end_form(), '$', $command=param('comd'), pre(`$command`), hr(), end_html(); use CGI ':standard';

2a. Program to accept the user name and display a greeting message.
#! /usr/bin/perl use CGI ':standard'; print header(), start_html(-title=>'Greeting a user',-bgcolor=>'#000000', -text=>'#33ff00'), h1({align=>"center"},'GREETING A USER'), hr(), 'Enter Username ..', br(), br(), start_form(-method=>'post',-action=>'/cgi-bin/lab_programs/2a.pl'), b('USER NAME:'), textfield(-name=>'uname',-value=>''), submit(-name=>'submit',-value=>'Send'), hr(), end_form(), 'Welcome to ', $username=param('uname'), end_html();

Purohit Shrinivasacharya

Dept. Of ISE, SIT

CGI PROGRAMMING LAB

2B. Program to keep track of the number of visitors, visited the web page and display the counter with proper headings.
Before executing the program perform the following. 1. Login to mysql using following command 2. #mysql u root 3. /* if people database already present use it or create it using CREATE DATABASE people; mysql> USE people; 4. Create table and insert 0 into table in people database. mysql> CREATE DATABASE people; mysql> USE people; mysql> CREATE TABLE counter ( count int); mysql> INSERT INTO counter VALUES (0); mysql> QUIT;

use DBI; use CGI ':standard'; print header(), start_html(-title=>"Page visited", -bgcolor=>'#000000', -text=>'#33ff00'), h1({-align=>'center'}, 'SERVER VISITED INFORMATION'); $dbh = DBI->connect('DBI:mysql:people','root','') or die "can't connect:" .DBI->errstr(); $sth = $dbh->prepare('select * from counter') or die "can't prepare:" .$dbh->errstr(); $sth->execute() or die "can't execute:" .$sth->errstr(); ($count)=Ssth->fetchrow(); $count=$count+1; Smsg=update counter set count=$count where 1; $sth = $dbh->prepare(msg) or die "can't prepare:" .$dbh->errstr(); $sth->execute() or die "can't execute:" .$sth->errstr(); print hr(), $count times this page is visited, end_html();

Purohit Shrinivasacharya

Dept. Of ISE, SIT

CGI PROGRAMMING LAB

3. Program to display a greeting based on the access time of the web server. Also to verify whether the webmaster is currently loggedin.
January

4. Program to display a digital clock which displays the current time of the server.
#! /usr/bin/perl use CGI ':standard'; ($sec,$min,$hr)=localtime(); print header(); print start_html(-title=>'Time system',-bgcolor=>'#000000', -text=>'#33ff00'); print h1({-align=>'center'},'DIGITAL CLOCK'); print hr(); print "<meta http-equiv='refresh' content='1'>"; if ($hr>=12) { $hr=$hr-12; $time="$hr:$min:$sec pm" } else { $time="$hr:$min:$sec am" } print h1({-align=>'center'},("$time")); print hr(); print end_html();

5. Program to display the current contents of the table in a database.


Before executing the program perform the following and this table is used for both 5, 6 and 7 programs. 1. Login to mysql using following command 2. #mysql u root 3. /* if people database already present use it or create it using CREATE DATABASE people; mysql> USE people; 4. Create table and insert values into table in people database. mysql> CREATE TABLE user (name char(30), age int); mysql> INSERT INTO user VALUES (PS,30); mysql> INSERT INTO user VALUES (VMS,24);

Purohit Shrinivasacharya

Dept. Of ISE, SIT

CGI PROGRAMMING LAB


mysql> INSERT INTO user VALUES (BS,25); mysql> QUIT; #! /usr/bin/perl use DBI; use CGI ':standard'; print header(), start_html(-title=>"Database Information", -bgcolor=>'#000000', -text=>'#33ff00'), h1({-align=>'center'}, 'USER AGE INFORMATION');

$dbh = DBI->connect('DBI:mysql:people','root','') or die "can't connect:" .DBI->errstr(); $sth = $dbh->prepare('select * from user') or die "can't prepare:" .$dbh->errstr(); $sth->execute() or die "can't execute:" .$sth->errstr(); print <table align=center border=1 > <tr><th>Name</th><th>Age</th></tr> while(($f1, $f2)=$sth->fetchrow()) { print ("<tr><td>$f1</td><td>$f2</td></tr>"); } print </table>; print end_html();

6. Program to insert new name and age information entered by the user into the database.
#! /usr/bin/perl #file name : 6.pl use DBI; use CGI ':standard'; #Create a form to read name and age of the person to insert into table. print header(), start_html(-title=>'DATABASE ENTRY',-bgcolor=>'#000000', -text=>'#33ff00'), h1({-align=>'center'},'DATABASE ENTRY'), hr(),br(), start_form(-method=>'post',-action=>'/cgi-bin/6ll.pl'), 'USER NAME:',textfield(-name=>'uname',-value=>' '), ' AGE:', textfield(-name=>'age',-value=>' '), br(), submit(-name=>'submit',-value=>'Insert'), reset(),hr(), end_form(); # insert data into user table

Purohit Shrinivasacharya

Dept. Of ISE, SIT

CGI PROGRAMMING LAB


$username=param('uname')|| ; $age=param('age') || ; if($username eq "" or $age eq "") { print "<b>Do not enter Null values</b>"; } else { $dbh=DBI->connect('DBI:mysql:people','root','') or die "can't connect:".DBI->errstr(); $sth=$dbh->prepare("insert into user1 values(?,?)") or die "can't prepare:".$dbh->errstr(); $sth->execute($username,$age) or die "can't execute:".$sth->errstr(); $sth->finish(); $dbh->disconnect(); print "Data are inserted...."; } print end_html();

After executing the program login to mysql and execute the following commands to verify the inserted values. 1. #mysql u root 2. mysql> USE people; 3. mysql> SELECT * FROM user;

Purohit Shrinivasacharya

Dept. Of ISE, SIT

CGI PROGRAMMING LAB

II. PHP PROGRAMS


Before executing PHP program perform the following. 1. Create a php folder #mkdir /var/www/html/php #chmod a+rx 2. Store all PHP programs to this folder extenuation as .php 3. Execute this programs using following URL http://localhost/php/filename.php

7. Prepare to query the database and to display the result on a web page
<html> <head> <title> Database Access using PHP </title> </head> <body bgcolor="#000000", text="#33ff00"> <h1 align="center">DATABASE ACCESS</h1> <hr></hr> <table align=center border=1 width=20%> <tr><th>NAME</th><th>AGE</th></tr> <? $mysql=mysql_connect("localhost","root","") or die ("can't connect to mysql"); $result=mysql_db_query("people","select * from user") or die ("query failed - ".mysql_errno().": ".mysql_error()); while($array=mysql_fetch_row($result)) { echo"<tr><td>$array[0]</td><td>$array[1]</td></tr>"; } echo "</table> <hr>"; echo "<b> QUERY EXECUTED:</b> $query"; echo "<br>"; echo "<b> Number of rows selected:</b>".mysql_num_rows($result); mysql_close($mysql);

?> </body> </html>

Purohit Shrinivasacharya

Dept. Of ISE, SIT

CGI PROGRAMMING LAB

1 0

8. Program to accept book information viz., Accession number, Title, Author, Edition, Publication from a webpage and to store those in a database. Before executing the program perform the following. 1. Login to mysql using following command
2. #mysql u root 3. /* if people database already present use it or create it using CREATE DATABASE people; mysql> USE people; 4. Create table and insert values into table in people database. mysql> CREATE TABLE BOOK (accn char(15), title char(30), author char(30), edition char(10),pubn char(30)); mysql> QUIT 5. Save file name as 8.php </html> <body bgcolor="#1E90FF"> <form action="/php/8l.php" method="post"> <h2>Complete the form with proper entry for Book Information </h2> <hr> <table border="0"> <tr><td>Accession No : </td> <td><input type="text" name="acc_no" width="15"></td> </tr> <tr><td>Title : </td> <td><input type="text" name="title" width="30"></td> </tr> <tr><td>Author : </td> <td><input type="text" name="author" width="30"></td> </tr> <tr><td>Edition : </td> <td><input type="text" name="edition" width="10"></td> </tr> <tr><td>Publication : </td> <td><input type="text" name="pub" width="30"></td> </tr> </table> <hr> <pre> <input type="submit" value="Click to Submit"> </pre> </form> <? $accnn = $_POST["acc_no"]; $titlee = $_POST["title"]; $authorr = $_REQUEST["author"]; $editionn = $_REQUEST["edition"]; $pubnn = $_REQUEST["pub"]; if($accnn == "" or $titlee == "" or $authorr == "" or $editionn == "" or $pubnn == "") { echo "Donot enter the null values $accnn $titlee"; } else

Purohit Shrinivasacharya

Dept. Of ISE, SIT

CGI PROGRAMMING LAB


{ $mysql=mysql_connect("localhost","root","") or die ("can't connect to mysql");

1 1

} ?> <hr> </body> </html>

mysql_db_query("people","insert into BOOK(accn,title,author,edition,pubn) values ('$accnn','$titlee','$authorr','$editionn','$pubnn')") or die ("query failed - ".mysql_errno().": ".mysql_error()); mysql_close($mysql);

9. Program to search a book for a title given by a user on a web page and display the search result with proper heading. Before executing the program perform the following. 1. Login to mysql using following command
2. #mysql u root 3. /* if people database already present use it or create it using CREATE DATABASE people; mysql> USE people; 4. Create table and insert values into table in people database. mysql> CREATE TABLE BOOK (accn char(15), title char(30), author char(30), edition char(10),pubn char(30)); mysql> INSERT INTO BOOK VALUES (1,CGI LAB,PS,1,SIT); mysql> INSERT INTO BOOK VALUES (2,DS,BS,1,SIT); mysql> INSERT INTO BOOK VALUES (3,CGI LAB,VMS,1,SIT); mysql> INSERT INTO BOOK VALUES (4,LD LAB,MSR,4,SIT); mysql> QUIT; 5. Save file name as 9.php

<html> <head> <title> Php Database search </title> </head> <body bgcolor='#ffffff', text='#000000'> <h1 align="center"> DATABASE SEARCH </h1> <hr> <form action="/php/9.php" method="post"> <b>Enter Book Title : </b><input type=text name=title> <input type=submit value=Search> <input type=reset><hr> </form>

<? $title=$_POST["title"]; if($title==NULL) { echo "<b> Donot Enter NULL Values </b>"; } else {

Purohit Shrinivasacharya

Dept. Of ISE, SIT

CGI PROGRAMMING LAB


$mysql=mysql_connect("localhost","root","") or die ("couldn't connect to mysql"); $result=mysql_db_query("people","select * from BOOK where title='$title'") or die ("query failed - : ".mysql_error()); echo"<h3 align=center>Search Result.....</h3>"; echo"<table border=0 width=50% align=center>"; echo"

1 2

<tr><th>Accession No</th><th>Title</th><th>Author</th> <th>Edition</th><th>Publication</th></tr>";

?> <hr> </body> </html>

while ($array=mysql_fetch_row($result)) { echo" <tr align=center><td>$array[0]</td><td>$array[1]</td> <td>$array[2]</td><td>$array[3]</td> <td>$array[4]</td></tr>"; } echo"</table>"; mysql_close($mysql); }

Purohit Shrinivasacharya

Dept. Of ISE, SIT

CGI PROGRAMMING LAB

1 3

III. JAVA SERVLET PROGRAMS


Steps to Execute the JAVA SERVLET Programs : 1. export CLASSPATH=/usr/share/java/servletapi5.jar ( .bash_profile OR .bashrc 2. Create the following folders #mkdir /var/lib/tomcat5/webapps/test #mkdir /var/lib/tomcat5/webapps/test/WEB-INF #mkdir /var/lib/tomcat5/webapps/test/WEB-INF/classes 3. In classes folder create JAVA and Class files. 4. In /test/WEB-INF/web.xml file and edit the following code <?xml version=1.0 encoding=ISO-8859-1 ?> <web-app> <servlet> <servlet-name> filename </servlet-name> <servlet-class> filename </servlet-class> </servlet> <servlet-mapping> <servlet-name> filename </servlet-name> <servlet-pattern> /servlet/filename </servletpattern> </servlet-mapping> </web-app> 5. start httpd and tomcat5 #service httpd start #service tomcat5 start 6. Open browser type the following url http://localhost:8080/test/servlet/filename 7. Store html file in /var/www/html

10a. Program to accept username and display a greeting message. 1. Save following html code as 10a.html in folder /var/www/html
<html> <head>

Purohit Shrinivasacharya

Dept. Of ISE, SIT

CGI PROGRAMMING LAB


<title>Greeting </title></head> <body bgcolor='#ffffff', text='#000000'> <h1 align=center> GREETING A USER </h1> <hr> <form method=get action='http://localhost:8080/test/servlet/10a'> <b>NAME :</b><input type=text name=name > <input type=submit value=SUBMIT> <hr> </form> </body> </html>

1 4

2.

Save following html code as 10a.java in folder and compile


1. /var/lib/tomcat5/webapps/test/WEB-INF/classes 2. javac 10a.java 3. execute this command after saving web.xml file #service tomcat5 restart

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class 10a extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name; response.setContentType("text/html"); name=request.getParameter("name"); PrintWriter out=response.getWriter(); out.println("<html><body bgcolor='#ffffff', text='#000000' >"); out.println("<h1 align=center> Hello.......! "+name+"</h1>"); out.close(); } }

3. Save following web code as web.xml in folder


/var/lib/tomcat5/webapps/test/WEB-INF <?xml version="1.0" encoding="ISO-8859-1"?> <web-app> <servlet> <servlet-name>10a</servlet-name> <servlet-class>10a</servlet-class> </servlet> <servlet-mapping> <servlet-name>10a</servlet-name> <url-pattern>/servlet/10a</url-pattern> </servlet-mapping> </web-app>

Purohit Shrinivasacharya

Dept. Of ISE, SIT

CGI PROGRAMMING LAB

1 5

Execution : 1. Open the browser and type the following URL http://localhost/10a.html

10b. Program to change the background color of the page based on the color selected by the user. 1. Save following html code as 10b.html in folder /var/www/html
<html> <body bgcolor=white> <form action="http://localhost:8080/test/servlet/10b" method="get"> <center><hr><br> <h3>Choose the color</h3> <select name="color" size=1> <option value=#DC143C>Red <option value=#1E90FF>Blue <option value=#FFD700>Yellow <option value=#00FF00>Green <option value=#00FFFF>Aqua <option value=#FF1493>Pink </select> <input type=submit value="Submit"> </br><br><hr> </center></hr> </form> </body> </html>

2.

Save following html code as 10b.java in folder and compile


1. /var/lib/tomcat5/webapps/test/WEB-INF/classes 2. javac 10b.java 3. execute this command after saving web.xml file #service tomcat5 restart

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class 10b extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException, IOException { PrintWriter out = res.getWriter(); res.setContentType("text/html"); String color = req.getParameter("color");

Purohit Shrinivasacharya

Dept. Of ISE, SIT

CGI PROGRAMMING LAB


out.println("<html>"); out.println("<BODY bgcolor=\""+ color + "\">"); out.println("<form action=\" http://localhost:8080/test/servlet/10b\">"); out.println("<center><hr><br>"); out.println("<h3>Choose the color</h3>"); out.println("<select name=\"color\" size=1>"); out.println("<option value=\"#DC143C\">Red"); out.println("<option value=\"#1E90FF\">Blue"); out.println("<option value=\"#FFD700\">Yellow"); out.println("<option value=\"#00FF00\">Green"); out.println("<option value=\"#00FFFF\">Aqua"); out.println("<option value=\"#FF1493\">Pink"); out.println("</select>"); out.println("<input type=submit value=\"Submit\"> "); out.println("</br><br><hr>"); out.println("</center></hr>"); out.println("</form>"); out.println("</body>"); out.println("</html>");

1 6

} }

3. Save following web code as web.xml in folder


/var/lib/tomcat5/webapps/test/WEB-INF <?xml version="1.0" encoding="ISO-8859-1"?> <web-app> <servlet> <servlet-name>10b</servlet-name> <servlet-class>10b</servlet-class> </servlet> <servlet-mapping> <servlet-name>10b</servlet-name> <url-pattern>/servlet/10b</url-pattern> </servlet-mapping> </web-app>

Execution :

1. Open the browser and type the following URL http://localhost/10b.html

Purohit Shrinivasacharya

Dept. Of ISE, SIT

CGI PROGRAMMING LAB

1 7

11. Program to display a greeting based on the access time of the server. 1. Save following java code as 11.java in folder and compile
1. /var/lib/tomcat5/webapps/test/WEB-INF/classes 2. javac 11.java 3. execute this command after saving web.xml file #service tomcat5 restart import import import import javax.servlet.*; java.io.*; javax.servlet.http.*; java.util.*;

public class 11 extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String s; Calendar calendar=Calendar.getInstance(); int hour=calendar.get(Calendar.HOUR_OF_DAY); if(hour<12) s = "Good Morning...Have a nice Day"; else if(hour<16) s="Good Afternoon..."; else if(hour<20) s="Good Evening..."; else s="Good Night..."; res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("<HTML>"); out.println("<HEAD><TITLE>Greeting Message</TITLE></HEAD>"); out.println("<BODY bgcolor=1E90FF>"); out.println("<hr><br><h3>" + s ); out.println("<br><br><hr>"); out.println("</BODY>"); out.println("</HTML>"); out.close(); } }

2. Save following web code as web.xml in folder


/var/lib/tomcat5/webapps/test/WEB-INF

Purohit Shrinivasacharya

Dept. Of ISE, SIT

CGI PROGRAMMING LAB


<?xml version="1.0" encoding="ISO-8859-1"?> <web-app> <servlet> <servlet-name>11</servlet-name> <servlet-class>11</servlet-class> </servlet> <servlet-mapping> <servlet-name>11</servlet-name> <url-pattern>/servlet/11</url-pattern> </servlet-mapping> </web-app>

1 8

Execution :
1. Open web browser type the following URL http://localhost:8080/test/servlet/11

12.

Program to create and display a cookie.

1. Save following html code as 12.html in folder /var/www/html


<html> <head> <title>Cookie Program</title> </head> <body bgcolor='#ffffff', text='#000000'> <h1 align=center>COOKIE EXAMPLE</h1> <hr> <form method=post action=http://localhost:8080/test/servlet/12> <b>NAME :</b><input type=text name=name /> <b>VALUE :</b><input type=text name=data /> <br><br> <input type=submit value=SUBMIT> <hr> </form> </body> </html>

2. Save following java code as 12.java in folder and compile


1. /var/lib/tomcat5/webapps/test/WEB-INF/classes 2. javac 12.java 3. execute this command after saving web.xml file #service tomcat5 restart

import java.io.*; import javax.servlet.http.*; import javax.servlet.*; public class Prg12 extends HttpServlet {

Purohit Shrinivasacharya

Dept. Of ISE, SIT

CGI PROGRAMMING LAB

1 9

public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String name = request.getParameter("name"); String data =request.getParameter("data"); Cookie cookie = new Cookie(name,data); response.addCookie(cookie); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html><body bgcolor='#000000', text='#33ff00'>"); out.println("<center>"); out.println("<h2>Your Cookie has been set to :</h2>"+data); // to display created cookies Cookie[] cookies=request.getCookies(); out.println("<br><br><hr><b>"); for(int i=0;i<cookies.length;i++) { String cname=cookies[i].getName(); String value=cookies[i].getValue(); out.println("<h1>Created Cookie information</h1><br>"); out.println("<br><b>NAME = </b>"+cname); out.println("<br>"); out.println("<b>VALUE = </b>"+value); } out.println("</body></html>"); out.close();

} }

3. Save following web code as web.xml in folder


/var/lib/tomcat5/webapps/test/WEB-INF <?xml version="1.0" encoding="ISO-8859-1"?> <web-app> <servlet> <servlet-name>12</servlet-name> <servlet-class>12</servlet-class> </servlet> <servlet-mapping> <servlet-name>12</servlet-name> <url-pattern>/servlet/12</url-pattern> </servlet-mapping> </web-app>

Execution :
1. Open web browser type the following URL http://localhost/12.html

Purohit Shrinivasacharya

Dept. Of ISE, SIT

CGI PROGRAMMING LAB

2 0

13. Program to create a session and display session information viz. session ID, creation time and last accessed. 1. Save following java code as 13.java in folder and compile
1. /var/lib/tomcat5/webapps/test/WEB-INF/classes 2. javac 13.java 3. execute this command after saving web.xml file #service tomcat5 restart

import import import import

javax.servlet.*; javax.servlet.http.*; java.io.*; java.util.Date;

public class 13 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { HttpSession mySession=request.getSession(true); response.setContentType("text/html"); PrintWriter out=response.getWriter(); out.println("<html>"); out.println("<head>"); out.println("<title>Session Information</title>"); out.println("</head>"); out.println("<body bgcolor='#000000', text='#33ff00'>"); out.println("<h1 align=center>SESSION INFORMATION</h1>"); out.println("<hr><br><center>"); out.println("<table border=5>"); out.println("<tr><td><b>New Session </b></td>"); out.println("<td>"); out.println(mySession.isNew()); out.println("</td></tr>"); out.println("<tr><td><b>Session ID </b></td>"); out.println("<td>"); out.println(mySession.getId()); out.println("</td></tr>"); out.println("<tr><td><b>Session Creation Time </b></td>"); out.println("<td>"); out.println(new Date(mySession.getCreationTime())); out.println("</td></tr>"); out.println("<tr><td><b>Session Last Accessed Time </b></td>"); out.println("<td>"); out.println(new Date(mySession.getLastAccessedTime())); out.println("</td></tr></table>");

Purohit Shrinivasacharya

Dept. Of ISE, SIT

CGI PROGRAMMING LAB


out.println("<br><hr>"); out.println("</body></html>"); } }

2 1

2. Save following web code as web.xml in folder


/var/lib/tomcat5/webapps/test/WEB-INF <?xml version="1.0" encoding="ISO-8859-1"?> <web-app> <servlet> <servlet-name>13</servlet-name> <servlet-class>13</servlet-class> </servlet> <servlet-mapping> <servlet-name>13</servlet-name> <url-pattern>/servlet/13</url-pattern> </servlet-mapping> </web-app> Execution : 1. Open web browser type the following URL http://localhost:8080/test/servlet/13

14. Program to request server information viz. Request method, URI, Protocol and Remote address. 1. Save following java code as 14.java in folder and compile
1. /var/lib/tomcat5/webapps/test/WEB-INF/classes 2. javac 14.java 3. execute this command after saving web.xml file #service tomcat5 restart import java.io.*; import javax.servlet.http.*; import javax.servlet.*; public class 14 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out=response.getWriter(); out.println("<html><head>"); out.println("<title>Server Information</title>");

Purohit Shrinivasacharya

Dept. Of ISE, SIT

CGI PROGRAMMING LAB


out.println("</head>"); out.println("<body bgcolor='#000000', text='#33ff00'>"); out.println("<h1 align=center>SERVER INFORMATION</h1>"); out.println("<hr><br><center><table border=5><tr>"); out.println("<td><b>Request Method </b></td>"); out.println("<td>"); out.println(request.getMethod()); out.println("</td></tr>"); out.println("<tr>"); out.println("<td><b>URI </b></td>"); out.println("<td>"); out.println(request.getRequestURI()); out.println("</td></tr>"); out.println("<tr>"); out.println("<td><b>Protocol </b></td>"); out.println("<td>"); out.println(request.getProtocol()); out.println("</td></tr>"); out.println("<tr>"); out.println("<td><b>Remote Address </b></td>"); out.println("<td>"); out.println(request.getRemoteAddr()); out.println("</td></tr></table>"); out.println("<br><hr>"); out.println("</body></html>");

2 2

} }

2. Save following web code as web.xml in folder


/var/lib/tomcat5/webapps/test/WEB-INF <?xml version="1.0" encoding="ISO-8859-1"?> <web-app> <servlet> <servlet-name>14</servlet-name> <servlet-class>14</servlet-class> </servlet> <servlet-mapping> <servlet-name>14</servlet-name> <url-pattern>/servlet/14</url-pattern> </servlet-mapping> </web-app> Execution : 1. Open web browser type the following URL http://localhost:8080/test/servlet/14

Purohit Shrinivasacharya

Dept. Of ISE, SIT

CGI PROGRAMMING LAB

2 3

15. Program to accept username and address and display them in a webpage by passing parameters. 1. Save following html code as 12.html in folder /var/www/html
<html> <head> <title>Address</title> </head> <body bgcolor='#ffffff', text='#000000'> <h1 align=center> Client Address</h1> <hr> <center> <form method=get action=http://localhost:8080/test/servlet/15> <table align=center border=0> <tr><td>Name :</td><td> <input type=text name=name></td></tr> <tr><td>Address :</td><td><input type=text name=address></td></tr> <tr><td>City :</td><td><input type=text name=city></td></tr> <tr><td>Pin Code :</td><td><input type=text name=code></td></tr> <tr><td>State :</td><td><input type=text name=state></td></tr> </table> <br> <input type=submit value=SUBMIT> <hr> </form> </body> </html>

1. Save following java code as 14.java in folder and compile


1. /var/lib/tomcat5/webapps/test/WEB-INF/classes 2. javac 15.java 3. execute this command after saving web.xml file #service tomcat5 restart

import javax.servlet.http.*; import javax.servlet.*; import java.io.*; public class 15 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String name,code,address,state,city; response.setContentType("text/html"); name=request.getParameter("name"); address=request.getParameter("address");

Purohit Shrinivasacharya

Dept. Of ISE, SIT

CGI PROGRAMMING LAB

2 4

city=request.getParameter("city"); code=request.getParameter("code"); state=request.getParameter("state"); PrintWriter out=response.getWriter(); out.println("<html><body bgcolor='#000000', text='#33ff00'>"); out.println("<b>" +name+</b>); out.println("<br>" + address + <br> + city + <br> + code); out.println("<br>" + state); out.println("<body></html>"); out.close(); } }

2. Save following web code as web.xml in folder


/var/lib/tomcat5/webapps/test/WEB-INF <?xml version="1.0" encoding="ISO-8859-1"?> <web-app> <servlet> <servlet-name>15</servlet-name> <servlet-class>15</servlet-class> </servlet> <servlet-mapping> <servlet-name>15</servlet-name> <url-pattern>/servlet/15</url-pattern> </servlet-mapping> </web-app> Execution : 1. Open web browser type the following URL http://localhost/15.html

Purohit Shrinivasacharya

Dept. Of ISE, SIT

Potrebbero piacerti anche