0% found this document useful (0 votes)
10 views

Wip Printout

The document describes how to create a web form and invoke a servlet from HTML. It includes the HTML and Java code for a simple form that submits to a servlet. The HTML form uses the GET method and specifies the servlet URL as the action. The servlet code uses annotations to map the URL and extends HttpServlet to process the request.

Uploaded by

ismathkani29
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Wip Printout

The document describes how to create a web form and invoke a servlet from HTML. It includes the HTML and Java code for a simple form that submits to a servlet. The HTML form uses the GET method and specifies the servlet URL as the action. The servlet code uses annotations to map the URL and extends HttpServlet to process the request.

Uploaded by

ismathkani29
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

EX.No.

:1 a ) CREATION OF WEB PAGE USING HTML TAGS

CODE:
<html>
<head>
<title>web Technology</title>
</head>
<marquee bgcolor="yellow" style="color:green; font-size:50px; font-family:times new roman;"
scrollamount="10" height="70px" width="100%"> Webpage </marquee>
<body> <form >
<p style="font-size:20px; font-family:times new roman;"> A web page is a hypertext document
provided by a website and displayed to a user in a web browser. A website typically consists of many
web pages linked together in a coherent fashion. The name "web page" is a metaphor of paper pages
bound together into a book.</p>
<label style="font-size:15px;"><b>Firstname</b></label>
<input type="text" required ><br>
<label style="font-size:15px;"><b>Lastname</b></label>
<input type="text" required ><br>
<button type="button"onclick="alert('hi have a nice day and study well!!!')">Click
here</button></form>
</body> </html>
OUTPUT:
EX.No.:1 b) CREATION OF FORM

CODE:
<html>
<head>
<title>login</title>
</head>
<body>
<form>
<center>
<b><strong> HTML Login page</strong></b>
<fieldset style=width:20%; >
<label>Name</label><input type="text" required><br>
<label>Password</label><input type="password" required><br>
<input type= "submit" value="submit">
<input type ="reset" value="reset">
</fieldset>
</center>
</form>
</body>
<html>
OUTPUT:
EX. No.:2 CREATE A WEB PAGE WITH THE FOLLOWING USING HTML

CODE:
Indiamap.html
<!DOCTYPE html>
<html>
<body>
<h1>The map and area elements</h1>
<p>Click on the Hotspots to go to a new page and read more about the Places:</p>
<img src="india.jpg" alt="Workplace" usemap="#workmap" width="800" height="955">
<map name="workmap">
<area shape="rect" coords="144,209,317,313" alt="delhi" href="delhi.html">
<area shape="rect" coords="481,413,630,490" alt="calcutta" href="calcutta.html">
<area shape="rect" coords="192,747,390,854" alt="tamilnadu" href="tamilnadu.html">
</map>
</body>
</html>
calcutta.html
<html>
<body bgcolor="SKYBLUE">
<font face="Times New Roman" size="10" color="RED">
<center><b><i>Calcutta is the wealthy city in WEST BENGAL<br> and <br>It has Famous
"Sunderbans Forests"</i></b></center>
<a href="Indiamap.html">Home Page</a>
</font>
</body>
</html>
delhi.html
<html>
<body bgcolor="SKYBLUE">
<font face="Arial" size="10" color="RED">
<center><b><i><tt>Delhi is the capital of our INDIA<br> and <br>More IT companies are
Camped at Delhi</tt></i></b></center>
<a href="Indiamap.html">Home Page</a>
</font>
</body>
</html>
tamilnadu.html
<html>
<body bgcolor="cyan">
<font face="Times New Roman" size="10" color="orange">
<center>Chennai is the capital of Tamil Nadu<br> and <br>More IT companies are camped
at Chennai</center>
<a href="Indiamap.html">Home Page</a>
</font>
</body>
</html>
OUTPUT:
EX.No.:3 CREATON OF WEB PAGE USING STYLE SHEETS

Source.html
<html>
<head>
<title>CascadingStyleSheets</title>
</head>
<bodyalink="blue"vlink="purple">
<h1><u><b><font face="Monotype corsiva"
color="red">DifferenttypesofCascadingStyleSheets</font></b></
u></h1>
<br/>
<fontface="Arial"size="6">
<ahref="inline.html"style="text-decoration:none;">1.InlineStyleSheet</a><br/>
<a href ="embedded.html" style="text-decoration :none;"> 2. Embeded
StyleSheet</a><br/>
<a href ="external.html" style="text-decoration :none;"> 3. External
StyleSheet</a><br/>
<ahref="error.html"style="text-decoration:none;">4.ErrorStyleSheet</a><br/></font>
</body>
</html>

