Sei sulla pagina 1di 62

TEEGALA KRISHNA REDDY ENGINEERING COLLEGE (R9)

(Affiliated to JNTUH)

MEERPET, MEDBOWLI, HYDERABAD

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

INTERNET TECHNOLOGIES AND SAERVICES


LAB MANUAL
Index
(i) Internet Technologies

1. Develop static pages (using Only HTML) of an online Book store. The pages should
resemble: www.amazon.com the website should consist the following pages:
Home page, Registration and user Login
User Profile Page, Books catalog
Shopping Cart, Payment By credit card
Order Conformation
2. Validate the Registration, user login, user profile and payment by credit card pages using
JavaScript.
3. Create and save an XML document at the server, which contains 10 users information.
Write a program, which takes User Id as an input and returns the user details by taking
the user information from the XML document.
4. Install TOMCAT web server. Convert the static web pages of assignments 2 into
dynamic web pages using Servlets and cookies. Hint: Users information (user id,
password, credit card number) would be stored in web.xml. Each user should have a
separate Shopping Cart.
5. Redo the previous task using JSP by converting the static web pages of assignments 2
into dynamic web pages. Create a database with user information and books information.
The books catalogue should be dynamically loaded from the database. Follow the MVC
architecture while doing the website.
6. Implement the “Hello World!” program using JSP Struts Framework.

(ii) Additional Assignment Problems

1. Write an HTML page including any required Javascript that takes a number from one text
field in the range of 0 to 999 and shows it in another text field in words. If the number is
out of range, it should show “out of range” and if it is not a number, it should show “not a
number” message in the result box.
2. Write a java swing application that takes a text file name as input and counts the
characters, words and lines in the file. Words are separated with white space characters
and lines are separated with new line character.
3. Write a simple calculator servlet that takes two numbers and an operator (+, -, /, * and %)
from an HTML page and returns the result page with the operation performed on the
operands. It should check in a database if the same expression is already computed and if
so, just return the value from database. Use MySQL or PostgreSQL.
4. Write an HTML page that contains a list of 5 countries. When the user selects a country,
its capital should be printed next to the list. Add CSS to customize the properties of the
font of the capital (color, bold and font size).
5. Write a servlet that takes name and age from an HTML page. If the age is less than 18, it
should send a page with “Hello <name>, you are not authorized to visit this site”
message, where <name> should be replaced with the entered name. Otherwise it should
send “Welcome <name> to this site” message.
6. Write a calculator program in HTML that performs basic arithmetic operations (+, -, /, *
and %). Use CSS to change the foreground and background color of the values, buttons
and result display area separately. Validate the input strings using JavaScript regular
expressions. Handle any special cases like division with zero reasonably. The screen may
look similar to the following:

7. Write a Java program that creates a calculator GUI, as shown in figure. Extra components
may be added for convenience:

