Lab Manual
Lab Manual
AIM:
To create a web page which includes a map and display the related information when a hot spot is
clicked in the map.
PROCEDURE:
Create a html file with map tag
Set the source attribute of the img tag to the location of the image and also set the use map attribute
Specify an area with name, shape and href set to the appropriate values
Repeat step 3 as many hot spots you want to put in the map
Create html files for each and every hot spot the user will select
PROGRAM
LIGHTMAP.HTML
<html>
<body>
<h1>The map and area elements</h1>
<p>Click on the Light house picture, Sea, or rocks to go to a new page and read more about the topic:</p>
<img src="Lighthouse.jpg" alt="Eveninghouse" usemap="#Lighthousemap" width="1024" height="763">
<map name="Lighthousemap">
<area shape="rect" coords="3,53,295,353" alt="Lighthouse" href="Lighthouse_spot.html">
<area shape="rect" coords="812,377,1021,427" alt="Sea" href="Sea_spot.html">
<area shape="rect" coords="151,404,1019,763" alt="Rock" href="Rock_spot.html">
</map>
</body>
</html>
Lighthouse_spot.html
<html>
<head>
<Title>Lighthouse</Title>
</head>
<body>
<img src="lighthouse_pic.jpg">
<p><h1>Light House</h1> <p>
<p>lighthouse, structure, usually with a tower, built onshore or on the seabed to serve as an aid to maritime
coastal navigation, warning mariners of hazards, establishing their position, and guiding them to their
destinations. From the sea a lighthouse may be identified by the distinctive shape or colour of its structure, by
the colour or flash pattern of its light, or by the coded pattern of its radio signal.The development of electronic
navigation systems has had a great effect on the role of lighthouses.</p>
</body>
</html>
Sea_spot.html
<html>
<head>
<Title>Sea</Title>
</head>
<body>
<img src="sea_pic.jpg">
<p><h1>Sea</h1> <p>
<p>In general, a sea is defined as a portion of the ocean that is partly surrounded by land.
Given that definition, there are about 50 seas around the world. But that number includes water
bodies not always thought of as seas, such as the Gulf of Mexico and the Hudson Bay</p>
</body>
</html>
OUTPUT:
RESULT:
Thus the creation of a web page which includes a map and display the related in-formation when a hot
spot is clicked in the map was executed successfully
EX NO:2 CASCADING STYLE SHEETS
AIM:
To create a web page that displays college information using various style sheet
PROCEDURE:
Create a web page with frame sets consisting two frames
In the first frame include the links
In the second frame set display the web page of the link
Create a external style sheets
Create a embedded style sheets
Create a inline and internal style sheets and make it link to the external style sheets
PROGRAM:
CSS CODE:
External.css
h3{font-family:arial;font-size:20;color:cyan}
table{border-color:green}
td{font-size:20pt;color:magenta}
style.html
<html>
<head><h1><center>ALL STYLE SHEETS</center></h1>
<title>USE of STYLESHEETS
</title>
<link rel="stylesheet" href="External.css" type="text/css">
<!-- External Style Sheet -->
<style type="text/css">
<!-- Internal Style Sheet -->
.S1{font-family:verdana; font-style:italic; color:red; text-align:center}
.S2{font-family:tahoma; font-style:italic; font-size:20; text-align:center;}
font{font-family:georgia; color:blue; font-size:20}
ul{list-style-type:circle}
</style>
</head>
<body>
<ol style="list-style-type:lower-alpha">
<b> Anna University </b><br><br><br>
<li> Mahendra Engineering College, Namakkal
<li> Mahendra Institute of Technology, Namakkal
<li> Mahendra Institute of Engineering and Technology, Namakkal
</ol>
<p style="font-size:20pt;color:purple">
About our College</p> <!-- InlineStyle Sheet -->
<p class="S2"> Run by Anna University, Chennai<br>
It is approved by AICTE.NAAC A grade
<br>
</p>
</table>
</body>
</html>
RESULT:
Thus the program to create a web page that displays college information using various style sheet
EX NO:3 VALIDATE THE USER LOGIN USING JAVA SCRIPT
AIM:
To create a user login page for password validation using java script.
PROCEDURE:
Create a html file with css and javascript
validate the password by ensuring that both the user's password and the password entered by the user
are the same
validation Form with usernameand use all the validations in point and then created a form with a
username.
Create password, and confirm password are the fields.
The fields marked with an asterisk (*) are mandatory fields in which the user must provide data.
PROGRAM:
<html>
<head>
<center>
<title> Password Validation</title>
</head>
<script>
function validateForm() {
var pw1 = document.getElementById("pswd1").value;
var pw2 = document.getElementById("pswd2").value;
var name1 = document.getElementById("fname").value;
if(name1 == "") {
document.getElementById("blankMsg").innerHTML = "**Fill the first name";
return false;
}
if(!isNaN(name1)){
document.getElementById("blankMsg").innerHTML = "**Only characters are allowed";
return false;
}
if(pw1 == "") {
document.getElementById("message1").innerHTML = "**Fill the password please!";
return false;
}
if(pw2 == "") {
document.getElementById("message2").innerHTML = "**Enter the password please!";
return false;
}
if(pw1.length < 8) {
document.getElementById("message1").innerHTML = "**length must be atleast 8 characters";
return false;
}
if(pw1.length > 15) {
document.getElementById("message1").innerHTML = "**length must not exceed 15 characters";
return false;
}
if(pw1 != pw2) {
document.getElementById("message2").innerHTML = "**Passwords are not same! Retry with new
Password";
return false;
} else {
alert ("password created successfully");
document.write("form has been submitted successfully");
}
}
</script>
<body>
<h1 style="color:orange">password validation using java script</h1>
<h3> Please Fill the form </h3>
<form onsubmit ="return validateForm()">
<td> Full Name* </td>
<input type = "text" id = "fname" value = "">
<span id = "blankMsg" style="color:orange"> </span> <br><br>
<td> Create Password* </td>
<input type = "password" id = "pswd1" value = "">
<span id = "message1" style="color:orange"> </span> <br><br>
<td> Confirm Password* </td>
<input type = "password" id = "pswd2" value = "">
<span id = "message2" style="color:orange"> </span> <br><br>
<input type = "submit" value = "Submit">
<button type = "reset" value = "Reset" >Reset</button>
</form>
</body>
</center>
</html>
OUTPUT:
RESULT:
Thus the user login page for password validation using java script is created successfully
EX NO:4a INVOKING SERVLETS FROM HTML FORM
AIM:
To write a java program to invoke servlets from HTML form.
ALGORITHM:
client.html
(1) Create a web page using HTML form that contains the fields such as text, password and one submit
button.
(2) Set the URL of the server as the value of form’s action attribute.
(3) Run the HTML program.
(4) Submit the form data to the server.
server.java
(1) Define the class server that extends the property of the class GenericServlet.
(2) Handle the request from the client by using the method service() of GenericServlet class.
(3) Get the parameter names from the HTML form by using the method getParameterNames().
(4) Get the parameter values from the HTML forms by using the method getParameter().
(5) Send the response to the client by using the method of PrintWriter class.
PROGRAM
server.java:
import java.io.*;
import java.util.*;
import javax.servlet.*;
public class server extends GenericServlet
{
public void service(ServletRequest req,ServletResponse res)throws ServletException,IOException
{
PrintWriter pw=res.getWriter();
pw.print("<h3>Registration Successful...</h3>");
Enumeration e=req.getParameterNames();
while(e.hasMoreElements())
{
String str1=(String)e.nextElement();
String str2=req.getParameter(str1);
pw.print(str1+"="+str2+"<br/>");
}
pw.close();
}
}
web.xml:
<web-app>
<servlet>
<servlet-name>Register</servlet-name>
<servlet-class>server</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Register</servlet-name>
<url-pattern>/server</url-pattern>
</servlet-mapping>
</web-app>
Client.HTML:
<html>
<head>
<title>Invoking Servlet From HTML</title>
</head>
<body bgcolor="violet">
<form name="form1" method="post" action="http://localhost:8080/servlets1/server">
<fieldset>
<legend>Registration</legend>
Enter E-mail :
<input type="text" name="LoginID" size="25"/><br/><br/>
Enter Password:
<input type="password" name="Password" size="25">
<input type="submit" Value="SUBMIT">
</fieldset>
</form>
</body>
</html>
OUTPUT:
Result:
Thus the program to invoke servlets from HTML form is executed and verified successfully.
EX.NO:4b SESSION TRACKING USING HIDDEN FORM FIELDS
AIM:
To write a Java Program for Session Tracking Using Hidden Form Fields. This servlet demonstrates
session tracking using hidden form fields by displaying the shopping cart for a bookworm. Note that, if you try
this servlet, the buttons at the bottom of the page it generates don't take you anywhere real.
PROCEDURE:
Create a web page using HTML form that contains the fields such as text, password and one submit
button.
Set the URL of the server as the value of form’s action attribute.
Ask if the user wants to add more items or check out.
Include the current items as hidden fields so they'll be passed on and submit to self.
PROGRAM:
register.html:
<html>
<body bgcolor = "cyan">
<center>
<h1>WELCOME TO REGISTRATION PAGE</h1>
<form action="./registerone" METHOD="post">
Name: <input type="text" name = "name"><br><br>
Password: <input type="password" name="password"><br><br>
PROFESSION:
<select name="profession">
<option value="engineer">ENGINEER</option>
<option value="teacher">TEACHER</option>
<option value="businessman">BUSINESSMAN</option>
</select><br><br>
<input type="submit" value="REGISTER">
</form>
</center>
</body>
</html>
web.xml
<web-app>
<welcome-file-list>
<welcome-file>register.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>RegistrationServletOne</servlet-name>
<servlet-class>RegistrationServletOne</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RegistrationServletOne</servlet-name>
<url-pattern>/registerone</url-pattern>
</servlet-mapping>
<servlet>
RegistrationServletOne.java:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class RegistrationServletOne extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String name = request.getParameter("name");
String password = request.getParameter("password");
String profession = request.getParameter("profession");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body bgcolor = wheat>");
out.println("<center>");
out.println("<h1>COMPLETE THE REGISTRATION</h1>");
out.println("<form action = ./registertwo method = post");
out.println("<input type = hidden name = name value =" + name + ">");
out.println("<input type = hidden name = password value =" + password + ">");
out.println("<input type = hidden name = profession value =" + profession + ">");
out.println("EMAIL ID:<input type =text name = email><br><br>");
out.println("PHONE NO:<input type =text name = cell><br><br>");
out.println("<input type =submit value=registernow>");
out.println("</center>");
out.println("</body></html>");
out.close();
}
}
RegistrationServletTwo.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
OUTPUT:
RESULT:
Thus the Java program for Session Tracking using hidden form fields has been executed successfull
Ex.No:5 ON-LINE EXAMINATION USING SERVLETS
Date:
AIM:
To write java servlet programs to conduct online examination and to display student
mark list available in a database
PROCEDURE:
Client:
1. In index.html on the client side declare the contents that you like to transfer to the server
using html form and input type tags.
2. Create a submit button and close all the included tags.
Server:
1. Import all necessary packages
2. Define a class that extends servlet
3. In the doPost() method, do the following:
Set the content type of the response to "text/html"
Create a writer to the response
Get a paratmeter from the request
If its value is equal to right answer then add 5 to mark variable
Similarly repeat step for all parameters
Display the result in an html format using the writer
Student Mark List Database:
1. Import necessary to java packages and javax packages and classes
2. Create a class that extends HttpServlet and implements ServletException and IOException
3. In the doGet() method, do the following:
Create a PrintWriter object
Open a connection with the data source name
Write a sql query and execute to get the resultset
Display the resultset information in html form
Servlet Code:
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class StudentServlet3 extends HttpServlet
{
String message,Seat_no,Name,ans1,ans2,ans3,ans4,ans5;
int Total=0;
Connection connect;
Statement stmt=null;
ResultSet rs=null;
public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletExcep-
tion,IOException
{
try
{
String url="jdbc:odbc:NEO"; Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
connect=DriverManager.getConnection(url," "," ");
message="Thank you for participating in online Exam";
}
catch(ClassNotFoundException cnfex){ cnfex.printStackTrace();
}
catch(SQLException sqlex){ sqlex.printStackTrace();
}
catch(Exception excp){ excp.printStackTrace();
}
Seat_no=request.getParameter("Seat_no");
Name=request.getParameter("Name");
ans1=request.getParameter("group1");
ans2=request.getParameter("group2");
ans3=request.getParameter("group3");
ans4=request.getParameter("group4");
ans5=request.getParameter("group5");
if(ans1.equals("True"))
Total+=2; if(ans2.equals("False"))
Total+=2; if(ans3.equals("True")) Total+=2;
if(ans4.equals("False")) Total+=2;
if(ans5.equals("False")) Total+=2;
try
{
Statement stmt=connect.createStatement();
String query="INSERT INTOstudent("+"Seat_no,Name,Total"+")
VALUES('"+Seat_no+"','"+Name+"','"+Total+"')";
int result=stmt.executeUpdate(query);
stmt.close();
}catch(SQLException ex){
}
response.setContentType("text/html");
PrintWriter out=response.getWriter(); o
ut.println("<html>");
out.println("<head>");
out.println("</head>");
out.println("<body bgcolor=cyan>");
out.println("<center>");
out.println("<h1>"+message+"</h1>\n");
out.println("<h3>Yours results stored in our database</h3>");
out.print("<br><br>");
out.println("<b>"+"Participants and their Marks"+"</b>");
out.println("<table border=5>"); try
{
Statement stmt=connect.createStatement();
String query="SELECT * FROM student";
rs=stmt.executeQuery(query);
out.println("<th>"+"Seat_no"+"</th>");
out.println("<th>"+"Name"+"</th>");
out.println("<th>"+"Marks"+"</th>");
while(rs.next())
{
out.println("<tr>"); out.print("<td>"+rs.getInt(1)+"</td>");
out.print("<td>"+rs.getString(2)+"</td>"); out.print("<td>"+rs.getString(3)+"</td>");
out.println("</tr>");
}
out.println("</table>");
}
catch(SQLException ex){ } finally
{
try
{
if(rs!=nul) rs.close();
if(stmt!=null) stmt.close();
if(connect!=null)
connect.close();
}
catch(SQLException e){ }
}
out.println("</center>"); out.println("</body></html>"); Total=0;
}}
HTML Code:
<html><head><title>Database Test</title></head> <body>
<center><h1>Online Examination</h1> </center>
<form action="StudentServlet3.view" method="POST">
<div align="left"><br></div>
<b>Seat Number:</b>
<input type="text" name="Seat_no">
<div align="Right">
<b>Name:</b>
<input type="text" name="Name" size="50"><br> </div>
<br><br>
<b>1. Every host implements transport layer.</b><br/>
<input type="radio" name="group1" value="True">True
<input type="radio" name="group1" value="False">False<br>
<b>2. It is a network layer's responsibility to forward packets reliably from source to destina
tion</b><br/>
<input type="radio" name="group2" value="True">True
<input type="radio" name="group2" value="False">False<br>
<b>3. Packet switching is more useful in bursty traffic</b><br/>
<input type="radio" name="group3" value="True">True
<input type="radio" name="group3" value="False">False<br>
<b>4. A phone network uses packet switching</b><br/> <input type="radio" name="group4"
value="True">True
<input type="radio" name="group4" value="False">False<br>
<b>5. HTML is a Protocol for describing web contents</b><br/> <input type="radio"
name="group5" value="True">True
<input type="radio" name="group5" value="False">False<br> <br><br><br>
<center>
<input type="submit" value="Submit"><br><br> </center>
</form></body></html>
OUTPUT:
RESULT:
Thus to write java servlet programs to conduct online examination and to display student mark
list available in a database was successfully executed and verified.
EX.NO:6 CONVERSION OF STATIC WEBPAGES INTO DYNAMIC USING SERVLETS
AIM:
To convert the static web pages into dynamic web pages using servlets (or JSP) and cookies.
PROCEDURE:
We will create ahtml form for entering the user name,password and card ID.
From the above HTML form, the servlet program is invoked in which the validity of the user
name,password and card id is checked.if it is a valid user then the welcome message will be
displayed otherwise the “invalid user” message will be displayed. In this servlet we set the
cookies in which the current user name is stored.
Compile the above servlet Login servlet.java and copy its class file in tomcats folder at c:\
tomcatdirectory\webapps\examples\WEB-INF\classes.
Then edit the web.xml in WEB-INF folder.We must store he user information such as user
name,password and card id in the web.xml using init-param.
On successful login , the information from the cookie is checked and shopping cart page for
corressponding user can be displayed.
Compile the above servlet LoginSuccess.java and copy its class file in the tomcat's folder at c:\
tomcatdirectory\webapps\examples\WEB-INF\classes.
Then edit the web.xml in WEB-INF folder.
Start tomcat web server.Open the web browser and display the login form created in step1.
PROGRAM:
Loginform.html
<!DOCTYPE html>
<html>
<head>
<body>
<form action="http://localhost:8080/shopping/LoginServlet" method="post"> Enter username:
<input type="text" value="" name="User"><br><br> enter password:
<input type="password" value="" name="password"><br><br> enter card ID:
<input type="text" value="" name="CardID"><br><br>
<input type="submit" value="login">
</form>
</body>
</html>
LoginServlet.java package shopping;
import java.io.*; import javax.servlet.*;
import javax.servlet.http.*;
public class LoginServlet extends HttpServlet
{
protected void doPost(HttpServletRequest req, HttpServletResponseres) throws
ServletException,IOException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
String usr=req.getParameter("User";
String pwd=req.getParameter("password");
String card=req.getParameter("CardID");
boolean flag=true;
String[] userID=getInitParameter("usernames").split(",");
String[] password=getInitParameter("passwords").split(",");
String[] cardids=getInitParameter("cardIDs").split(",");
int i; for(i=0;i<userID.length;i++)
{
if(userID[i].equals(usr) && password[i].equals(pwd)&&cardids[i].equals(card))
{
flag=false;
Cookie cookie1=new Cookie("CurrentUser",usr);
Cookie cookie2=new Cookie("CreditCard",card);
res.addCookie(cookie1); res.addCookie(cookie2);
out.println("<h2>Welcome "+usr+"</h2><hr>");
out.println("<h2>Select the book you would like to purchase<h2><hr>");
out.println("<form action='LoginSuccess'>");
out.println("<input type=radio name='book' checked value='Let us C'/>Let us C<br>");
out.println("<input type=radio name='book' value='Exploring Python'/>Exploring Python<br>");
out.println("<input type=radio name='book' value='Mastering C'/>Mastering C <br>");
out.println("<input type=submit value='purchase'><hr>");
}
}
if(flag==true)
{
out.println("<h4>Invalid user name or password or card number,please try again by clicking following
link</h4>");
out.println("<a href='LoginForm.html'>"+"LoginForm.html");
}
}
}
LoginSuccess.Java
package shopping;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class LoginSuccess extends HttpServlet
{
protected void doGet(HttpServletRequest req,HttpServletResponse res) throws
ServletException,IOException
{
Cookie[] mycookie=req.getCookies(); res.setContentType("text/html");
PrintWriter out=res.getWriter();
String book=req.getParameter("book");
out.print("<h2>welcome "+mycookie[0].getValue()+"</h2><hr>"); out.print("<h3>Thank you for
purchasing book:"+book+"</h3><hr>"); out.print("<h3>Rs.250 debited from credit card:
"+mycookie[1].getValue()); out.close();
}
}
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-
app_3_1.xsd">
<servlet>
<init-param>
<param-name>usernames</param-name>
<param-value> indhu,abc,xyz</param-value>
</init-param>
<init-param>
<param-name>passwords</param-name>
<param-value>indhu,abc,xyz</param-value>
</init-param>
<init-param>
<param-name>cardIDs</param-name>
<param-value>111111,222222,333333</param-value>
</init-param>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>shopping.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>LoginSuccess</servlet-name>
<servlet-class>shopping.LoginSuccess</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginSuccess</servlet-name>
<url-pattern>/LoginSuccess</url-pattern>
</servlet-mapping>
</web-app>
RESULT:
Thus the conversion of the static web pages into dynamic web pages using servlets cookies has been
executed successfully.
Ex. No:7 CONVERSION OF STATIC WEBPAGES INTO DYNAMIC USING JSP
AIM:
To convert the static web pages into dynamic web pages using JSP. Create a database with
user
information and books information. The books catalogue should be dynamically loaded from
the
database.
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.
a. Catalina.bat run
b. At install‐dir/bin
5. At I.E give url as http://localhost:8081/tr1/main.html.
PROGRAM :
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()"> <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()">()"> <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()">()"> <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”> <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”> <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>”);%>
RESULT:
The static web pages are converted into dynamic web pages using JSP for book catalogue.
PROGRAM :
index.html:
<!DOCTYPE html>
<HTML>
<HEAD>
<TITLE>Searching for XML Elements </TITLE>
<SCRIPT>
function readXMLData()
{
var xmlDocumentObject, id , name , addr, phone, email;
xmlDocumentObject=new XMLHttpRequest();
xmlDocumentObject.open("GET","userlist.xml",false);
xmlDocumentObject.send();
xmlDocumentObject=xmlDocumentObject.responseXML;
id = xmlDocumentObject.getElementsByTagName("userid");
name = xmlDocumentObject.getElementsByTagName("username");
address = xmlDocumentObject.getElementsByTagName("address");
phone = xmlDocumentObject.getElementsByTagName("phone");
email = xmlDocumentObject.getElementsByTagName("email");
for (i = 0; i < id.length; i++)
{
output=id[i].firstChild.nodeValue;
if (output == document.getElementById("myText").value)
{displayDIV.innerHTML = id[i].firstChild.nodeValue + "<br> " +
name[i].firstChild.nodeValue+"<br> " +address[i].firstChild.nodeValue + "<br> " +
phone[i].firstChild.nodeValue+"<br>"+email[i].firstChild.nodeValue;
}}}
</SCRIPT>
</HEAD>
<BODY>
<H1>Search User</H1>
<input type="text" id="myText" value="">
<input type="BUTTON" VALUE="Get User Details" ONCLICK="readXMLData()">
<P>
<DIV ID="displayDIV"> </DIV>
</BODY>
</HTML>
userlist.xml:
<userlist>
<userid>usr01</userid>
<username>indhu</username>
<address>trichy</address>
<phone>9000000078</phone>
<email>[email protected]</email>
<userid>usr02</userid>
<username>Pooja</username>
<address>chennai</address>
<phone>9111111111</phone>
<email>[email protected]</email>
<userid>usr03</userid>
<username>sadhana</username>
<address>telugana</address>
<phone>9222222222</phone>
<email>[email protected]</email>
<userid>usr04</userid>
<username>sameera</username>
<address>bangalore</address>
<phone>9555555555</phone>
<email>[email protected]</email>
<userid>usr05</userid>
<username>naveena</username>
<address>Perambalur</address>
<phone>9666666666</phone>
<email>[email protected]</email>
</userlist>
RESULT:
Thus the Java Program takes user id as an input and returns the user details by
taking the user information from the XML document has been executed successfully
EX.NO: 9A FORM VALIDATION USING PHP REGULAR EXPRESSION
AIM:
To validate the form using PHP regular expression.
PROCEDURE:
1. Form is created for class registration with fileds.
2. These fields are validated using PHP code.
3. Form is displayed.
PROGRAM:index.php:
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = ""; if
($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-
9+&@#\/%=~_|]/i",$website)) {$websiteErr = "Invalid URL";
}
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["gender"])) {$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data); return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website: <input type="text" name="website" value="<?php echo $website;?>">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"><?php echo
$comment;?></textarea>
<br><br> Gender:
<input type="radio" name="gender" <?php if (isset($gender) &&
$gender=="female") echo "checked";?> value="female">Female
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo
"checked";?> value="male">Male
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="other") echo
"checked";?> value="other">Other
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>"; echo $name;
echo "<br>"; echo $email; echo "<br>"; echo $website; echo "<br>"; echo $comment; echo
"<br>"; echo $gender;
?>
</body>
</html>
OUTPUT:
RESULT:
The form is validated using PHP regular expression.
Ex.No: 9b STORING A FORM DATA IN PHP
Date:
AIM:
To store a PHP form data into database.
PROCEDURE:
1. Form is created with fileds name, mail id, contact and address.
2. Table is created in mysql.
3. The input data entered into the fields are stored using PHP code.
PROGRAM:
index.php:
<!DOCTYPE html>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website =$result= ""; if
($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-
9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "iplab";
$conn = new mysqli($servername, $username, $password, $dbname); if ($conn-
>connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO register (name, email,website,comments,gender) VALUES ('$name',
'$email', '$website','$comment', '$gender')";
if ($conn->query($sql) === TRUE) {
$result="New Record Inserted Successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data); return $data;
}
?>
<h2>Registration Form</h2>
<p><span class="error">* required field</span></p>
<form method="post" action="<?php
echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> Name: <input type="text"
name="name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website: <input type="text" name="website">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br> Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo $result;
?>
</body>
</html>
OUTPUT:
RESULT:
The PHP form data is stored into the database.