Inline.html:
<html>
<head>
<title>inline</title>
</head>
<body>
<h1 style="font-family:MonotypeCorsiva ;
background-color:antiquewhite;">studentinfo</h1>
<h3>
<p style="text-indent :30pt;color:blue;font-family :arial;">

In ourdepartmentthe secondyearstrength is 60.


</p></h3>
</body>
</html>
Embedded.html
<html>
<head>
<title>Embeded/internalStyleSheet</title>
<styletype="text/css">
h1{text-align:left;
background:antiquewhite;
font-family:monotypecorsiva;
color:red}
p{
font-size:20px;
text-align:justify;
font-family:arial;
color:blue}
</style>
</head>
<body>
<h1>Facilities</h1>
<br/><p>
ourdepartmentprovidedgoodlaboratoryforlabexperiments.
</p>
</body>
</html>

External.html:
<html>
<head>
<title>ExternalStyleSheet</title>
<linkrel=Stylesheethref="style1.css"type="text/css"/>
</head>
<body>
<h1>Events</h1><br/>
<p>
Variouseventsconductedinourdepartmentlikeonlinequizcompetition. Thestudents
participatedinthe eventvoluntarily
</p>
</body>
</html>

Style.css:
h1{color:blue;
font-family:Monotype
Corsiva;font-size:40px;
background-color:antiquewhite;
}
p
{
color:red;
font-family:Time new
roman;font-size:30px;
text-indent:30pt;
}
OUTPUT:
EX.No.:4 VALIDATE THE EMAIL ID, PHONE NUMBER AND PASSWORD
WHILE ENTERING THE INFORMATION OF A STUDENT USING
JAVASCRIPT

CODE:

Index.html:

<html>

<head>

<linkhref="app.css"rel="stylesheet"/>

</head>

<body>

<divclass="container">

<divclass="header">

<h2>CreateUser</h2>

</div>

<formclass="form">

<divclass="form-control">

<lablefor="username"name="username">UserName</lable>

<inputid="txtUserName"type="text"name="username"/>

<small>ErrorMessage</small>

</div>

<divclass="form-control">

<lablefor="email"name="email">Email</lable>

<inputid="txtEmail"type="email"name="email"/>

<small>ErrorMessage</small>

</div>
<divclass="form-control">

<lablefor="phoneno"name="email">phoneno</lable>
<inputid="txtphoneno"type="phoneno"name="phoneno"/>

<small>ErrorMessage</small>

</div>

<divclass="form-control">

<lablefor="pwd"name="pwd">Password</lable>

<inputid="txtPwd"type="password"name="pwd"/>

<small>ErrorMessage</small>

</div>

<divclass="form-control">

<lablefor="conpwd"name="conpwd">ConfirmPassword</lable>

<inputid="txtConPwd"type="password"name="conpwd"/>

<small>ErrorMessage</small>

</div>

<divclass="form-control">

<button>Register</button>

</div>

</form>

</div>

<scriptsrc="app.js"></script>

</body>

</html>

app.css

*{
box-sizing:border-box;
}

body{

background-color: rgb(4,4,95);

display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
margin:0;
}
.container{width:400px;
background-color: #fff;
border-radius: 4px;
overflow: hidden;
}

.header{

background-color: #d8d1d1;padding:10px20px;
}

.form{

padding:20px40px;

}
.form-control{

margin-bottom:10px;

padding-bottom: 10px;
position:relative;
}

. form-control lable {display: inline-block;

margin-bottom:5px;
}

. form-control input{display: block;


width: 100%;padding: 10px;

border-radius:4px;
border:2pxsolid#d8d1d1;

}
form-control.success input{border:2pxsolidrgb(26,167,26);
}

. form-control.error input{border:2pxsolidrgb(228,29,22);
}