The Color Scheme may be Black on White or Blue on Yellow (selectable) and
accordingly all components colors must be changed. The values can be either entered or
increased or decreased by a step of 10. The operators are +, -, / and * (selectable). Once
any change takes place, the result must be automatically computed by the program.
8. Write a Java Application that will read an XML file that contains personal information
(Name, Mobile, Number, age and place. It reads the information using SAX parser. After
reading the information, it shows two input Text Fields in a window, one for tag name
and the other for value. Once these two values are given, it should list all the records in
the XML file that match the value of the given field in a text area (result box). For
example, if the two text boxes are entered with “name” and “ABCD” then it should show
all the records for which name is “ABCD”? An Illustration is given below that takes a
mobile number and lists all the records that have the same mobile number.

9. Consider the following web application for implementation:


The user is first served a login page which takes user's name and password. After
submitting the details the server checks these values against the data from a database and
takes the following decisions.
If name and password matches, serves a welcome page with user's full name.
If name matches and password doesn't match, then serves “password mismatch” page
If name is not found in the database, serves a registration page, where users full name,
present user name (used to login) and password are collected. Implement this application
in:
1. Pure JSP
2. Pure Servlets
3. Struts Framework
10. Implement a simple arithmetic calculator with +, -, /, *, % and = operations using Struts
framework. The number of times the calculator is used should be displayed at the bottom
(use session variable).

(iii) Internet Technologies and Services Lab - Additional Problems

1. Create a web Service in Java that takes two city names from the user and returns the
distance between these two from data available from a table in MySql.
Write a java and a C# client which use the above service.
2. Write a Java program that takes a file as input and encrypts it using DES encryption. The
program should check if the file exists and its size is not zero.
3. Write a Java program that generates a key pair and encrypts a given file using RSA
algorithm.
4. Write a Java program that finds digest value of a given string.
5. Consider the following xml file for encryption
<?xmlversion=”1.0”><transaction><from>12345</from><to>54321</to>
<amount>10000</amount>
<secretcode>abc123</secretcode> <checksum></checksum> </transaction>
Replace <from> and <to> values with the RSA encrypted values represented with base64
encoding assuming that the public key is available in a file in local directory
“pubkey.dat”. Encrypt <secretcode> with AES algorithm with a password ‘secret’. The
checksum of all the field values concatenated with a delimiter character ‘+’ will be
inserted in the checksum and the xml file is written to encrypted.xml file.
6. Assume that a file ‘config.xml’, which has the following information:
<users>
<user><name>abc</name><pwd>pwd123</pwd><role>admin</role><md5>xxx</md5>
</user>
<user><name>def</name><pwd>pwd123</pwd> <role>guest</role> <md5>xxx</md5>
</user>
</users>
Replace name and role with DES encrypted values and pwd with RSA encrypted values
(represent the values with base64 encoding). The public key is available in “public.key”
file in current directory. Replace xxx with respective MD5 values of all the fields for
each user. Write the resulting file back to config.xml.
7. Write an HTML page that gives 3 multiple choice (a,b,c and d) questions from a set of 5
preloaded questions randomly. After each question is answered change the color of the
question to either green or blue using CSS. Finally on clicking OK button that is
provided, the score should be displayed as a pop-up window. Use Java Script for dynamic
content.
8. Write an HTML page that has 3 countries on the left side (“USA”, “UK” and “INDIA”)
and on the right side of each country, there is a pull-down menu that contains the
following entries: (“Select Answer”, “New Delhi”, “Washington” and “London”). The
user will match the Countries with their respective capitals by selecting an item from the
menu. The user chooses all the three answers (whether right or wrong). Then colors of
the countries should be changed either to green or to red depending on the answer. Use
CSS for changing color.
9. Write an HTML Page that can be used for registering the candidates for an entrance test.
The fields are: name, age, qualifying examination (diploma or 10+2), stream in
qualifying examination. If qualifying examination is “diploma”, the stream can be
“Electrical”, “Mechanical” or “Civil”. If the qualifying examination is 10+2, the stream
can be “MPC” or “BPC”. Validate the name to accept only characters and spaces.
10. Write an HTML page that has two selection menus. The first menu contains the states
(“AP”, “TN” and “KN”) and depending on the selection the second menu should show
the following items: “Hyderabad”, “Vijayawada”, “Kurnool” for AP, “Chennai”,
“Salem”, “Madurai” for TN and “Bangalore”, “Bellary”, “Mysore” for KN.
11. Write an HTML page that has phone buttons 0 to 9 and a text box that shows the dialed
number. If 00 is pressed at the beginning, it should be replaced with a + symbol in the
text box. If the number is not a valid international number (+ followed by country code
and 10 digit phone number) the color of the display should be red and it should turn to
green when the number is valid. Consider only “+91, +1 and +44 as valid country codes.
Use CSS for defining colors.
12. Write an HTML page that has a text box for phone number or Name. If a number is
entered in the box the name should be displayed next to the number. If 00 is pressed at
the beginning, it should be replaced with a + symbol in the text box. If a name is entered
in the text box, it should show the number next to the name. If the corresponding value is
not found, show it in red and show it in green otherwise. Use CSS for colors. Store at
least 5 names and numbers in the script for testing.
13. A library consists of 10 titles and each title has a given number of books initially. A
student can take or return a book by entering his/her HTNo as user ID and a given
password. If there are at least two books, the book is issued and the balance is modified
accordingly.
(a) Use RDBMS and implement it with JSP.
(b) Use XML File for data and Implement it with JSP
(c) Use RDBMS and implement it with Servlets
(d) Use XML File for data and Implement it with Servlets
14. A Bus Reservation System contains the details of a bus seat plan for 40 seats in 2x2 per
row arrangement, where the seats are numbered from 1 to 40 from first row to last row.
The customer can visit the website and can reserve a ticket of his choice if available by
entering his details (Name, Address, Gender and Age). The customer can cancel the
ticket by entering the seat number and his name as entered for reservation.
(a) Use RDBMS and implement it with JSP.
(b) Use XML File for data and Implement it with JSP
(c) Use RDBMS and implement it with Servlets
(d) Use XML File for data and Implement it with Servlets.
15. Implement a simple messaging system with the following details:
When a student logs in with his/her HTNO and a given password, they should get all the
messages posted to him/her giving the ID of sender and the actual message. Each
message may be separated with a ruler. There should be a provision for the user to send a
message to any number of users by giving the IDs separated with commas in the “To”
text box.
(a) Use RDBMS and implement it with JSP.
(b) Use XML File for data and Implement it with JSP
(c) Use RDBMS and implement it with Servlets
(d) Use XML File for data and Implement it with Servlets.
16. There is an image of 600x100 size which can be logically divided into 12 button areas
with labels (0-9, +, =). Write a javascript calculator program that uses this image as input
virtual keyboard and three text areas for two input numbers and result of sum of these
numbers. Add a CSS that can be used to change the colors of text and background of text
areas and the page. The input numbers can be up to 4 digits each.
17. Develop a web application that takes user name and password as input and compares
them with those available in an xml user database. If they match, it should display the
welcome page that contains the user’s full name and last used date and time retrieved
from a client cookie. On logout it stores new time to the cookie and displays a goodbye
page. If authentication fails, it should store the attempt number to the client cookie and
displays an error page. Add necessary CSS that takes care of the font, color of foreground
and background.
18. A web application has the following specifications:
The first page (Login page) should have a login screen where the user gives the login
name and password. Both fields must be validated on client side for a minimum length of
4 characters, name should be lower case a-z characters only and password should contain
at least one digit. On submitting these values, the server should validate them with a
MySQL database and if failed, show the login page along with a message saying “Login
Name or Password Mismatch” in Red color below the main heading and above the form.
If successful, show a welcome page with the user's full name (taken from database) and
and a link to Logout. On logout, a good bye page is displayed with the total time of usage
(Logout time – login time). Specify the Schema details of table and web.xml file
contents.
Implement it using (a) JSP Pages (b) Servlets (c) Struts
19. Design a struts based web portal for an international conference with following
specifications:
The welcome page should give the details of the conference and a link to login. If login
fails, direct them back for re-login and also provide a link for registration. On successful
registration/login, the user will be directed to a page where s/he can see the status
(accepted/rejected) of their already submitted papers followed by a form for submitting a
doc file to the conference. Provide a logout button on all pages including the home page,
once the user logs in. Implement validation framework to check that the user name is in
the form of CCDDCC and password is in the form of (CCSDDD) (C for character, S for
special character (one of @, #, $, %, ^, & and !) and D for digit)., Database should be
accessed through Connection Pool for MySql for user information. Provide scope for
internationalization in future. Assume any missing information and mention it first.
(i) Internet Technologies

Problem 1: Develop static pages (using Only HTML) of an online Book store. The pages should
resemble: www.amazon.com the website should consist the following pages:
Home page, Registration and user Login
User Profile Page, Books catalog
Shopping Cart, Payment By credit card
Order Conformation

Solution:

Main.html:
<frameset rows=”25%, 75 %”>
<frame src=”top.html” name=”top”>
<frameset cols=”25%,75%”>
<frame src=”left.html” name=”left”>
<frame src=”right.html” name=”right”>
</frameset>
</frameset>

Top.html:
<html>
<body bgcolor=”pink”>
<br><br>
<marquee><h1 align=”center”><b><u>ONLINE BOOK
STORAGE</u></b></h1></marquee>
</body>
</html>

Right.html:
<html>
<body bgcolor=”pink”>
<br><br><br><br><br>
<h2 align=”center”>
<b><p> welcome to online book storage. Press login if you are
having id otherwise press registration.
</p></b></h2>
</body>
</html>

Left.html:
<html>
<body bgcolor=”pink”>
<h3>
<ul>
<li><a href=”login.html” target=”right”><font color=”black”>
LOGIN</font></a></li><br><br>
<li><a href=”reg.html” target=”right”><font color=”black”>
REGISTRATION</font></a></li><br><br>
<li><a href=”profile.html” target=”right”><fontcolor=”black”>
USER PROFILE</font></a></li><br><br>
<li><a href=”catalog.html” target=”right”><fontcolor=”black”>
BOOKS CATALOG</font></a></li><br><br>
<li><a href=”scart.html” target=”right”><font color=”black”>
SHOPPINGCART</font></a></li><br><br>
<li><a href=”payment.html” target=”right”><fontcolor=”black”>
PAYMENT</font></a></li><br><br>
<li><a href=”order.html” target=”right”><font color=”black”>
ORDER CONFIRMATION</font></a></li><br><br>
</ul>
</body>
</html>

Login.html:
<html>
<body bgcolor=”pink”><br><br><br>
<script language=”javascript”>
function validate()
{
var flag=1;
if(document.myform.id.value==”“||document.myform.pwd.
value==” “)
{
flag=0;
}
if(flag==1)
{
alert(“VALID INPUT”);
}
else
{
alert(“INVALID INPUT”);
document.myform.focus();
}
}
</script>
<form name=”myform”>
<div align=”center”><pre>
LOGIN ID:<input type=”text” name=”id”><br>
PASSWORD:<input type=”password” name=”pwd”>
</pre><br><br>
</div>
<br><br>
<div align=”center”>
<input type=”submit” value=”ok” onClick=”validate()”>&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;<input type=”reset” value=”clear”>
</form>
</body>
</html>

Reg.html:
<html>
<body bgcolor=”pink”><br><br>
<script language=”javascript”>
function validate()
{
var flag=1;
if(document.myform.name.value==””||
document.myform.addr.value==””||
document.myform.phno.value==””||
document.myform.id.value==””||
document.myform.pwd.value==””)
{
flag=0;
}
var str=document.myform.phno.value;
var x;
for(var i=0;i<str.length;i++)
{
x=str.substr(i,1)
if(!(x<=9))
{
flag=0;
break;
}
}
if(flag==1)
{
alert("VALID INPUT");
}
else
{
alert("INVALID INPUT");
document.myform.focus();
}
}
</script>
<form name="myform">
<div align="center"><pre>
NAME :<input type="text" name="name"><br>
ADDRESS :<input type="type" name="addr"><br>
CONTACT NUMBER:<iput type="text" name="phno"><br>
LOGINID :<input type="text" name="id"><br>
PASSWORD :<input type="password" name="pwd"></pre><br><br>
</div>
<br><br>
<div align="center">
<input type="submit" value="ok" onClick="validate()">&nbsp;&nbsp;&nbsp;
<input type="reset" value="clear">
</form></body></html>
Catalog.html:
<html>
<body bgcolor="pink"><br><br><br>
<div align="center"><pre>
BOOK TITLE :<input type="text" name="title"><br>
</pre><br><br>
</div>
<br><br>
<div align="center">
<input type="submit" value="ok" name="button1">&nbsp;&nbsp;&nbsp;&nbsp;
<input type="reset" value="clear" name="button2">
</body>
</html>

Order.html:
<html>
<body bgcolor="pink"><br><br><br>
<div align="center"><pre>
LOGIN ID :<input type="text" name="id"><br>
TITLE :<input type="text" name="title"><br>
NO.OF BOOKS :<input type="text" name="no"><br>
COST OF BOOK:<input type="text"name="cost"><br>
DATE :<input tpe="text" name="date"><br></pre><br><br>
</div>
<br><br>
<div align="center">
<input type="submit" value="ok" name="button1"> &nbsp;&nbsp;&nbsp;&nbsp;
<input type="reset" value="clear" name="button2">
</body>
</html>

Payment.html:
<html>
<body bgcolor="pink"><br><br><br>
<script language="javascript">
function validate()
{
var flag=1;
if(document.myform.id.value==""||
document.myform.pwd.value==""||
document.myform.amount.value==""||
document.myform.num.value=="")
{
flag=0;
}
var str=document.myform.amount.value;
var x;
for(var i=0;i<str.length;i++)
{
x=str.substr(i,1);
if(!(x<=9))
{
flag=0;
break;
}
}
str=document.myform.num.value;
for(var i=0;i<str.lenght;i++)
{
x=str.substr(i,1);
if(!(x<=9))
{
flag=0;
break;
}
}
if(flag==1)
{
alert("VALID INPUT");
}
else
{
alert("INVALID INPUT");
document.myform.focus();
}
}
</script>
<form name="myform">
<div align="center"><pre>
LOGIN ID :<input type="text" name="id"><br>
PASSWORD :<input type="password" name="pwd"><br>
AMOUNT :<input type="text" name="amount"><br>
CREDITCARDNUMBER:<input type="PASSWORD" name="num+"><br></pre><br><br>
</div>
<br><br>
<div align="center">
<input type="submit" value="ok" onClick="validate()">&nbsp;&nbsp;&nbsp;&nbsp;
<input type="reset" value="clear" >
</form>
</body>
</html>
Profile.html:
<html>
<body bgcolor="pink"><br><br><br>
<script language="javascript">
function validate()
{
var flag=1;
if(document.myform.id.value==""||
document.myform.pwd.value=="")
{
flag=0;
}
if(flag==1)
{
alert("VALID INPUT");
}
else
{
alert("INVALID INPUT");
document.myform.focus();
}
}
</script>
<form name="myform">
<div align="center"><pre>
LOGIN ID :<input type="text" name="id"><br>
PASSWORD:<input type="password" name="pwd"></pre><br><br>
</div>
<br><br>
<div align="center">
<input type="submit" value="ok" onClick="validate()">&nbsp;&nbsp;&nbsp;&nbsp;
<input type="reset" value="clear" >
</form>
</body>
</html>

Problem 3: Create and save an XML document at the server, which contains 10 users
information. Write a program, which takes User Id as an input and returns the user details by
taking the user information from the XML document.

Solution:

StudentDetails.Java :
import javax.servlet.*;
import java.util.*;
import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
public class StudentDetails implements Servlet
{
private DocumentBuilderFactory fact;
private DocumentBuilder builder;
private Document doc;
private NodeList list,childs;
private Node node,parent,child;
private String str;
private String hallTicket;
private ServletConfig sc;
public void init(ServletConfig sc)
{
try
{
this.sc=sc;
str="C:\Program Files\Apache Software Foundation\Tomcat
5.0\webapps\StudentDetails\WEBINF\
classes\Details.xml";
fact=DocumentBuilderFactory.newInstance();
builder =fact.newDocumentBuilder();
doc=builder.parse(str);
System.out.println("In the Init Method");
}
catch(Exception e)
{
System.out.println("Error in the Init Method"+e.getMessage());
}
}
public void service(ServletRequest req, ServletResponse res)throws
ServletException,IOException
{
hallTicket=req.getParameter("hall");
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
list=doc.getElementsByTagName("HallTicketNo");
pw.print("<center><h1>Welcome To Student Details</center></h1>");
for(int i=0;i<list.getLength();i++)
{
node=list.item(i);
if(node.getTextContent().equals(hallTicket))
{
parent=node.getParentNode();
childs=parent.getChildNodes();

for(int j=1;j<childs.getLength()-1;j=j+2)
{
child=childs.item(j);
pw.print("<center>"+child.getNodeName()+" "+child.getTextContent());
}
break;
}//if
}//for
}//service
public ServletConfig getServletConfig()
{
return sc;
}
public String getServletInfo()
{
return "Developed By Krati Bajpai";
}
public void destroy()
{
}

LogIn.html :
<html><head><title>StudentDetails</title>
</head>
<body style="height: 100%;width:100%; margin: 0; padding: 0;overflow-y:hidden;">
<form method="post" action="http://localhost:8080/StudentDetails/MyServletEx">
<div>
</div>
<div style="position:absolute;top:0;left:0;width:100%;height:100%;margin:0;padding:0;z-
index:0;">
<img src="college.jpg" width="100%" height="100%">
</div>
<div style="position:absolute;top:4%;left:25%;z-index:1" align="center" >
<font size="6" color="red" >Teegala Krishna Reddy Engineering College</font>
<br/>
<font size=4 color="red">(Affiliated to JNTU Approved By AICTE)</font>
<br/>
<font size=3 color="red">Meerpet, Medbowli, Hyderabad</font>
<br/>
<font size=3 color="red">Ranga Reddy District Telangana</font>
<br/>
</div>
<div style="position:absolute;top:60%;right:5%; z-index:2">
<input type="text" SIZE="10" name="hall"><br/>
<input type="submit" value="Submit">
</div>
</form>
</body>
</html>

web.xml :
<web-app>
<servlet>
<servlet-name>Student</servlet-name>
<servlet-class>StudentDetails</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Student</servlet-name>
<url-pattern>/MyServletEx</url-pattern>
</servlet-mapping>
</web-app>
Details.xml output :
- <StudentDetails>
- <Details>
<HallTicketNo>16R91D5801</HallTicketNo>
<Name>Akshita</Name>
<Education>M.Tech</Education>
<Specialization>CSE</Specialization>
<Year>I</Year>
<Semester>II</Semester>
<Ambition>SoftwareEngineer</Ambition>
<Hobby>Reading Books</Hobby>
</Details>
- <Details>
<HallTicketNo>16R91D5802</HallTicketNo>
<Name>Prashanti</Name>
<Education>M.Tech</Education>
<Specialization>CSE</Specialization>
<Year>I</Year>
<Semester>II</Semester>
<Ambition>SoftwareEngineer</Ambition>
<Hobby>Dance</Hobby> </Details>- <Details>
<HallTicketNo>16R91D5803</HallTicketNo> <Name>Pruthvi</Name>
<Education>M.Tech</Education>
<Specialization>CSE</Specialization> <Year>I</Year> <Semester>II</Semester>
<Ambition>SoftwareEngineer</Ambition>
<Hobby>Foot Ball</Hobby> </Details>- <Details>
<HallTicketNo>16R91D5804</HallTicketNo> <Name>Harsha</Name>
<Education>M.Tech</Education>
<Specialization>CSE</Specialization>
<Year>I</Year>
<Semester>II</Semester>
<Ambition>SoftwareEngineer</Ambition>
<Hobby>Cricket</Hobby>
</Details>- <Details> <HallTicketNo>16R91D5816</HallTicketNo>
<Name>Srividhya</Name>
<Education>M.Tech</Education> <Specialization>CSE</Specialization> </Details>
</StudentDetails>

Problem 4: Install TOMCAT web server. Convert the static web pages of assignments 2 into
dynamic web pages using Servlets and cookies. Hint: Users information (user id, password,
credit card number) would be stored in web.xml. Each user should have a separate Shopping
Cart.

Solution:

PROCEDURE:
First install the tomcat into the system.
Then make a subdirectly(eg., tr) in the \tomcat\webapps.
Under tr create WEB-INF directory and also place the html files in this tr directory only.
Next under WEB-INF create two subclasses lib,classes and web.xml
Next place all the class files under the classes and jar files(servlet-api.jar,classes12.jar etc…)
under lib subdirectories.
After this start tomcat by giving the following command at the instll_dir>tomcat>bin
Catalina.bat run
At the I.E(web browser) give the url as http;//localhost:8080//tr/htmlfile or servlet url pattern
Portno 8080 is assigned for the tomcat.

Web.xml
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<display-name>Servlet 2.4 Examples</display-name>
<description>
Servlet 2.4 Examples.
</description>
<servlet>
<servlet-name>reg</servlet-name>
<servlet-class>reg</servlet-class>
</servlet>
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>login</servlet-class>
</servlet>
<servlet>
<servlet-name>profile</servlet-name>
<servlet-class>profile</servlet-class>
</servlet>
<servlet>
<servlet-name>catalog</servlet-name>
<servlet-class>catalog</servlet-class>
<servlet-mapping>
<servlet-name>order</servlet-name>
<url-p</servlet>
<servlet>
<servlet-name>order</servlet-name>
<servlet-class>order</servlet-class>
</servlet>
attern>order</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>catalog</servlet-name>
<url-pattern>catalog</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>profile</servlet-name>
<url-pattern>profile</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>login</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>reg</servlet-name>
<url-pattern>reg</url-pattern>
</servlet-mapping>
</web-app>

Main.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<body bgcolor="pink">
<br /><br /><br /><br /><br />
<h1 align="center"><U>ONLINE BOOK STORAGE</U></h1><br /><br /><br />
<h2 align="center"><pre>
<b>Welcome to online book storage.
Press LOGIN if you are having id
otherwise press REGISTRATION
</b></pre></h2>
<br /><br /><pre>
<div align="center"><a href="/tr/login.html">LOGIN</a> <a href="/tr/reg.html">
REGISTRATION</a></div></pre>
</body>
</html>

Login.html
<html>
<body bgcolor="pink"><br /><br /><br />
<form name="myform" method="post" action="/tr/login">
<div align="center"><pre>
LOGIN ID :<input type="text" name="id" /><br />
PASSWORD :<input type="password" name="pwd" /></pre><br /><br />
</div>
<br /><br />
<div align="center">
<input type="submit" value="ok" onclick="validate()" />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="reset" value="clear" />
</div>
</form>
</body>
</html>

Reg.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<body bgcolor="pink"><br /><br />
<form name="myform" method="post" action="/tr/reg">
<div align="center"><pre>
NAME :<input type="text" name="name" /><br />
ADDRESS :<input type="text" name="addr" /><br />
CONTACT NUMBER :<input type="text" name="phno" /><br />
LOGINID :<input type="text" name="id" /><br />
PASSWORD :<input type="password" name="pwd" /></pre><br /><br />
</div>
<br /><br />
<div align="center">
<input type="submit" value="ok" onclick="validate()" />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="reset" value="clear" />
</div>
</form>
</body>
</html>

Profile.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<body bgcolor="pink"><br /><br /><br />
<form name="myform" method="post" action="/tr/profile">
<div align="center"><pre>
LOGIN ID :<input type="text" name="id" /><br />
</pre><br /><br />
</div>
<br /><br />
<div align="center">
<input type="submit" value="ok" onclick="validate()" />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="reset" value="clear" />
</div></form></body></html>

Catalog.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<body bgcolor="pink"><br /><br /><br />
<form method="post" action="/tr/catalog">
<div align="center"><pre>
BOOK TITLE :<input type="text" name="title" /><br />
</pre><br /><br />
</div>
<br /><br />
<div align="center">
<input type="submit" value="ok" name="button1"/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input type="reset" value="clear" name="button2"/>
</div>
</form>
</body></html>

Order.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<body bgcolor="pink"><br /><br />
<form method="post" action="/tr/reg">
<div align="center"><pre>
NAME :<input type="text" name="name" /><br />
PASSWORD :<input type="password" name="pwd" />
TITLE :<input type="text" name="title" /><br />
NO. OF BOOKS :<input type="text" name="no" /><br />
DATE :<input type="text" name="date" /><br />
CREDIT CARD NUMBER:<input type="password" name="cno" /><br /></pre><br /><br />
</div>
<br /><br />
<div align="center">
<input type="submit" value="ok" name="button1"/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="reset" value="clear" name="button2"/>
</div>
</form>
</body>
</html>

Login.java
import java.sql.*;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class login extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse resp)
throws ServletException,IOException
{ PrintWriter pw=resp.getWriter();
pw.println("<html><body bgcolor=\"pink\");
String id=req.getParamenter("id");
String pwd=req.getParameter("pwd");
try
{ Driver d=new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver(d);
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger")
;
Statement stmt=con.createStatement();
String sqlstmt="select id,password from login";
ResultSet rs=stmt.executeQuery(sqlstmt);
int flag=0;
while(rs.next())
{
if(id.equal(rs.getString(1))&&pwd.equals(rs.getString(2)))
{
flag=1;
}
}
if(flag==0)
{
pw.println("SORRY INVALID ID TRY AGAIN ID<br><br>");
pw.println("<a href=\"/tr/login.html\">press LOGIN to RETRY</a>");
}
else
{
pw.println("VALID LOGIN ID<br><br>");
pw.println("<h3><ul>");
pw.println("<li><ahref=\"profile.html\"><fontcolor=\"black\">USER
PROFILE</font> </a></li><br><br>");
pw.println("<li><ahref=\"catalog.html\"><fontcolor=\"black\">BOOKS
CATALOG</font></a></li><br><br>");
pw.println("<li><ahref=\"order.html\"><fontcolor=\"black\">ORDER
CONFIRMATION</font> </a></li><br><br>");
}
pw.println("</body></html>");
}
catch(Exception e)
{ resp.sendError(500,e.toString());
}
}

Reg.html
import java.sql.*;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class login extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse resp)
throws ServletException,IOException
{
PrintWriter pw=resp.getWriter();
pw.println("<html><body bgcolor=\"pink\");
String name=req.getParamenter("name");
String addr=req.getParameter("addr");
String phno=req.getParameter("phno");
String id=req.getParamenter("id");
String pwd=req.getParameter("pwd");
int no=Integer.parseInt(phno);
try
{
Driver d=new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver(d);
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger")
;
Statement stmt=con.createStatement();
String sqlstmt="select id,password from login";
ResultSet rs=stmt.executeQuery(sqlstmt);
int flag=0;
while(rs.next())
{
if(id.equal(rs.getString(1))&&pwd.equals(rs.getString(2)))
{
flag=1;
}}
if(flag==1)
{
pw.println("SORRY INVALID ID ALREADY EXITS TRY AGAIN WITH NEW
ID<br><br>");
pw.println("<a href=\"/tr/reg.html\">press REGISTER to RETRY</a>");
}
else
{ Statement stmt1=con.createStatement();
stmt1.executeUpdate("insertintologin
values("+names","+addr+","+no+","+id+","+pwd+")");
pw.println("YOUR DETAILS ARE ENTERED<br><br>");
pw.println("<a href=\"/tr/login.html\">press LOGIN to login</a>");
}
pw.println("</body></html>");
}
catch(Exception e)
{ resp.sendError(500,e.toString());
} }}

Catlog.java
import java.sql.*;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class login extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse resp)
throws ServletException,IOException
{
PrintWriter pw=resp.getWriter();
pw.println("<html><body bgcolor=\"pink\");
String title=req.getParameter("title");
try
{
Driver d=new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver(d);
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger")
;
Statement stmt=con.createStatement();
String sqlstmt="select id,password from login";
ResultSet rs=stmt.executeQuery(sqlstmt);
int flag=0;
while(rs.next())
{
pw.println(",div align=\"center\">");
pw.println("TITLE :"+rs.getString(1)+"<br>");
pw.println("AUTHOR :"+rs.getString(2)+"<br>");
pw.println("VERSION :"+rs.getString(3)+"<br>");
pw.println("PUBLISHER :"+rs.getString(4)+"<br>");
pw.println("COST :"+rs.getString(5)+"<br>");
pw.println("</div");
flag=1;
}
if(flag==0)
{
pw.println("SORRY INVALID TITLE TRY AGAIN <br><br>");
pw.println("<a href=\"/tr/catalog.html\">press HERE to RETRY</a>");
}
pw.println("</body></html>");
}
catch(Exception e)
{
resp.sendError(500,e.toString());
}
}
}

Profile.java
import java.sql.*;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class login extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse resp)
throws ServletException,IOException
{
PrintWriter pw=resp.getWriter();
pw.println("<html><body bgcolor=\"pink\");
String id=req.getParamenter("id");
try
{
Driver d=new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver(d);
Connection con=DriverManager.getConnection("jdbc:oracle:thin:
@localhost:1521:orcl","scott","tiger");
Statement stmt=con.createStatement();
String sqlstmt="select * from login where id="+id+"";
ResultSet rs=stmt.executeQuery(sqlstmt);
int flag=0;
pw.println("<br><br><br>");
while(rs.next())
{
pw.println("<div align=\"center\">");
pw.println("NAME :"+rs.getString(1)+"<br>");
pw.println("ADDRESS :"+rs.getString(2)+"<br>");
pw.println("PHONE NO :"+rs.getString(3)+"<br>");
pw.println("</div>");
flag=1;
}
if(flag==0)
{
pw.println("SORRY INVALID ID TRY AGAIN ID<br><br>");
pw.println("<a href=\"/tr/profile.html\">press HERE to RETRY</a>");
}
pw.println("</body></html>");
}
catch(Exception e)
{
resp.sendError(500,e.toString());
}
}
}

Order.java
import java.sql.*;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class login extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse resp)
throws ServletException,IOException
{
PrintWriter pw=resp.getWriter();
pw.println("<html><body bgcolor=\"pink\");
String id=req.getParamenter("id");
String pwd=req.getParameter("pwd");
String title=req.getParameter("title");
String count1=req.getParameter("no");
String date=req.getParameter("date");
String cno=req.getParameter("cno");
int count=Integer.parseInt(count1);
try
{
Driver d=new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver(d);
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger")
;
Statement stmt=con.createStatement();
String sqlstmt="select id,password from login";
ResultSet rs=stmt.executeQuery(sqlstmt);
int flag=0,amount,x;
while(rs.next())
{
if(id.equals(rs.getString(1))&&pwd.equals(rs.getString(2)))
{
flag=1;
}
}
if(flag==0)
{
pw.println("SORRY INVALID ID TRY AGAIN ID<br><br>");
pw.println("<a href=\\"/tr/order.html\\">press HERE to RETRY</a>");
}
else
{
Statement stmt2=con.createStatement();
String s="select cost from book where title="+title+"";
ResultSet rs1=stmt2.executeQuery(s);
int flag1=0;
while(rs1.next())
{
flag1=1;
x=Integer.parseInt(rs1.getString(1));
amount=count*x;
pw.println("AMOUNT :"+amount+"<br><br><br><br>");
Statement stmt1=con.createStatement();
stmt1.executeUpdate("insertintodetails
values('"+id+",'"+title+"'+amount+'","'+cno+'")"');
pw.println("YOUR ORDER has taken<br>");
}
if(flag1==0)
{
pw.println("SORRY INVALID ID TRY AGAIN ID<br><br>");
pw.println("<a href=\\"/tr/order.html\\">press HERE to RETRY</a>");
}
}
pw.println("</body></html>");
con.close();
}
catch(Exception e)
{
resp.sendError(500,e.toString());

}
Problem 5: Redo the previous task using JSP by converting the static web pages of assignments
2 into dynamic web pages. Create a database with user information and books information. The
books catalogue should be dynamically loaded from the database. Follow the MVC architecture
while doing the website.

Solution:

PROCEDURE:
1) Create your own directory under tomcat/webapps (e.g. tr1)
2) Copy the html files in tr1
3) Copy the jsp files also into tr1
4) Start tomcat give the following command
Catalina.bat run
At install‐dir/bin
5) at I.E give url as http://localhost:8081/tr1/main.html

Main.html:
<html>
<body bgcolor=”pink”>
<br><br><br><br><br><br>
<h1 align=”center”>>U>ONLINE BOOK STORAGE</u></h1><br><br><br>
<h2 align=”center”><PRE>
<b> Welcome to online book storage.
Press LOGIN if you are having id
Otherwise press REGISTRATION
</b></PRE></h2>
<br><br><pre>
<div align=”center”><a href=”/tr/login.html”>LOGIN</a>
href=”/tr/login.html”>REGISTRATION</a></div></pre>
</body></html>

Login.html:
<html>
<body bgcolor=”pink”><br><br><br>
<form name="myform" method="post" action=/tr1/login.jsp">
<div align="center"><pre>
LOGIN ID : <input type="passwors" name="pwd"></pre><br><br>
PASSWORD : <input type="password" name="pwd"></pre><br><br>
</div>
<br><br>
<div align="center">
<inputtype="submit"value="ok"
onClick="validate()">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="reset"
value="clear">
</form>
</body>
</html>
Reg.html:
<html>
<body bgcolor="pink"><br><br>
<form name="myform" method="post" action="/tr1/reg.jsp">
<div align="center"><pre>
NAME :<input type="text" name="name"><br>
ADDRESS :<input type="text" name="addr"><br>
CONTACT NUMBER : <input type="text" name="phno"><br>
LOGIN ID : <input type="text" name="id"><br>
PASSWORD : <input type="password" name="pwd"></pre><br><br>
</div>
<br><br>
<div align="center">
<inputtype="submit"value="ok"
onClick="validate()">()">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="reset"
value="clear">
</form>
</body>
</html>

Profile.html:
<html>
<body bgcolor="pink"><br><br>
<form name="myform" method="post" action="/tr1/profile.jsp">
<div align="center"><pre>
LOGIN ID : <input type="text" name="id"><br>
</pre><br><br>
</div>
<br><br>
<div align="center">
<inputtype="submit"value="ok"
onClick="validate()">()">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="reset"
value="clear">
</form>
</body>
</html>

Catalog.html:
<html>
<body bgcolor="pink"><br><br><br>
<form method="post" action="/tr1/catalog.jsp">
<div align="center"><pre>
BOOK TITLE : <input type="text" name="title"><br>
</pre><br><br>
</div>
<br><br>
<div align="center">
<inputtype="submit"value="ok"
name=”button1”>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<inputtype="reset"value="clear"
name=”button2”>
</form>
</body>
</html>

Order.html:
<html>
<body bgcolor="pink"><br><br><br>
<form method="post" action="/tr1/order.jsp">
<div align="center"><pre>
LOGIN ID :<input type="text" name="id"><br>
PASSWORD : <input type="password" name="pwd"><br>
TITLE :<input type="text" name="title"><br>
NO. OF BOOKS : <input type="text" name="no"><br>
DATE : <input type="text" name="date"><br>
CREDIT CARD NUMBER : <input type="password" name="cno"><br></pre><br><br>
</div>
<br><br>
<div align="center">
<input type="submit" value="ok" name=”button1”>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input
type="reset"
value="clear" name=”button2”>
</form>
</body>
</html>

Login.jsp:
%@page import=”java.sql.*”%
%@page import=”java.io.*”%
<%
out.println(“<html><body bgcolor=\”pink\”>”);
String id=request.getParameter(“id”);
String pwd=request.getParameter(“pwd”);
Driver d=new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver(d);
Connection
con=DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:orcl”,”scott”,”tiger”);
Statement stmt=con.createStatement();
String sqlstmt=”select id,password from login where id=”+id+” and password=”+pwd+””;
ResultSet rs=stmt.executeQuery(sqlstmt);
int flag=0;
while(rs.next())
{
flag=1;
}
if(flag==0)
{
out.println(“SORRY INVALID ID TRY AGAIN ID<br><br>”);
out.println(“ <a href=\”/tr1/login.html\”>press LOGIN to RETRY</a>”);
}
else
{
out.println(“VALID LOGIN ID<br><br>”);
out.println(“<h3><ul>”);
out.println(“<li><ahref=\”profile.html\”><fontcolor=\”black\”>USER
PROFILE</font></a></li><br><br>”);
out.println(“<li><ahref=\”catalog.html\”><fontcolor=\”black\”>BOOKS
CATALOG</font></a></li><br><br>”);
out.println(“<li><ahref=\”order.html\”><fontcolor=\”black\”>ORDER
CONFIRMATION</font></a></li><br><br>”);
out.println(“</ul>”);
}
out.println(“<body></html>”);
%>

Reg.jsp:
%@page import=”java.sql.*”%
%@page import=”java.io.*”%
<%
out.println(“<html><body bgcolor=\”pink\”>”);
String name=request.getParameter(“name”);
String addr=request.getParameter(“addr”);
String phno=request.getParameter(“phno”);
String id=request.getParameter(“id”);
String pwd=request.getParameter(“pwd”);
int no=Integer.parseInt(phno);
Driver d=new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver(d);
Connection con=
DriverManager.getConnection (“jdbc:oracle:thin:@localhost:1521:orcl”,”scott”,”tiger”);
Statement stmt=con.createStatement();
String sqlstmt=”select id from login”;
ResultSet rs=stmt.executeQuery(sqlstmt);
int flag=0;
while(rs.next())
{
if(id.equals(rs.getString(1)))
{
flag=1;
}
}
if(flag==1)
{
out.println(“SORRY LOGIN ID ALREADY EXISTS TRY AGAIN WITH NEW ID
<br><br>”);
out.println(“<a href=\”/tr1/reg.html\”>press REGISTER to RETRY</a>”);
}
else
{
Statement stmt1=con.createStatement ();
stmt1.executeUpdate (“insert into login values
(“+name+”,”+addr+”,”+no+”,”+id+”,”+pwd+”)”);
out.println (“YOU DETAILS ARE ENTERED <br><br>”);
out.println (“<a href =\”/tr1/login.html\”>press LOGIN to login</a>”);
}
out.println (“</body></html>”);
%>

Profile.jsp:
<%@page import=”java.sql.*”%>
<%@page import=”java.io.*”%>
<%
out.println (“<html><body bgcolor=\”pink\”>”);
String id=request.getParameter(“id”);
Driver d=new oracle.jdbc.driver.OracleDriver();
DriverManager.regiserDriver(d);
Connection con=
DriverManager.getConnection (“jdbc:oracle:thin:@localhost:1521:orcl”,”scott”,”tiger”);
Statement stmt=con.createStatement ();
String sqlstmt=”select * from login where id=”+id+””;
ResultSet rs=stmt.executeQuery (sqlstmt);
int flag=0;
while(rs.next())
{
out.println (“<div align=\”center\”>”);
out.println (“NAME :”+rs.getString(1)+”<br>”);
out.println (“ADDRESS :”+rs.getString(2)+”<br>”);
out.println (“PHONE NO :”+rs.getString(3)+”<br>”);
out.println (“</div>”);
flag=1;
}
if(flag==0)
{
out.println(“SORRY INVALID ID TRY AGAIN ID <br><br>”);
out.println(“<a href=\”/tr1/profile.html\”>press HERE to RETRY </a>”);
}
out.println (“</body></html>”);
%>
Catalog.jsp:
<%@page import=”java.sql.*”%>
<%@page import=”java.io.*”%>
<%
out.println (“<html><body bgcolor=\”pink\”>”);
String title=request.getParameter (“title”);
Driver d=new oracle.jdbc.driver.OracleDriver ();
DriverManager.regiserDriver (d);
Connection con=
DriverManager.getConnection (“jdbc:oracle:thin:@localhost:1521:orcl”,”scott”,”tiger”);
Statement stmt=con.createStatement ();
String sqlstmt=”select * from book where title=”+title+””;
ResultSet rs=stmt.executeQuery (sqlstmt);
int flag=0;
while(rs.next())
{
out.println (“<div align=\”center\”>”);
out.println (“TITLE :”+rs.getString(1)+”<br>”);
out.println (“AUTHOR :”+rs.getString(2)+”<br>”);
out.println (“VERSION:”+rs.getString(3)+”<br>”);
out.println (“PUBLISHER :” +rs.getString(4)+”<br>”);
out.println (“COST :” +rs.getString(5)+”<br>”);
out.println (“</div>”);
flag=1;
}
if(flag==0)
{
out.println(“SORRY INVALID ID TRY AGAIN ID <br><br>”);
out.println(“<a href=\”/tr1/catalog.html\”>press HERE to RETRY </a>”);
}
out.println (“</body></html>”);
%>

Order.jsp:
<%@page import=”java.sql.*”%>
<%@page import=”java.io.*”%>
<%
out.println (“<html><body bgcolor=\”pink\”>”);
String id=request.getParameter (“id”);
String pwd=request.getParameter (“pwd”);
String title=request.getParameter (“title”);
String count1=request.getParameter (“no”);
String date=request.getParameter (“date”);
String cno=request.getParameter (“cno”);
int count=Integer.parseInt(count1);
Driver d=new oracle.jdbc.driver.OracleDriver ();
DriverManager.regiserDriver (d);
Connection con=
DriverManager.getConnection (“jdbc:oracle:thin:@localhost:1521:orcl”,”scott”,”tiger”);
Statement stmt=con.createStatement ();
String sqlstmt=”select id, password from login”;
ResultSet rs=stmt.executeQuery (sqlstmt);
int flag=0,amount,x;
while(rs.next())
{
if(id.equals(rs.getString(1))&& pwd.equals(rs.getString(2)))
{
flag=1;
}
}
if(flag==0)
{
out.println(“SORRY INVALID ID TRY AGAIN ID <br><br>”);
out.println(“<a href=\”/tr1/order.html\”>press HERE to RETRY </a>”);
}
else
{
Statement stmt2=con.createStatement();
String s=”select cost from book where title=”+title+””;
ResultSet rs1=stmt2.executeQuery(s);
int flag1=0;
while(rs1.next())
{
flag1=1;
x=Integer.parseInt(rs1.getString(1));
amount=count*x;
out.println(“AMOUNT :”+amount+”<br><br><br><br>”);
Statement stmt1=con.createStatement ();
stmt1.executeUpdate (“insert into details (“+id+”,”+title+”,”+amount+”,”+date+”,”+cno+”)”);
out.println (“YOU ORDER HAS TAKEN<br>”);
}
if(flag1==0)
{
out.println(“SORRY INVALID BOOK TRY AGAIN <br><br>”);
out.println(“<a href=\”/tr1/order.html\”>press HERE to RETRY </a>”);
}
} out.println (“</body></html>”);%>
Problem 6: Implement the “Hello World!” program using JSP Struts Framework.

Solution:

PROCEDURE:

Step 1:
In tomcat install directory
Open tomcat/webapps
Create a subdirectory(ts)
Copy the struts‐blank.war file
At that directory path in cmd give the command as
Jar xvf struts‐blank.war

Step 2:
create a directory (work in e:\) and copy struts.jar,servelet‐appi.jar into work d directory.Then set the
classpath as
set classpath=struts.jar;servlet‐api.jar;
then copy the ActionOne.class file to webapps/ts/WEB‐INF/classes
ActionOne.java:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.struts.action.*;
public class ActionOne extends Action
{
publicActionForwardexecute(ActionMappingmapping,ActionFormform,HttpServletRequest
request,HttpServletResponse response)throws Exception
{
System.out.println("‐‐‐Action executed‐‐‐‐");
PrintWriter pw=response.getWriter();
pw.println("HELLO WORLD!");
return null;
}
}

Step 3:
Struts‐Config.xml file
<?xml version="1.0" encoding="UTF‐8"?>
<struts‐config>
<action‐mappings>
<action path="/xxx" type="ActionOne"/>
</action‐mappings>
</struts‐config>

Step 4:
Web.xml
<?xml version="1.0" encoding="ISO‐8859‐1"?>
<web‐app>
<servlet>
<servlet‐name>action</servlet‐name>
<servlet‐class>org.apache.struts.action.ActionServlet</servlet‐class>
<init‐‐param>
<param‐name>config</param‐name>
<param‐value>/WEB‐INF/struts‐config.xml</param‐value>
</init‐param>
<init‐param>
<param‐name>debug</param‐name>
<param‐value>2</param‐value>
</init‐param>
<load‐on‐startup>2</load‐on‐startup>
</servlet>
<!‐‐Standard Action Servlet Mapping ‐‐>
<servlet‐mapping>
<servlet‐name>action</servlet‐name>
<url‐pattern>*.do</url‐pattern>
</servlet‐mapping>
<!‐‐ The Usual Welcome File List ‐‐>
<welcome‐file‐list>
<welcome‐file>index.jsp</welcome‐file>
</welcome‐file‐list>
<!‐‐ Struts Tag Library Descriptors ‐‐>
<taglib>
<taglib‐uri>/tags/struts‐bean</taglib‐uri>
<taglib‐location>/WEB‐INF/struts‐html.tld</taglib‐location>
</taglib>
<taglib>
<taglib‐uri>/tags/struts‐logic</taglib‐uri>
<taglib‐location>/WEB‐INF/struts‐logic.tld</taglib‐location>
</taglib>
<taglib>
<taglib‐uri>/tags/struts‐nested</taglib‐uri>
<taglib‐location>/WEB‐INF/struts‐nested.tld</taglib‐location>
</taglib>
<taglib>
<taglib‐uri>/tags/struts‐tiles</taglib‐uri>
<taglib‐location>/WEB‐INF/struts‐tiles.tld</taglib‐location>
</taglib>
</web‐app>

Step 5:
Then in I.E give the url as http:localhost:8080/ts/xxx.do
Problem 2: Validate the Registration, user login, user profile and payment by credit card pages
using JavaScript.

Solution:

Validation.js
function form1_validation()
{
//Username Validation
if(f1.username.value=="")
{
alert("You must enter a User Name");
f1.username.focus();
return false;
}
if(f1.username.value.length<3)
{
alert("User Name must consist of atleast 3 character");
f1.username.focus();
return false;
}
var checkStr=f1.username.value;
for(i=0;i<checkStr.length;i++)
if(!(checkStr.charCodeAt(i)>=65&&checkStr.charCodeAt(i)<=91)
&& !(checkStr.charCodeAt(i)>=97 && chec
kStr.charCodeAt(i)<=122))
{
alert("Please enter valid User Name");
f1.username.focus();
return false;
}
//Password Validation
if(f1.password.value.length<6)
{
alert("Please enter Password not less than 6");
f1.password.focus();
return false;
}
if(!(f1.password.value==f1.password1.value))
{
alert("Please re-enter corrert Password");
f1.password1.focus();
return false;
}
//email validation
flag=true;
if(f1.email.value=="")
flag=false;
var Str=f1.email.value;
if(allValidChars(Str))
for(i=0;i<Str.length;i++)
if(Str.charAt(i)=="@")
{
if((Str.substr(i+1,9)=="yahoo.com")||(Str.substr(i+1,9)=="gmail.com"))
{
flag=true;
break;
}
}
else
flag=false;
if(!(flag))
{
alert("Please enter a valid Email ID");
f1.email.focus();
return false;
}
//phone number validation
flag=true;
if(f1.phno.value.length!=10)
flag=false;
var phno=f1.phno.value;
for(i=0;i<phno.length;i++)
if(!(phno.charCodeAt(i)>=48&&phno.charCodeAt(i)<=57))
flag=false;
if(!flag)
{
alert("Please enter valid Phone Number");
f1.phno.focus();
return false;
}
//gender validation
flag=false;
for(i=0;i<f1.radio.length;i++)
if(f1.radio[i].checked)
flag=true;
if(!(flag))
{
alert("Please choose a Gender");
return false;
}
//Date of birth validation
if((f1.dd.selectedIndex<=0)||(f1.mm.selectedIndex<=0)||(f1.yyyy.sele
ctedIndex<=0))
{
alert("Please choose a Date of Birth");
f1.phno.focus();
return false;
}
//checkbox validation
flag=false;
for (i = 0; i < f1.checkbox.length; i++)
{
if (f1.checkbox[i].checked)
flag = true;
}
if(!(flag))
{
alert("Please select at least one of the
\
"Language
\
" options.");
return false;
}
//address validation
if(f1.address.value.length<25)
{
alert("Please enter a Correct Address");
return false;
}
}
function allValidChars(email)
{
var validchars = "abcdefghij
klmnopqrstuvwxyz0123456789@.
-
_";
for (i=0; i < email.length; i++)
{
var letter = email.charAt(i).toLowerCase();
if (validchars.indexOf(letter) ==
-
1)
return false;
} return true;
}
Login.html
<html>
<head>
<title> Welcome to AMAZON website</title>
<link rel="stylesheet" href="style.css" type="text/css">
<script type="text/javascript" src="validation.js"></script>
</head>
<body >
<center>
<h3> Enter Login Details</h3>
<br/>
<form name="f1" onsubmit="return form1_validation()">
<table align="center" >
<tr> <td> User ID</td>
<td> <input type="text" name="username"></td> </tr>
<tr> <td> Password</td>
<td> <input type="password" name="password"></td> </tr>
<tr> <td></td>
<td><input type="submit" value="Submit"></td>
<input type="reset" value="Reset"></td>
</tr>
<tr> <td colspan=2>Forgot my User ID or Password</td>
</tr>
</table>
</html>
(ii) Additional Assignment Problems

Problem 1: Write an HTML page including any required Javascript that takes a number from
one text field in the range of 0 to 999 and shows it in another text field in words. If the number is
out of range, it should show “out of range” and if it is not a number, it should show “not a
number” message in the result box.

Solution:

<html>
<head>
<title>Example1</title>
<script>
function checkfun()
{
var num = document.f1.num1.value;
var a= new RegExp("[0-9]");
if(!a.test(num))
alert("enter numbers only");
if(num.length>3)
alert("out of range");
var SingleDigits = new Array("Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven",
"Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen",
"Seventeen", "Eighteen", "Nineteen");
var DoubleDigits = new Array("Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy",
"Eighty", "Ninety");
var Words = "";
var St;
for (var i = 9; i >= 1; i--) {
if (num >= i * 100) {
Words += SingleDigits[i];
St = 1;
Words += " hundred";
if (num != i * 100) Words += " and ";
{ num -= i*100; }
i=0; }
}
//alert(Words);
for (var i = 9; i >= 2; i--) {
if (num >= i * 10)
{
Words += (St?DoubleDigits[i-2].toLowerCase():DoubleDigits[i-2]);
St = 1;
if (num != i * 10) Words += "-";
{
num -= i*10;
}
i=0;
}
}
//alert(Words);

for (var i = 1; i < 20; i++)


{
if (num == i)
{
Words += (St?SingleDigits[i].toLowerCase():SingleDigits[i]);
}
}
//alert(Words);

f1.res.value = Words;
//document.f1.res.value = Words;
}

</script>
</head>
<body>
<form name="f1">
<font background-color=pink color=green>
enter a num<input type=text name=num1>
<input type="button" value=validate onclick="checkfun()">
result<textarea name=res></textarea>
</font>
</form>
</body>
</html>

Problem 2: Write a java swing application that takes a text file name as input and counts the
characters, words and lines in the file. Words are separated with white space characters and lines
are separated with new line character.

Solution:

import java.awt.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import java.awt.event.*;
public class WordCount extends JApplet implements ActionListener
{
JTextField t1;
Label l1;
String msg=" ";
public void init()
{
Container contentpane=getContentPane();
contentpane.setLayout(new FlowLayout());
l1=new Label("Enter the filename");
t1=new JTextField(10);
contentpane.add(l1);
contentpane.add(t1);
t1.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
msg=" ";
String fn=t1.getText();
try{
msg=count(fn);
repaint();
}
catch(Exception e)
{
msg="Error: Invalid file name";
repaint();
}
}
String count(String s) throws IOException
{
int char_count=0;
int word_count=0;
int line_count=0;
StringTokenizer st;
BufferedReader buf=new BufferedReader(new FileReader(s));
while((s=buf.readLine())!=null)
{
line_count++;
st=new StringTokenizer(s," ,;:.");
while(st.hasMoreTokens())
{
word_count++;
s=st.nextToken();
char_count+=s.length();
}
}
buf.close();
return "No of lines :"+line_count+"\n No of words:"+word_count+"\n No of
Characters:"+char_count;
}
public void paint(Graphics g)
{
g.drawString(msg,50,50);
}

}
/*<applet code="WordCount.class" height=200 width=100>
</applet> */

Problem 3: Write a simple calculator servlet that takes two numbers and an operator (+, -, /, *
and %) from an HTML page and returns the result page with the operation performed on the
operands. It should check in a database if the same expression is already computed and if so, just
return the value from database. Use MySQL or PostgreSQL.

Solution:

package mypackage;

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

public class Calculator extends HttpServlet


{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
try
{
response.setContentType("text/html");
PrintWriter out= response.getWriter();
int a1= Integer.parseInt(request.getParameter("n1"));
int a2= Integer.parseInt(request.getParameter("n2"));
if(request.getParameter("r1")!=null)
{
out.println("<h1>Addition</h1>"+(a1+a2));
}
if(request.getParameter("r2")!=null)
{
out.println("<h1>Substraction</h1>"+(a1-a2));
}
if(request.getParameter("r3")!=null)
{
out.println("<h1>Multiplication</h1>"+(a1*a2));
}if(request.getParameter("r1")!=null)
{
out.println("<h1>Division</h1>"+(a1/a2));
}
}
catch(Exception e)
{

}
}
}

index.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"


"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Calculator</title>
</head>
<body>
<h1 style="text_align=center">Calculator</h1>
<form method="get" action="/Servlet">
<label>first number:</label>
<input type="text" name="n1" />
<br />
<label>Second number : </label>
<input type="text" name="n2" />
<br />
<div>
<label>
<input type="radio" name="r1" value="add" />addition
<br />
</label>
<input type="radio" name="r2" value="sub" />subtraction
<br />
<input type="radio" name="r3" value="mul" />multiplication
<br />
<input type="radio" name="r4" value="div" />division
<br />
</div>
<input type="button" value="submit" />
</form>
</body>
</html>

web.xml:

<?xml version="1.0" encoding="UTF-8"?>


<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-
app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>Servlet</display-name>
<servlet>
<servlet-name>Servlet</servlet-name>
<servlet-class>mypackage.Calculator</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Servlet</servlet-name>
<url-pattern>/firstHomePage</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>

Problem 4: Write an HTML page that contains a list of 5 countries. When the user selects a
country, its capital should be printed next to the list. Add CSS to customize the properties of the
font of the capital (color, bold and font size).

Solution:

<html>
<head>
<title>Countries & Capitals </title>
<body>
<h3> Countries and Capitals </h3>
<form name="f1">
Country<select name="country" onChange=call()>
<option> </option>
<option value="India">India</option>
<option value="France">France</option>
<option value="Nepal">Nepal</option>
<option value="Japan">Japan</option>
<option value="Germany">Germany</option>
</select> Capital <input type="text" name="capital" style="font-size:large; font-
weight:bold;color:red">
</form>
<script>
var result=" ";
function call(){
id=f1.country.selectedIndex;
con=f1.country.options[id].value;
if(con=="India")
result="New Delhi";
else if(con=="France")
result="Paries";
else if(con=="Nepal")
result="Kathmandu";
else if(con=="Japan")
result="Tokyo";
else if(con=="Germany")
result="Berlin";
f1.capital.value=result; }
</script>
</body> </html>

Problem 6: Write a calculator program in HTML that performs basic arithmetic operations (+, -,
/, * and %). Use CSS to change the foreground and background color of the values, buttons and
result display area separately. Validate the input strings using JavaScript regular expressions.
Handle any special cases like division with zero reasonably. The screen may look similar to the
following:

Solution:

<html>
<head>
<title>
CALCULATOR</title>
<script>
function cal()
{
var a=parseInt(document.f2.num1.value);
var b=parseInt(document.f2.num2.value);
var op=document.f2.coun.value;
var res1;
switch(op)
{
case '+': res1 = a +b;
break;
case '-': res1 = a-b;
break;
case '*': res1 = a*b;
break;
case '/': res1 = a/b;
break;
case '%': res1 = a%b;
break;
}
f2.res.value=res1;
}
</script>
</head>
<body>
<form name="f2">
value1<input type=text name=num1>
operater<select name="coun">
<option >+</option>
<option >-</option>
<option >*</option>
<option >/</option>
<option >%</option>
</select>
value2<input type=text name=num2>
<input type=button value="=" onclick="cal()">
result<input type=text name=res>
</form>
</body>
</html>
(iii) Internet Technologies and Services Lab - Additional Problems
Problem 1: Write a Java program that takes a file as input and encrypts it using DES encryption.
The program should check if the file exists and its size is not zero.

Solution:

package test;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

public class CipherExample {

public static void main(String[] args) {


try {
String key = "squirrel123"; // needs to be at least 8 characters for
DES
FileInputStream fis = new FileInputStream("original.txt");
FileOutputStream fos = new FileOutputStream("encrypted.txt");
encrypt(key, fis, fos);

FileInputStream fis2 = new FileInputStream("encrypted.txt");


FileOutputStream fos2 = new FileOutputStream("decrypted.txt");
decrypt(key, fis2, fos2);
} catch (Throwable e) {
e.printStackTrace();
}
}

public static void encrypt(String key, InputStream is, OutputStream os) throws
Throwable {
encryptOrDecrypt(key, Cipher.ENCRYPT_MODE, is, os);
}

public static void decrypt(String key, InputStream is, OutputStream os) throws
Throwable {
encryptOrDecrypt(key, Cipher.DECRYPT_MODE, is, os);
}

public static void encryptOrDecrypt(String key, int mode, InputStream is,


OutputStream os) throws Throwable {

DESKeySpec dks = new DESKeySpec(key.getBytes());


SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
SecretKey desKey = skf.generateSecret(dks);
Cipher cipher = Cipher.getInstance("DES"); // DES/ECB/PKCS5Padding for
SunJCE

if (mode == Cipher.ENCRYPT_MODE) {
cipher.init(Cipher.ENCRYPT_MODE, desKey);
CipherInputStream cis = new CipherInputStream(is, cipher);
doCopy(cis, os);
} else if (mode == Cipher.DECRYPT_MODE) {
cipher.init(Cipher.DECRYPT_MODE, desKey);
CipherOutputStream cos = new CipherOutputStream(os, cipher);
doCopy(is, cos);
}
}

public static void doCopy(InputStream is, OutputStream os) throws IOException {


byte[] bytes = new byte[64];
int numBytes;
while ((numBytes = is.read(bytes)) != -1) {
os.write(bytes, 0, numBytes);
}
os.flush();
os.close();
is.close();
}

Problem 2: Write a Java program that generates a key pair and encrypts a given file using RSA
algorithm.

Solution:

package in.javadigest.encryption;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;

import javax.crypto.Cipher;

public class EncryptionUtil {

/**
* String to hold name of the encryption algorithm.
*/
public static final String ALGORITHM = "RSA";

/**
* String to hold the name of the private key file.
*/
public static final String PRIVATE_KEY_FILE = "C:/keys/private.key";

/**
* String to hold name of the public key file.
*/
public static final String PUBLIC_KEY_FILE = "C:/keys/public.key";

/**
* Generate key which contains a pair of private and public key using 1024
* bytes. Store the set of keys in Private.key and Public.key files.
*
* @throws NoSuchAlgorithmException
* @throws IOException
* @throws FileNotFoundException
*/
public static void generateKey() {
try {
final KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM);
keyGen.initialize(1024);
final KeyPair key = keyGen.generateKeyPair();

File privateKeyFile = new File(PRIVATE_KEY_FILE);


File publicKeyFile = new File(PUBLIC_KEY_FILE);
// Create files to store public and private key
if (privateKeyFile.getParentFile() != null) {
privateKeyFile.getParentFile().mkdirs();
}
privateKeyFile.createNewFile();

if (publicKeyFile.getParentFile() != null) {
publicKeyFile.getParentFile().mkdirs();
}
publicKeyFile.createNewFile();

// Saving the Public key in a file


ObjectOutputStream publicKeyOS = new ObjectOutputStream(
new FileOutputStream(publicKeyFile));
publicKeyOS.writeObject(key.getPublic());
publicKeyOS.close();

// Saving the Private key in a file


ObjectOutputStream privateKeyOS = new ObjectOutputStream(
new FileOutputStream(privateKeyFile));
privateKeyOS.writeObject(key.getPrivate());
privateKeyOS.close();
} catch (Exception e) {
e.printStackTrace();
}

/**
* The method checks if the pair of public and private key has been generated.
*
* @return flag indicating if the pair of keys were generated.
*/
public static boolean areKeysPresent() {

File privateKey = new File(PRIVATE_KEY_FILE);


File publicKey = new File(PUBLIC_KEY_FILE);

if (privateKey.exists() && publicKey.exists()) {


return true;
}
return false;
}

/**
* Encrypt the plain text using public key.
*
* @param text
* : original plain text
* @param key
* :The public key
* @return Encrypted text
* @throws java.lang.Exception
*/
public static byte[] encrypt(String text, PublicKey key) {
byte[] cipherText = null;
try {
// get an RSA cipher object and print the provider
final Cipher cipher = Cipher.getInstance(ALGORITHM);
// encrypt the plain text using the public key
cipher.init(Cipher.ENCRYPT_MODE, key);
cipherText = cipher.doFinal(text.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
return cipherText;
}

/**
* Decrypt text using private key.
*
* @param text
* :encrypted text
* @param key
* :The private key
* @return plain text
* @throws java.lang.Exception
*/
public static String decrypt(byte[] text, PrivateKey key) {
byte[] dectyptedText = null;
try {
// get an RSA cipher object and print the provider
final Cipher cipher = Cipher.getInstance(ALGORITHM);

// decrypt the text using the private key


cipher.init(Cipher.DECRYPT_MODE, key);
dectyptedText = cipher.doFinal(text);

} catch (Exception ex) {


ex.printStackTrace();
}
return new String(dectyptedText);
}

/**
* Test the EncryptionUtil
*/
public static void main(String[] args) {

try {

// Check if the pair of keys are present else generate those.


if (!areKeysPresent()) {
// Method generates a pair of keys using the RSA algorithm and stores it
// in their respective files
generateKey();
}

final String originalText = "Text to be encrypted ";


ObjectInputStream inputStream = null;

// Encrypt the string using the public key


inputStream = new ObjectInputStream(new FileInputStream(PUBLIC_KEY_FILE));
final PublicKey publicKey = (PublicKey) inputStream.readObject();
final byte[] cipherText = encrypt(originalText, publicKey);

// Decrypt the cipher text using the private key.


inputStream = new ObjectInputStream(new FileInputStream(PRIVATE_KEY_FILE));
final PrivateKey privateKey = (PrivateKey) inputStream.readObject();
final String plainText = decrypt(cipherText, privateKey);

// Printing the Original, Encrypted and Decrypted Text


System.out.println("Original: " + originalText);
System.out.println("Encrypted: " +cipherText.toString());
System.out.println("Decrypted: " + plainText);

} catch (Exception e) {
e.printStackTrace();
}
}
}

Potrebbero piacerti anche