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

Wip Printout Final

The document describes how to invoke servlets from HTML forms. It provides an example HTML page with a form that submits to a servlet. It also includes the Java code for a simple servlet that handles the form submission and response.

Uploaded by

jeevadon007007
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 Final

The document describes how to invoke servlets from HTML forms. It provides an example HTML page with a form that submits to a servlet. It also includes the Java code for a simple servlet that handles the form submission and response.

Uploaded by

jeevadon007007
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/ 50

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 HTM L FORM S

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:

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;
import javax.servlet.http.HttpSession;
@WebServlet("/SessionCounter")
public class Hitcount extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
PrintWriter out = response.getWriter();
HttpSession session = request.getSession();
Integer count = (Integer) session.getAttribute("visitCount");
if (count == null) {
count = 1;
} else {
count++;
}
session.setAttribute("visitCount", count);
out.println("<h1>Session Tracking Example</h1>");
out.println("<p>You have visited this page " + count + " times.</p>");
out.println("</body></html>");
}
}
OUTPUT:
EX.No.:6 CREATION OF THREE-TIER APPLICATION
TO CONDUCT ONLINE EXAMINATION
CODE:

Index.htlml:
<html>
<head>
<title>Exam Portal Login</title>
</head>
<body>
<div style="text-align: center">
<h3> ONLINE EXAM PORTAL - LOGIN </h3>
<hr>
<form method="post" action="Acceptuser">
Username: <input type="text" name="uname" value=""><br><br>
Password: <input type="password" name="pass" value=""><br><br>
<button type="submit">LOGIN</button>
</form>
</div>
</body>
</html>

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"> 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>

Acceptuser.java

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
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("/Acceptuser")
public class Acceptuser extends HttpServlet {
// private static final long serialVersionUID = 1L;
private Connection con;
private PreparedStatement ps;
public void init() throws ServletException {
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
con = DriverManager.getConnection("jdbc:derby://localhost:1527/six", "root", "root");
ps = con.prepareStatement("SELECT COUNT(*) FROM users WHERE username = ? AND
password = ?");
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void destroy() {
try {
ps.close();
con.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}

protected void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
PrintWriter out = response.getWriter();
String username = request.getParameter("uname");
String password = request.getParameter("pass");
try {
ps.setString(1, username);
ps.setString(2, password);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
int count = rs.getInt(1);
if (count > 0) {
out.println("<b><i><font color='green'>Valid credentials.</font></i></b><br>");
out.println("<a href='examclient.html'><font size='6' color='blue'>Click Here to take
test</font></a>");
} else {
// Invalid credentials
out.println("Invalid credentials");
}
}
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

ExamServer.java
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
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("/Examserver")
public class Examserver extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException,
IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String str1 = request.getParameter("ans1");
String str2 = request.getParameter("ans2");
String str3 = request.getParameter("ans3");
int mark = 0;
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
con = DriverManager.getConnection("jdbc:derby://localhost:1527/six", "root", "root");
stmt = con.createStatement();
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++;
}
out.println("<html>");
out.println("<head>");
out.println("<title>Online Exam Result</title>");
out.println("</head>");
out.println("<body>");
out.println("<h2>ONLINE EXAMINATION</h2>");
out.println("<hr/>");
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>");
}
out.println("</body>");
out.println("</html>");
}
catch (Exception e) {
out.println("<html><body><h3>Error processing the request. Please try again
later.</h3></body></html>");
e.printStackTrace();
} finally {
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (con != null) con.close();
} catch (SQLException e) {
e.printStackTrace();

}
}
}
}
OUTPUT:
EX.No.:7 DYNAM IC 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 DYNAM IC 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.js p:
<%@ 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 XM L DOCUM ENT TO STORE INFORM ATION 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

Reg.html:

<html>
<body>
<form action="reg.php" method="post">
<label for="email">Email:</label><br>
<input type="text" id="email" name="email"><br>
<label for="phone">Phone:</label><br>
<input type="text" id="phone" name="phone"><br>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

Reg.php:

<?php
function validateEmail($email) {
return filter_var($email, FILTER_VALIDATE_EMAIL);
}
function validatePhone($phone) {
$phone = preg_replace('/\D/', '', $phone);
return strlen($phone) === 10 && is_numeric($phone);
}
function validatePassword($password) {
return strlen($password) >= 8;
}
$email = $_POST['email'];
$phone = $_POST['phone'];
$password = $_POST['password'];
if (!validateEmail($email)) {
echo 'Please enter a valid email address';
} elseif (!validatePhone($phone)) {
echo 'Please enter a valid 10-digit phone number';
} elseif (!validatePassword($password)) {
echo 'Password must be at least 8 characters long';
}
else
{
echo 'Form validated successfully!';

}
?>

OUTPUT:
(ii) PHP stores a form data into database
Connect.php
<?php
$host="localhost:3306";
$user="root";
$pass="";
$con=mysqli_connect($host,$user,$pass);
if(!$con)
{
echo"not conected".mysqli_error();
}
else
{
echo"connected";
}
mysqli_close($con);
?>

Dbconnect.php:
<?php
$host="localhost:3306";
$user="root";
$pass="";
$db="demo";
$con=mysqli_connect($host,$user,$pass,$db);
if(!$con)
{
echo"db not conected".mysqli_error();
}
else
{
echo"db connected";
}
mysqli_close($con);
?>
Insert.html:
<html>
<body>
<form action="finsert.php" method="post">
<label for="email">Email:</label><br>
<input type="text" id="email" name="email"><br>
<label for="phone">Phone:</label><br>
<input type="text" id="phone" name="phone"><br>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

finsert.php:

<?php
$host="localhost:3306";
$user="root";
$pass="";
$db="demo";
$con=mysqli_connect($host,$user,$pass,$db);
if(!$con)
{
echo"not connected";
}
else
{
echo" connected";
}
$email = $_POST['email'];
$phone = $_POST['phone'];
$password = $_POST['password'];
$sql="INSERT INTO email(EMAIL,PHONE,PASSWORD)VALUES('$email','$phone','password')";
if(mysqli_query($con,$sql))
{
echo"inserted";
}
else
{
echo" not inserted";
}
?>
OUTPUT:

You might also like