form-control small{position:absolute;

margin: 3px;

visibility:hidden

button{

background-color: rgb(4,4,95);color:#fff;
padding: 10px
20px;width:
100%;border-
radius:4px;
border:2px solid
rgb(4,4,95);cursor:point
er;
}
app.js:

letuserName=document.getElementById("txtUserName")
;letemail=document.getElementById("txtEmail");
let
phoneno=document.getElementById("txtphoneno");letpwd=do
cument.getElementById("txtPwd");
letconPwd=document.getElementById("txtConPwd");letform=docume
nt.querySelector("form");
functionvalidateInput(){

//check username is
emptyif(userName.value.trim
()=""){
onError(userName,"UserNamecannotbeempty");

}else{

onSuccess(userName);
}

if(email.value.trim()==="")
{onError(email,"Emailcannotbeempty");
}else{

if(!isValidEmail(email.value.trim()))
{onError(email,"Emailisnotvalid");
}else{

onSuccess(email);

//
phonenoif(phoneno.value.t
rim()="){
onError(phoneno,"phonenocannotbeempty");

}else{

if(!isValidphoneno(phoneno.value.trim()))
{onError(phoneno,"phonenumbershouldbe10digit");
}else{

onSuccess(phoneno);

}
}

//
passwordif(pwd.value.
trim()="){
onError(pwd,"UserNamecannotbeempty");

}else{

onSuccess(pwd);
}

if(conPwd.value.trim()==="")
{onError(conPwd,"UserNamecannotbeempty");
}else{

if(pwd.value.trim()!==conPwd.value.trim())
{onError(conPwd,"Password&Confirmpasswordnotmatching");
}

elseonSuccess(conPwd);
}

document.querySelector("button")

. addEventListener("click",
(event)=>{event.preventDefault();validateInput();
});

functiononSuccess(input){

letparent=input.parentElement;

letmessageEle=parent.querySelector("small")
;messageEle.style.visibility="hidden";parent.
classList.remove("error");parent.classList.ad
d("success");
}
function onError(input,message)
{letparent=input.parentElement;
letmessageEle=parent.querySelector("small");message
Ele.style.visibility="visible";messageEle.innerText=me
ssage;parent.classList.add("error");parent.classList.rem
ove("success");
}functionisValidEmail(email){

return/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.
[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-
Z]{2,}))$/.test(email);}

function isValidphoneno(phoneno)
{return/^\d{10}$/.test(phoneno);
}

OUTPUT:
EX.No.:5 a INVOKING SERVLETS FROM HTML FORMS

CODE:
index.html:
<html>
<head>
<title>Invoking Servlet from HTML</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form method="get" action="http://localhost:8080/WebApplication1/NewServlet">
<input type="submit" value="Invoke Servlet">
</form>
</body>
</html>

NewServlet.java:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(urlPatterns = {"/NewServlet"})
public class NewServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title> Hi this is NewServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h3>This is servelt page</h3>") ;
out.println("</body>");
out.println("</html>");
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

OUTPUT:

}
EX.No.:5b SESSION TRACKING USING HIDDEN FORM FIELDS AND
SESSION TRACKING FOR A HIT COUNT

CODE:
index.html:
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="http://localhost:8080/WebApplication1/FirstServlet">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
</body>
</html>

FirstServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(urlPatterns = {"/FirstServlet"})
public class FirstServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
String n=request.getParameter("userName");
out.print("Welcome "+n);
out.print("<form action='http://localhost:8080/WebApplication1/SecondServlet'>");
out.print("<input type='hidden' name='uname' value='"+n+"'>");
out.print("<input type='submit' value='go'>");
out.print("</form>");
out.close();
} }
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
public String getServletInfo() {
return "Short description";
}}
SecondServlet.java:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(urlPatterns = {"/SecondServlet"})
public class SecondServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
String n=request.getParameter("uname");
out.print("Hello "+n);

out.close();
}
} @Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}@Override
public String getServletInfo() {
return "Short description"; }}

output :
Session tracking for hit count:
CODE:

hitcount.java
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class hitcount extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
// Get the current session object, create one if necessary
HttpSession session = req.getSession();
// Increment the hit count for this page. The value is saved
// in this client's session under the name "tracker.count".
Integer count = (Integer)session.getAttribute("tracker.count");
if (count == null)
count = new Integer(1);
else
count = new Integer(count.intValue() + 1);
session.setAttribute("tracker.count", count);
out.println("<HTML><HEAD><TITLE>SessionTracker</TITLE></HEAD>");
out.println("<BODY><H1>Session Tracking Demo</H1>");
// Display the hit count for this page
out.println("You've visited this page " + count +
((count.intValue() == 1) ? " time." : " times."));
out.println("<P>");
out.println("<H2>Here is your session data:</H2>");
Enumeration enam = session.getAttributeNames();
while (enam.hasMoreElements()) {
String name = (String) enam.nextElement();
out.println(name + ": " + session.getAttribute(name) + "<BR>");
}
out.println("</BODY></HTML>");
}
}

OUTPUT:
EX.No.:6 CREATION OF THREE-TIER APPLICATION

TO CONDUCT ONLINE EXAMINATION


CODE:
Login.html
<html>
<head>
<title>exam portal</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div style="text-align: center">
<h3> ONLINE EXAM PORTAL-LOGIN </h3>
<hr>
<form method ="get" action="acceptuser.jsp">
Username <input type="text" name="uname" value=""><br><br>
Password <input type="password" name="pass" value=""><br>
<button type="submit">LOGIN </button>
</form>
</div>
</body>
</html>

acceptuser.jsp
<%@ page import="java.sql.*"%>
<%@ page import="java.util.*"%>
<%!
Connection con;
PreparedStatement ps1, ps2;
public void jspInit()
{
try
{
//loading the driver
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
//establish the connection
con = DriverManager.getConnection("jdbc:derby://localhost:1527/iplab2","root","root");
//create statement object
ps1 = con.prepareStatement("select count(*) from users where username = ? and
password=?");
ps2 = con.prepareStatement("select * from users");
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
%>
<%
String param = request.getParameter("s1");
if(param =="link")
{
ResultSet rs = ps2.executeQuery();
out.println("<table>");
while(rs.next())
{
out.println("<tr>");
out.println("<td>"+rs.getString(1)+"</td>");
out.println("<td>"+rs.getString(2)+"</td");
out.println("</tr>");
}
out.println("</table>");
rs.close();
}
else
{
//write jdbc code for authentication
String user = request.getParameter("uname");
String pass = request.getParameter("pass");
//set form data as param value
ps1.setString(1,user);
ps1.setString(2,pass);
//excute the query
ResultSet rs = ps1.executeQuery();
int cnt = 0;
if (rs.next())
cnt = rs.getInt(1);
if(cnt == 0)
out.println("<b><i><font color=red>Invalid credential</fonr></i></b>");
else
{
out.println("<form><fieldset style= width:25%; >");
out.println("<b><i><font color=red>valid credential..</font></i></b><br>");
out.println("<b><i><a href=examclient.html><font size=6 color=blue>Click Here to take
test</font></i></a></b>");
out.println("</fieldset></form>");
}
}
%>
<%!
public void jspDestroy()
{
try
{
//colse
ps1.close();
ps2.close();
con.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
%>

Examclient.html
<html>
<head>
<title>Online Exam Client</title>
</head>
<body>
<h2 style="text-align:center">ONLINE EXAMINATION</h2>
<h3>Answer the following questions (5 marks for each correct answer)</h3>
<hr/>
<form name="examForm" method="post" action="ExamServer.jsp">
1.Who is called as the father of computer?<br/>
<input type="radio" name="ans1" value="Sachin">Sachin
<input type="radio" name="ans1" value="Stuart">Stuart
<input type="radio" name="ans1" value="Charles Babbage">Charles Babbage
<input type="radio" name="ans1" value="Napier">Napier
<br/><br/>
2.C++ was developed by?<br/>
<input type="radio" name="ans2" value="Dennis Ritchie">Dennis Ritchie
<input type="radio" name="ans2" value="None">None
<input type="radio" name="ans2" value="David Ritchie">David Ritchie
<input type="radio" name="ans2" value="John">John
<br/><br/>
3.C was developed by?<br/>
<input type="radio" name="ans3" value="Dennis Ritchie">Dennis Ritchie
<input type="radio" name="ans3" value="Stroustrup">Stroustrup
<input type="radio" name="ans3" value="David Ritchie">David Ritchie
<input type="radio" name="ans3" value="Charles Babbage">Charles Babbage
<br/><br/>
<input type="submit" value="Check Your Result"/>
</form>
</body>
</html>

Examserver.jsp
<%@page contentType="text/html" language="java" import="java.sql.*"%>
<html>
<head>
<title>Online Exam Server</title>
<style type="text/css">
body{background-color:white;font-family:courier;color:blue}
</style>
</head>
<body>
<h2 style="text-align:center">ONLINE EXAMINATION</h2>
<p>
<a href="ExamClient.html">Back To Main Page</a>
</p>
<hr/>
<%
String str1=request.getParameter("ans1");
String str2=request.getParameter("ans2");
String str3=request.getParameter("ans3");
int mark=0;
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
Connection
con=DriverManager.getConnection("jdbc:derby://localhost:1527/iplab2","root","");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("SELECT * FROM examTab");
int i=1;
while(rs.next())
{
if(i==1)
{
String dbans1=rs.getString(1);
if(str1.equals(dbans1))
{
mark=mark+5;
}
}
if(i==2)
{
String dbans2=rs.getString(1);
if(str2.equals(dbans2))
{
mark=mark+5;
}
}
if(i==3)
{
String dbans3=rs.getString(1);
if(str3.equals(dbans3))
{
mark=mark+5;
}
}
i++;
}
if(mark>=10)
{
out.println("<h4>Your Mark Is : "+mark+"</h4>");
out.println("<h3>Congratulations....! You Are Eligible For The Next Round...</h3>");
}
else{
out.println("<h4>Your Mark is : "+mark+"</h4>");
out.println("<h3>Sorry....!! You Are Not Eligible For The Next Round...</h3>");
}
%></form></body></html>

OUTPUT:
EX.No.:7 DYNAMIC WEBPAGE FOR SHOPPING CART
CODE:
ShoppingCart.java:

import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.util.Enumeration;
import javax.servlet.annotation.WebServlet;
@WebServlet(urlPatterns = {"/ShoppingCart"})
public class ShoppingCart extends HttpServlet {
String [] items = new String [] {
"Samsung A30", "MI 108 CM Android TV",
"HP USB Pend Drive 32GB", "DELL Core i5, 8GB RAM, 1TB HDD Laptop" };
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<center><h3>ABC SHOPPING CART </h3></center>");
out.println("<hr>");
// get or create the session information
HttpSession session = request.getSession();
int [] purchases = (int [])session.getAttribute("purchases");
if ( purchases == null ) {
purchases = new int [ items.length ];
session.setAttribute( "purchases", purchases );
}
out.println( "<html><head><title>Shopping Cart</title>"
+ "</title></head><body><p>" );
if ( request.getParameter("checkout") != null )
out.println("<h1>Thanks for ordering!</h1>");
else {
if ( request.getParameter("add") != null ) {
addPurchases( request, purchases );
out.println(
"<h1>Purchase added. Please continue</h1>");
} else {
if ( request.getParameter("clear") != null )
for (int i=0; i<purchases.length; i++)
purchases[i] = 0;
out.println("<h1> Please Select Your Items! </h1>");
}
doForm( out, request.getRequestURI() );
}
showPurchases( out, purchases );
out.close();
}
void addPurchases( HttpServletRequest request, int [] purchases ) {
for (int i=0; i<items.length; i++) {
String added = request.getParameter( items[i] );
if ( added !=null && !added.equals("") )
purchases[i] += Integer.parseInt( added );
}
}
void doForm( PrintWriter out, String requestURI ) {
out.println( "<form method=POST action="+ requestURI +">" );
for(int i=0;i< items.length;i++)
out.println( "Quantity <input name=\"" + items[i]+ "\" value=0 size=3> of: " + items[i] +
"<br>");
out.println(
"<p><input type=submit name=add value=\"Add To Cart\">"
+ "<input type=submit name=checkout value=\"Check Out\">"
+ "<input type=submit name=clear value=\"Clear Cart\">"
+ "</form>");
}
void showPurchases( PrintWriter out, int [] purchases )
throws IOException {
out.println("<hr><h2>Your Shopping Basket</h2>");
for (int i=0; i<items.length; i++)
if ( purchases[i] != 0 )
out.println( purchases[i] +""+ items[i] +"<br>" );
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
public String getServletInfo() {
return "Short description";}}

OUTPUT:
EX.No.:8 DYNAMIC WEBPAGES USING JSP

CODE:
<html>
<head>
<title>Book Catalogue</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h3>ABC Book Store </h3>
<hr>
<a href="http://localhost:8080/WebApplication2/bookdisplay.jsp"> View All Books
</a><BR>
<TABLE>
<TR>
<TD><FORM ACTION="http://localhost:8080/WebApplication2/booksearch.jsp"
method="get">
Enter the Book title to search <input type="text" name ="bname" value="">
<button type="submit">Search</button></TD>
</TR>
</TABLE>
</body>
</html>

Bookdisplay.jsp:
<%@ page import="java.sql.*" %>
<%@ page import="java.io.*" %>
<html>
<head>
<title>display data from the table using jsp</title>
</head>
<body>
<h2>Book Catalog</h2>
<%
try {
Connection connection = null;
Statement statement = null;
ResultSet rs = null;
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
connection = DriverManager.getConnection("jdbc:derby://localhost:1527/iplab1", "root",
"root");
statement = connection.createStatement();
String QueryString = "SELECT * from bookdb";
rs = statement.executeQuery(QueryString);
%>
<TABLE cellpadding="15" border="1" style="background-color: #ffffcc;">
<%
while (rs.next()) {
%>
<TR>
<TD><%=rs.getInt(1)%></TD>
<TD><%=rs.getString(2)%></TD>
<TD><%=rs.getString(3)%></TD>
<TD><%=rs.getString(4)%></TD>
<TD><%=rs.getString(5)%></TD>
</TR>
<% } %>
<%
rs.close();
statement.close();
connection.close();
} catch (Exception ex) {
%>
</font>
<font size="+3" color="red"></b>
<%
out.println("Unable to connect to database.");
}
%>
</TABLE><TABLE>
<TR>
<TD><FORM ACTION="index.html" method="get">
<button type="submit"><-- back</button></TD>
</TR>
</TABLE>
</font>
</body>
</html>

Booksearch.jsp:
<%@ page import="java.sql.*" %>
<%@ page import="java.io.*" %>
<html>
<head>
<title>display data from the table using jsp</title>
</head>
<body>
<h2>Book Catalog</h2>
<%
try {
String connectionURL = "jdbc:derby://localhost:1527/iplab1";
Connection connection = null;
Statement statement = null;
ResultSet rs = null;
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
connection = DriverManager.getConnection(connectionURL, "root", "root");
statement = connection.createStatement();
String ss= request.getParameter("bname");
String QueryString = "SELECT * from bookdb where bname like '"+ss+"%'";
rs = statement.executeQuery(QueryString);
%>
<TABLE cellpadding="15" border="1" style="background-color: #ffffcc;">
<%
while (rs.next()) {
%>
<TR>
<TD><%=rs.getInt(1)%></TD>
<TD><%=rs.getString(2)%></TD>
<TD><%=rs.getString(3)%></TD>
<TD><%=rs.getString(4)%></TD>
<TD><%=rs.getString(5)%></TD>
</TR>
<% } %>
<%
rs.close();
statement.close();
connection.close();
} catch (Exception ex) {
%>
</font>
<font size="+3" color="red"></b>
<%
out.println(ex);
}
%>
</TABLE><TABLE>
<TR>
<TD><FORM ACTION="index.html" method="get">
<button type="submit"><--back</button></TD>
</TR>
</TABLE>
</font>
</body>
</html>
OUTPUT:
EX.No.:9 XML DOCUMENT TO STORE INFORMATION OF 10 USERS

CODE:
index.html:
<HTML>
<HEAD>
<TITLE>Searching for XML Elements </TITLE>
<SCRIPT>
function readXMLData()
{
var xmlDocumentObject, id , name , address, 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>Sathishkumar</username>
<address>Erode</address>
<phone>9213454567</phone>
<email>[email protected]</email>
<userid>usr02</userid>
<username>Praveen</username>
<address>Erode</address>
<phone>9994244540</phone>
<email>[email protected]</email>
<userid>usr03</userid>
<username>sadhik</username>
<address>Erode</address>
<phone>9994244542</phone>
<email>[email protected]</email>
<userid>usr04</userid>
<username>ssathish</username>
<address>Dharmapurai</address>
<phone>9835994445</phone>
<email>[email protected]</email>
<userid>usr05</userid>
<username>naveen</username>
<address>Perundurai</address>
<phone>968877555</phone>
<email>[email protected]</email>
</userlist>
OUTPUT:
EX.No.:10 (i)VALIDATE THE FORM USING PHP REGULAR EXPRESSION.

(ii)USING PHP TO STORE A FORM DATA INTO DATABASE

CODE:
i. Validate the form using PHP regular expression

index.php:
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$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"]);
// check if name only contains letters and whitespace
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"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}

if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
// check if URL address syntax is valid
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>Form Validation using Regular Epression</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>
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>
<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:

(ii) PHP stores a form data into database


index.php:
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$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"]);
// check if name only contains letters and whitespace
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"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}

if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
// check if URL address syntax is valid
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";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
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>
E-mail: <input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br>
Website: <input type="text" name="website">
<span class="error"><?php echo $websiteErr;?></span>
<br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<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>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo $result;
?>
</body>
</html>
OUTPUT:

You might also like