Web Technologies Lab Manual R13 JNTUA
1. Write a java Program which stores the
user login information in database in a server, creates user interface for
inserting, deleting, retrieving information from the database accepts user
login information and verifies it.
Source Code
import java.sql.*;
public class
AccessDBEx{
private static Connection con = null;
public static void main(String[] args){
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con =
DriverManager.getConnection("jdbc:odbc:student");
if(con!=null){
Statement stm =
con.createStatement();
//create statement is used to
create a table
stm.execute("create table
studentdata ( roll_no number, name varchar(20), address varchar(30) )");
//insert statement is used to
insert new record into a table
stm.execute("insert into
studentdata values(01,'Bharath Kuamr','Tirupati')");
stm.execute("insert into
studentdata values(02,'Rama','srikalahasti')");
stm.execute("insert into
studentdata values(03,'Samba','Gudur')");
stm.execute("insert into studentdata
values(04,'siddaiah','Nellore')");
stm.execute("insert into
studentdata values(05,'Sravan Kumar','Bangaluru')");
//update statement is used to update
existing records in a table
stm.execute("update studentdata
set name='dass', address='skht' where roll_no=01");
//select statement is used to
retrieve record from table
stm.execute("select * from
studentdata");
ResultSet rs = stm.getResultSet();
if (rs != null){
while ( rs.next() ){
System.out.println("========================================"
);
System.out.println("Roll Number : " + rs.getString(1) );
System.out.println("Name : " + rs.getString(2) );
System.out.println("Address : " + rs.getString(3) );
System.out.println("========================================"
);
}
}
// delete statement is used to delete
record from table
stm.execute("delete * from
studentdata where roll_no=1");
}
con.close();
} catch (Exception
e) {
e.printStackTrace();
}
}
}
C:\>javac AccessDBEx.java
C:\>java AccessDBEx
========================================
Roll Number : 1.0
Name : dass
Address : skht
========================================
========================================
Roll Number : 2.0
Name : Rama
Address : srikalahasti
========================================
========================================
Roll Number : 3.0
Name : Samba
Address : Gudur
========================================
========================================
Roll Number : 4.0
Name : siddaiah
Address : Nellore
========================================
========================================
Roll Number : 5.0
Name : Sravan Kumar
Address : Bangaluru
========================================
C:\>
2.
Write a java Program which establish a connection between client and severand
transfers data. Transfers the data without establishing a connection
Source Code
import java.io.*;
import java.net.*;
public class
TCPFactClient
{
public static void
main(String args[])throws Exception
{
String fact;
//create a socket
to the server
Socket soc=new
Socket("localhost",6789);
System.out.println("Connected
to localhost at port 6789");
//get streams
PrintWriter ts=new
PrintWriter(soc.getOutputStream(),true);
BufferedReader
fs=new BufferedReader(new InputStreamReader(soc.getInputStream()));
BufferedReader
fu=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter
an integer:");
String
n=fu.readLine();
ts.println(n);
System.out.println("sent
to server"+n);
fact=fs.readLine();
System.out.println("Received
from Server"+fact);
soc.close();
}
}
import java.io.*;
import java.net.*;
public class
TCPFactServer
{
public static void
main(String args[])throws Exception
{
ServerSocket ss=new
ServerSocket(6789);
System.out.println("Server
is listening on port 6789");
Socket
s=ss.accept();
System.out.println("Request
accepted");
BufferedReader
fc=new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter tc=new
PrintWriter(s.getOutputStream(),true);
int
n=Integer.parseInt(fc.readLine());
System.out.println("Received
from client "+n);
int fact=1;
for (int
i=2;i<=n;i++)
{
fact*=i;
}
tc.println(fact);
System.out.println("sent
to client"+fact);
s.close();
}
}
/*C:\>javac TCPFactClient.java
C:\>java TCPFactClient
Connected to localhost at port 6789
Enter an integer:
5
sent to server5
Received from Server120
C:\>*/
C:\>javac TCPFactServer.java
C:\>java TCPFactServer
Server is listening on port 6789
Request accepted
Received from client 5
sent to client120
C:\>*/
import java.io.*;
import java.net.*;
public class
TCPMTFactClient
{
public static void
main(String args[])throws Exception
{
String
sentence,modifiedSentence,fact;
//create a socket
to the server
Socket soc=new
Socket("localhost",6789);
System.out.println("Connected
to localhost at port 6789");
//get streams
PrintWriter ts=new
PrintWriter(soc.getOutputStream(),true);
BufferedReader
fs=new BufferedReader(new InputStreamReader(soc.getInputStream()));
BufferedReader
fu=new BufferedReader(new InputStreamReader(System.in));
while(true)
{
System.out.println("Enter
an integer:");
String
n=fu.readLine();
ts.println(n);
System.out.println("sent
to server"+n);
if
(n.equals("-1"))
break;
fact=fs.readLine();
System.out.println("Received
from Server"+fact);
}
soc.close();
}
}
import java.io.*;
import java.net.*;
public class
TCPMTFactServer
{
public static void
main(String args[])throws Exception
{
int n,fact=1;
ServerSocket ss=new
ServerSocket(6789);
System.out.println("Server
ready");
while(true)
{
Socket s=ss.accept();
System.out.println("Request
accepted");
new Handler(s);
}
}
}
class Handler
implements Runnable
{
Socket s;
Handler(Socket s)
{
this.s=s;
new
Thread(this).start();
System.out.println("
A Thread creates");
}
public void run()
{
try{
while(true)
{
BufferedReader
fc=new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter tc=new
PrintWriter(s.getOutputStream(),true);
int fact=1;
int
n=Integer.parseInt(fc.readLine());
System.out.println("Received
from client "+n);
if(n==-1)
{
s.close();
break;
}
for (int
i=2;i<=n;i++)
fact*=i;
tc.println(fact);
System.out.println("sent
"+fact);
}
}
catch(IOException
e)
{
}
}
}
C:\>javac TCPMTFactClient.java
C:\>java TCPMTFactClient
Connected to localhost at port 6789
Enter an integer:
4
sent to server4
Received from Server24
Enter an integer:
5
sent to server5
Received from Server120
Enter an integer:
6
sent to server6
Received from Server720
Enter an integer:
-1
sent to server-1
C:\>
C:\>javac TCPMTFactServer.java
C:\>java TCPMTFactServer
Server ready
Request accepted
A Thread creates
Received from client 4
sent 24
Received from client 5
sent 120
Received from client 6
sent 720
Received from client -1
C:\>
3.Write a java program to create
an employee class with the data members Emp_id, name, Department and create
member function to get the employee information ,display the details.
Source Code
import java.io.*;
class Employee
{
int id;
String name;
int age;
long salary;
void getData()throws IOException // Defining GetData()
{
BufferedReader br=new
BufferedReader(new InputStreamReader(System.in));
System.out.print("\n\t Give
Employee information");
System.out.print("\n\tEnter
Employee Id : ");
id =
Integer.parseInt(br.readLine());
System.out.print("\n\tEnter
Employee Name : ");
name = br.readLine();
System.out.print("\n\tEnter
Employee Age : ");
age = Integer.parseInt(br.readLine());
System.out.print("\n\tEnter
Employee Salary : ");
salary =
Integer.parseInt(br.readLine());
}
void putData() // Defining PutData()
{
System.out.print("Display:");
System.out.print("\n\tEmployee Id
: "+id);
System.out.print("\n\tEmployee
Name : "+name);
System.out.print("\n\tEmployee Age
: "+age);
System.out.print("\n\tEmployee
Salary : "+salary);
}
public static void main(String
args[])throws IOException
{
Employee e = new Employee();//
Creating Object
e.getData(); // Calling GetData()
e.putData(); // Calling PutData()
}
}
/*C:\>java Employee
Give Employee
information
Enter Employee Id : 504
Enter Employee Name :
siddaiah
Enter Employee Age : 34
Enter Employee Salary :
18000
Display:
Employee Id : 504
Employee Name : siddaiah
Employee Age : 34
Employee Salary : 18000*/
4.Write
a java program to create a package for simple arithmetic operations
Source
Code
package arithmetic;
public class MyMath
{
public int add(int x,int y)
{
return x+y;
}
public int sub(int x,int y)
{
return x-y;
}
public int mul(int x,int y)
{
return x*y;
}
public double div(int x,int y)
{
return (double)x/y;
}
public int mod(int x,int y)
{
return x%y;
}
}
import arithmetic.MyMath;
import java.io.*;
class TestDynamic
{
public static void main(String as[])throws
IOException
{
MyMath m=new MyMath();
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter the value for
A");
int
a=Integer.parseInt(br.readLine());
System.out.println("Enter the value for
A");
int
b=Integer.parseInt(br.readLine());
System.out.println(m.add(a,b));
System.out.println(m.sub(a,b));
System.out.println(m.mul(a,b));
System.out.println(m.div(a,b));
System.out.println(m.mod(a,b));
}
}
/*D:\webtech>javac TestDynamic.java
D:\webtech>java TestDynamic
Enter the value for A
8
Enter the value for A
5
13
3
40
1.6
3
D:\webtech>java TestDynamic
Enter the value for A
12
Enter the value for A
4
16
8
48
3.0
0
D:\webtech>*/
5.Write
a Java Program to create a user defined Exception called ―StringNotMatchException‖ when the user entered input is not
equal to ―INDIA
Source
Code
import java.io.*;
import java.lang.Exception;
class StringNotMatch extends Exception
{
StringNotMatch(String msg)
{
super(msg);
}
}
class StringIndia
{
public static void main(String args[]) throws
Exception
{
String s1;
System.out.println("enter string");
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
s1=br.readLine();
try{
if(s1.equalsIgnoreCase("INDIA"))
System.out.println("match");
else
throw new StringNotMatch("no match");
}
catch(StringNotMatch e)
{
System.out.println("stringnotmatch
caught");
System.out.println(e.getMessage());
}
}
}
/*D:\webtech>javac StringIndia.java
D:\webtech>java StringIndia
enter string
India
match
D:\webtech>java StringIndia
enter string
indane
stringnotmatch caught
no match
D:\webtech>*/
6. Write
a HTML to create user registration form with following constraints;
Source
Code
Main.html
<html>
<head>
<title>SREERAMA</title>
</head>
<body
bgcolor="cyan"><center>
<strong><h1>Welcome to SREERAMA
</h1></strong>
<form method="post"
action="login.html" target=_blank >
<h4>for books</h4>
<input type="submit"
value="click here">
</form>
</center>
</body>
</html>
Login.html:
<html>
<head>
<title>
login page</title>
</head>
<body
bgcolor="cyan"><center>
<strong><h1> SREERAMA
</h1></strong></center>
<right>
<table align="right">
<tr>
<td><h4>user name</td>
<td><input type="text"
></td>
<td></td>
</tr>
<tr>
<td><h4>password</td>
<td><input
type="password"></td>
<td></td>
</tr>
<tr>
<td>
<form method="post"
action="catalog.html" >
<input type="submit"
value="submit" >
</form>
</td>
<td>
<form method="post"
action="userpro.html" >
<input type="submit"
value="register" >
<input type="reset"
value="reset"></form></td>
</tr>
</table>
</body>
</html>
Userpro.html:
<html>
<head>
<title>
login page</title>
</head>
<body bgcolor="cyan">
<center><strong><h1>
SREERAMA</h1></strong></center>
<form method="post" action="catalog.html"
>
<right>
<table align="left">
<tr>
<td><h4>user name</td>
<td><input type="text"
></td>
<tr>
<tr>
<td><h4>password</td>
<td><input
type="password"></td>
</tr>
<tr>
<td><h4>confirm password</td>
<td><input
type="password"></td>
</tr>
<tr>
<td><h4>male
<option >
<input type="radio"
name="sex" id="male"></td>
<td><h4>female
<input type="radio"
name="sex" id="female" ></td>
</option>
</tr>
<tr>
<td>Address</td>
<td><textarea name="address"
rows=5 cols=19>
</textarea>
</td>
<tr>
<td>
<input type="submit"
value="submit" ></td>
<td>
<input type="reset"
value="reset"></td>
</tr>
</form>
</body>
</html>
Catalog.html:
<html>
<head>
<title>
books catalog</title>
</head>
<body bgcolor="cyan">
<center><h1>SREERAMA</h1></center>
<form method="post"
action="shopping.html">
<left>
<table>
<tr>
<td><b><h3>frontend
books</td>
<td></td></tr>
<tr>
<td></td>
<td><h4>CP</td>
</tr>
<tr>
<td></td>
<td><h4>DS</td>
</tr>
<tr>
<td></td>
<td><h4>JAVA
</td></tr>
<tr>
<td><b><h3>backend books</td>
<td></td>
</tr>
<tr>
<td></td>
<td><h4>Oracle</td>
</tr>
<tr>
<td></td>
<td><h4>Ms SQL Server
</td></tr>
<tr>
<td></td>
<td><h4>MySql </td>
</tr>
</table>
</h4>
<center>
<b>for buy one of these books
<br>
</b><input type="submit"
value="click here">
</center>
</form>
</body>
</html>
Shoppig.html
<html>
<head><title>shopping
cart</title>
</head>
<body bgcolor="cyan">
<center><h1>
Shopping Cart</h1></center>
<br><br><br><br><br>
<table align="center">
<tr>
<td>Text Books</td>
<td>
<select >
<optgroup label="select the
book">
<option value="CP">CP
<option value="DS">DS
<option value="Java">Java
<option value="Oracle">Oracle
<option value="Ms SQL
Server">Ms SQL Server
<option value="MySql">MySql
</optgroup>
</select>
</td></tr>
<tr>
<td>
Quantity</td>
<td>
<input type="text"
id="q">
</td></tr>
<tr>
<td></td>
<td>
<form method=post
action="payment.html">
<input type="submit" value=ok
/>
</form>
</td></tr>
</table>
<center>
<pre>Cost of one book is"500" +
shipping "100"</pre>
</center>
<body>
</html>
Payment.html
<html>
<head><title>payment</title></head>
<body bgcolor="cyan">
<center><h1>Payment By Credit
Card</h1></center>
<form method=post
action="ordrconform.html">
<br><br><br><br><br>
<table align="center">
<tr> <td>
<h4>Total Amount</h4></td>
<td><input type="text">
</td> </tr>
<tr>
<td><h4>Credit Card
Number</td>
<td><input
type="text"></td>
</tr> <tr> <td> </td>
<td><input type="submit"
value=OK>
</td> </tr>
</table>
</form></body>
</html>
Ordrconform.html
<html>
<head><title>order
conformation</title><M/head>
<body bgcolor="cyan">
<center>
<h1><b>SREERAMA</h1>
<pre><strong>
<b>Your order Is Conformed
</strong></pre>
<h2><b>THANK YOU</h2>
</center> </body> </html>
7. Validate
the registration, user login, user profile and payment by credit card pages
using Java Script
Source
Code
Main.html
<html>
<frameset rows="25%,*">
<frame src="Top.html"
name="top" scrolling ="no" frameborder ="0">
<frameset cols="25%,75%">
<frame src="Left.html"
name="left" scrolling ="no" frameborder ="0">
<frame src="Right.html"
name="right" scrolling ="auto" frameborder
="0">
</frameset>
</frameset>
</html>
Top.html:
<html>
<body
bgcolor="pink"> <br><br>
<marquee><h1
align="center"><b>
<u>ONLINE
BOOK STORAGE</u>
</b></h1></marquee>
</body>
</html>
Right.html:
<html>
<body>
<br><br><br><br><br>
<h2 align="center">
<b><p>
welcome to online book storage. Press login if you are having id otherwise
press user profile
</p></b></h2>
</body> </html>
Left.html:
<html>
<body
bgcolor="pink"> <h3>
<ul>
<li><a
href="Login.html" target="right"><font
color="black">
LOGIN</font></a></li><br><br>
<li><a
href="Profile.html" target="right"><font
color="black">
USER
PROFILE</font></a></li><br><br>
<li><a
href="Catalog.html" target="right"><font
color="black">
BOOKS
CATALOG</font></a></li><br><br>
<li><a
href="Scart.html" target="right"><font
color="black">
SHOPPINGCART</font></a></li><br><br>
<li><a
href="Payment.html" target="right"><font
color="black">
PAYMENT</font></a></li><br><br>
<br><br>
</ul>
</body>
</html>
Registration and user
Login
Login.html:
<html>
<body
bgcolor="pink"><br><br><br> <script
language="javascript">
function validate()
{
var flag=1;
if(document.myform.id.value==""||
document.myform.pwd.value=="")
{
alert("LoginId and Password
must be filled");
flag=0;
}
if(flag==1)
{
alert("VALID INPUT");
window.open("Catalog.html","right");
}
else
{
alert("INVALID INPUT");
//document.myform.focus();
}
}
</script>
<form
name="myform"> <div align="center"><pre>
LOGIN ID:<input
type="text" name="id"><br>
PASSWORD:<input
type="password" name="pwd"><br><br>
</pre>
<input type="button"
value="ok"
onClick="validate()">
<input type="reset"
value="clear" >
</div>
</form>
</body>
</html>
User profile page
Profile.html:
<html>
<body
bgcolor="pink"><br><br>
<script
type="text/javascript">
function validate()
{
var flag=1;
if(document.myform.name.value==""||
document.myform.addr.value==""||
document.myform.phno.value==""||
document.myform.id.value==""||
document.myform.pwd.value=="")
{
alert("Enter all the
details");
flag=0;
}
var
str=document.myform.phno.value;
var x=new
RegExp("\\d","g"); if(!(str.match(x)))
{
if(!(str.length==10))
flag=0;
}
var str1=document.myform.id.value;
var x1=new
RegExp("^[A-Z][a-zA-Z]+$","g"); if(!(str1.match(x1)))
{
flag=0;
alert("Invalid
UserID");
}
var
str1=document.myform.pwd.value; var x1=new
RegExp("^[A-Z][a-zA-Z]+$","g"); if(!(str1.match(x1)))
{
flag=0;
alert("Invalid
password");
}
if(flag==1)
{
alert("VALID INPUT");
window.self.location.href="Login.html";
}
else
{
alert("INVALID INPUT");
document.myform.focus();
}
}
</script>
<form
name="myform"> <div align="center"><pre>
NAME :<input type="text" name="name"><br>
ADDRESS :<input
type="type" name="addr"><br>
CONTACT NUMBER:<input
type="text" name="phno"><br>
LOGINID :<input type="text"
name="id"><br>
PASSWORD :<input type="password"
name="pwd"></pre><br><br>
</div>
<br><br>
<div
align="center">
<input type="button"
value="ok" onClick="validate()">
<input type="reset"
value="clear">
</form>
</body>
</html>
Books catalog :
Catalog.html:
<html>
<body
bgcolor="pink"><br><br><br> <script
language="javascript">
function validate()
{
var flag=1;
if(document.myform.id.value==""||
document.myform.title.value==""||
document.myform.no.value==""||
document.myform.cost.value=="")
{
flag=0;
}
str=document.myform.title.value;
var
str1=document.myform.cost.value;
if(!((str=="c"&&
str1==444) || (str=="jsp" && str1==555)))
{
flag=0;
}
if(flag==1)
{
alert("VALID INPUT");
}
else
{
alert("INVALID
INPUT");
document.myform.focus();
} }
</script>
<form name="myform" action="Scart.html"
target="right">
<div
align="center"><pre>
LOGIN ID :<input type="text"
name="id"><br>
TITLE :<input type="text"
name="title"><br>
NO.OF BOOKS :<input type="text"
name="no"><br>
COST OF BOOK :<input
type="text"name="cost"><br>
</pre><br><br>
</div>
<br><br>
<div
align="center">
<input type="submit"
value="ok" onClick="validate()">
<input type="reset"
value="clear">
</form>
</body>
</html>
Scart.html:
<html>
<body
bgcolor="pink"><br><br><br> <script
language="javascript">
function validate()
{
var flag=1;
if(document.myform.title.value=="")
{
flag=0;
}
str=document.myform.title.value;
if(str=="c"||str=="C")
{
document.myform.t1.value="C";
document.myform.t2.value=444;
}
else
if(str=="jsp"||str=="JSP")
{
document.myform.t1.value="JSP";
document.myform.t2.value=555;
}
else
{
flag=0;
}
if(flag==1)
{
alert("VALID INPUT");
}
else
{
alert("INVALID INPUT");
document.myform.focus();
}
}
</script>
<form name="myform"
action="payment.html" target="right"> <div
align="center"><pre>
BOOK TITLE :<input
type="text" name="title"><br>
</pre><br><br>
Book Title: <input
type="text" name="t1" disabled> Book Cost: <input
type="text" name="t2" disabled> </div>
<br><br>
<div
align="center">
<input type="submit"
value="ok"
onClick="validate()">
<input type="reset" value="clear">
<input type="submit"
value="Purchase"> </form>
</body>
</html>
Payment by credit
card
Payment.html:
<html>
<body
bgcolor="pink"><br><br><br> <script
language="javascript"> function validate()
{
var flag=1;
if(document.myform.id.value==""||
document.myform.pwd.value==""|| document.myform.amount.value==""||
document.myform.num.value=="")
{
flag=0;
}
var
str=document.myform.amount.value; var x=new
RegExp("\\d","g"); if(!(str.match(x)))
{
flag=0;
}
var
str1=document.myform.num.value; var x1=new
RegExp("\\d","g");
if(!(str.match(x1)))
{
flag=0;
}
if(flag==1)
{
alert("VALID INPUT");
window.self.location.href="order.html";
}
else
{
alert("INVALID INPUT");
document.myform.focus();
}
}
</script>
<form
name="myform"> <div align="center"><pre>
LOGIN ID :<input type="text" name="id"><br>
PASSWORD :<input type="password"
name="pwd"><br>
AMOUNT :<input type="text"
name="amount"><br>
CREDITCARDNUMBER :<input
type="PASSWORD"
name="num"><br></pre><br><br> </div>
<br><br>
<div
align="center">
<input type="button"
value="ok" onClick="validate()">
<input type="reset" value="clear" >
</form>
</body>
</html>
Order Conformation
Order.html:
<html>
<head><title>order
conformation</title><M/head> <body bgcolor="cyan">
<center>
<h1><b>SREERAMA</h1>
<pre><strong>
<b>Your order Is Conformed
</strong></pre> <h2><b>THANK YOU</h2>
</center>
</body>
</html>
Input&Output
8.Write
a Java Servlet Program to display the Current time on the server.
Develop
a servlet program that displays server date and time.
DateServlet.java
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DateServlet extends
GenericServlet
{
public void service(ServletRequest
req,ServletResponse res) throws IOException, ServletException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
Date d=new Date();
out.println("<h1> Server
Date is"+d+"</h1>");
} }
Web.xml:
<?xml version="1.0"
encoding="ISO-8859-1" ?>
<web-app
>
<servlet>
<servlet-name>DateServlet</servlet-name>
<servlet-class>DateServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DateServlet</servlet-name>
<url-pattern>/first</url-pattern>
</servlet-mapping>
</web-app>
Server Date isThu Mar 23 13:01:21 IST 2017
9.To write html and servlet to demonstrate invoking a servlet from
a html
Welcome.html:
<html>
<head><title>Welcome
HTML form</title></head>
<body>
<form method="get"
action=" ">
<h1> This welcome HTML
File</h1>
<input type="submit"
name="submit" value="submit">
</form>
</body>
</html> ServletHtml.java named as URL name invoking :
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ServletHtml extends
GenericServlet
{
public void service(ServletRequest
req,ServletResponse res) throws IOException, ServletException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.println("<h1> This is
demonstration of SERVLET from a HTML File</h1>");
}
}
Web.xml:
<web-app>
<servlet>
<servlet-name>ServletHtml</servlet-name>
<servlet-class>ServletHtml</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletHtml</servlet-name>
<url-pattern>/servhtml</url-pattern>
</servlet-mapping>
</web-app>
Input&Output
This is demonstration of SERVLET from a
HTML File
10.Write
a Java servlet program to change the Background color of the page by the color
selected by the user from the list box.
Source
Code
change.html:
<html>
<head><title>Selction
of color in List</title></head>
<body>
<form method="post"
action="changecolor ">
enter one color in the list
<select name="colornw">
<option
value="red">red</option>
<option
value="green">green</option>
<option
value="orange">orange</option>
<option value="cyan">cyan</option>
<option
value="yellow">yellow</option>
<option
value="blue">blue</option>
</select> </br>
<input type="submit"
name="submit" value="submit">
</form>
</body>
</html>
ChangeColor.java:
import java.io.*;
import
javax.servlet.*;
import javax.servlet.http.*;
public class
ChangeColor extends GenericServlet
{
String s1=null;
public void
service(ServletRequest req,ServletResponse res) throws IOException,
ServletException
{
s1=req.getParameter("colornw");
res.setContentType("text/html");
PrintWriter
out=res.getWriter();
if(s1.equals("red")) {
System.out.println("u have
selected red color");
out.println("<html><body
bgcolor="+s1+"><h1> This is demonstration of red background
SERVLET from a HTML File</h1></body></html>");
} else if(s1.equals("green"))
{
out.println("<html><body
bgcolor="+s1+"><h1> This is demonstration of green
background SERVLET from a HTML
File</h1></body></html>"); }
else
if(s1.equals("orange")) {
out.println("<html><body
bgcolor="+s1+"><h1> This is demonstration of orange
background SERVLET from a HTML
File</h1></body></html>");
}
else
if(s1.equals("cyan"))
{
out.println("<html><body
bgcolor="+s1+"><h1> This is demonstration of cyan background
SERVLET from a HTML File</h1></body></html>");
}
else
if(s1.equals("yellow"))
{
out.println("<html><body
bgcolor="+s1+"><h1> This is demonstration of yellow
background SERVLET from a HTML
File</h1></body></html>");
}
else
{
out.println("<html><body
bgcolor="+s1+"><h1> This is demonstration of blue background
SERVLET from a HTML File</h1></body></html>");
} } }
Web.xml:
<?xml
version="1.0" encoding="ISO-8859-1" ?>
<web-app>
<servlet>
<servlet-name>ChangeColor</servlet-name>
<servlet-class>ChangeColor</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ChangeColor</servlet-name>
<url-pattern>/changecolor</url-pattern>
</servlet-mapping>
</web-app>
Input&Output
enter
one color in the list
This is demonstration of green background
SERVLET from a HTML File
11.Write
a Java servlet to get the personal details about the user(Like name, Address,
City, Age, E-mail id) and check whether the user is Eligible to vote or not.
Source
Code
Personaldet.html:
<html>
<head><title>Selction of
color in List</title></head>
<body>
<form method="post"
action="personaldetails">
name: <input
type="text" name="t1" size=20></br>
address: <input
type="text" name="t2"></br>
city: <input
type="text" name="t3"></br>
age: <input type="text"
name="t4"></br>
mail id: <input
type="text" name="t5"></br>
<input type="submit"
name="submit" value="submit">
<input type="reset"
name="reset" value="clear">
</form>
</body>
</html>
PersonalDetials.java:
import
java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class PersonalDetials extends
GenericServlet
{
String s1=null,s2=null,s3=null,s4=null,s5=null;
int age;
public void service(ServletRequest
req,ServletResponse res) throws IOException, ServletException
{
s1=req.getParameter("t1");
s2=req.getParameter("t2");
s3=req.getParameter("t3");
s4=req.getParameter("t4");
s5=req.getParameter("t5");
res.setContentType("text/html");
PrintWriter out=res.getWriter();
age=Integer.parseInt(s4);
if(age>=18)
{
out.println("<h1>name
is"+s1+"</h1>");
out.println("<h1>address
is"+s2+"</h1>");
out.println("<h1>city
is"+s3+"</h1>");
out.println("<h1>age
is"+s4+"</h1>");
out.println("<h1>mail id
is"+s5+"</h1>");
} else {
out.println("<h1> You are
not have right to vote and u r under age 18</h1>");
} } }
Web.xml:
<?xml
version="1.0" encoding="ISO-8859-1" ?>
<web-app>
<servlet>
<servlet-name>PersonalDetials</servlet-name>
<servlet-class>PersonalDetials</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>PersonalDetials</servlet-name>
<url-pattern>/personaldetails</url-pattern>
</servlet-mapping>
</web-app>
Input&Output:
name:
address:
city:
age:
mail id:
address:
city:
age:
mail id:
name is siddaiah
address is Kalavakuru
city is Tirupati
age is 34
12.Write
a Java servlet Program to create a Cookie and keep it alive on the client for
30 minutes.
Source
Code
Welcome1.html:
<html>
<head><title>Welcome HTML
form</title></head>
<body>
<form method="get"
action="createcookie">
<h1> This welcome HTML File</h1>
enter value1<input type="text"
name="t1"></br>
enter value2<input type="text"
name="t2"></br>
<input type="submit"
name="submit" value="submit">
<input type="reset"
name="reset" value="clear">
</form>
</body>
</html>
CreateCookie.java:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class CreateCookie extends HttpServlet {
String
s1=null,s2=null;
protected void doGet(HttpServletRequest req,HttpServletResponse resp)
throws ServletException,IOException
{ resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
s1=req.getParameter("t1");
s2=req.getParameter("t2");
Cookie ck1=new Cookie("nameone",s1);
Cookie
ck2=new Cookie("nametwo",s2);
ck1.setMaxAge(360);
ck2.setMaxAge(360);
resp.addCookie(ck1);
resp.addCookie(ck2);
if(ck1.getMaxAge()==360 &&
ck2.getMaxAge()==360)
out.println("<h1>the created cookies
are alive for 30mins</h1>");
/* Cookie ck[]=request.getCookies();
for(int
i=0;i<ck.length;i++) */
out.println("<h1>"+ck1.getName()+":
value is"+ck1.getValue()+"</h1>");
out.println("<h1>"+ck2.getName()+":
value is"+ck2.getValue()+"</h1>");
}
}
Web.xml:
<?xml
version="1.0" encoding="ISO-8859-1" ?>
<web-app> <servlet>
<servlet-name>CreateCookie</servlet-name>
<servlet-class>CreateCookie</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CreateCookie</servlet-name>
<url-pattern>/createcookie</url-pattern>
</servlet-mapping>
</web-app>
Input&Output
This welcome HTML File
enter
value1
enter value2
enter value2
the created cookies are alive for 30mins
name one: value is siddu
name two: value is mtechcs
13. Write a java servlet program to display the
various client information like Connection, Host, Accept-Encoding, User Agent.
Source
Code
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class DisplayHeader
extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse
response)
throws ServletException,
IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<center><h1>HTTP
Header Request Example</h1></center>");
out.println("<table><tr><th>Header
Name</th><th>Header Information</th></tr>");
Enumeration headerNames =
request.getHeaderNames();
while(headerNames.hasMoreElements())
{
String paramName =
(String)headerNames.nextElement();
out.print("<tr><td>" + paramName +
"</td>\n");
String paramValue =
request.getHeader(paramName);
out.println("<td> " +
paramValue + "</td></tr>\n");
}
out.println("</table>\n</body></html>");
}
// Method to handle POST method request.
public void doPost(HttpServletRequest
request,
HttpServletResponse
response)
throws ServletException, IOException {
doGet(request, response);
}
}
Input&Output:
HTTP Header Request
Example
Header
Name
|
Header
Information
|
host
|
localhost:8080
|
connection
|
keep-alive
|
upgrade-insecure-requests
|
1
|
user-agent
|
Mozilla/5.0 (Windows NT 6.1)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36
|
accept
|
text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
|
accept-encoding
|
gzip, deflate, sdch, br
|
accept-language
|
en-US,en;q=0.8
|
14. To write java servlet programs to conduct
online examination and to display student mark list available in a database
Source
Code
Studentservlet.java:
import
java.io.*;
import java.sql.*;
import
javax.servlet.*;
import
javax.servlet.http.*;
public class
StudentServlet extends HttpServlet
{
String
message,Seat_no,Name,ans1,ans2,ans3,ans4,ans5;
int Total=0;
Connection con;
Statement
stmt=null;
ResultSet rs=null;
public void
doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con =
DriverManager.getConnection("jdbc:odbc:studentsinfo");
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=con.createStatement();
// stmt.execute("create
table studinfo(seat_no number, name varchar(20), total varchar(5) )");
// stmt.execute("insert into studentdata
values(01,'Bharath Kuamr','Tirupati')");
String
query="INSERT INTO
studinfo("+"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();
out.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=con.createStatement();
String
query="SELECT * FROM studinfo";
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!=null)rs.close();
if(stmt!=null)
stmt.close();
if(con!=null)con.close();}
catch(SQLException
e){ }}
out.println("</center>");
out.println("</body></html>");
Total=0;
}
}
Studentinfo.html
<html>
<head><title>Database
Test</title></head>
<body>
<center><h1>Online
Examination</h1></center>
<form
action="stuinfo" 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
todestination</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>
<web-app>
<servlet>
<servlet-name>StudentServlet</servlet-name>
<servlet-class>StudentServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>StudentServlet</servlet-name>
<url-pattern>/stuinfo</url-pattern>
</servlet-mapping>
</web-app>
Input&Output:
http://localhost:8080/stuinfo/studentinfo.html
Online
Examination
Seat Number:
Name:
1. Every host implements transport layer.
TrueFalse
2. It is a network layer's responsibility to forward packets reliably from source todestination
TrueFalse
3. Packet switching is more useful in bursty traffic
TrueFalse
4. A phone network uses packet switching
TrueFalse
5. HTML is a Protocol for describing web contents
TrueFalse
http://localhost:8080/stuinfo/stuinfo
Thank you for
participating in online Exam
Yours results stored in
our database
Participants and their Marks
Seat_no
|
Name
|
Marks
|
4
|
1
|
asdf
|
5
|
2
|
Siddaiah
|
6
|
3
|
Dinesh
|
7
|
5
|
SAMBA
|
15.Write a Java servlet Program to implement
the Book Information using JDBC
Source
Code
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class BookInfo extends HttpServlet{
protected void doGet(HttpServletRequest
req,HttpServletResponse resp) throws ServletException,IOException
{
resp.setContentType("text/html");
PrintWriter out=resp.getWriter();
try
{
Connection con=null;
Statement st=null;
ResultSet rs=null;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con =
DriverManager.getConnection("jdbc:odbc:studbook");
st=con.createStatement();
String sql="select * from
studentbook";
rs=st.executeQuery(sql);
out.println("<h1>database book
details</h1>");
while(rs.next())
{
out.println("<h1>"+rs.getInt(1)+"\t"+rs.getString(2)+"\t"+rs.getString(3)+"\t"+rs.getString(4)+"\t"+rs.getInt(5)+"</h1>");
}
rs.close();
st.close();
con.close();
}
catch(Exception e) { e.printStackTrace(); }
}
}
Web.xml
<web-app>
<servlet>
<servlet-name>BookInfo</servlet-name>
<servlet-class>BookInfo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>BookInfo</servlet-name>
<url-pattern>/studbook</url-pattern>
</servlet-mapping>
</web-app>
Input&Outpu
database book details
1 C AnandRao CSE 340
2 C++ Jaswanth CSE 440
3 DBMS Korth CSE 350
16.Write a Java Servlet Program to create a
Session and display the various information like, Last accessed time, Modified
time, Expiration)
Week17.html:
<html>
<head><title>Selction
of color in List</title></head>
<body>
<form
action="servlet1">
Name:<input
type="text" name="userName"/><br/>
<input
type="submit" value="go"/>
</form>
</form>
</body>
</html>
FirstServlet.java:
import
java.io.*;
import
java.util.*;
import
javax.servlet.*;
import
javax.servlet.http.*;
public class FirstServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,
HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out =
response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
HttpSession
session=request.getSession();
session.setAttribute("uname",n);
out.println("<h1>the
session id:"+session.getId()+"</h1><br>");
out.println("<h1>creation
time"+session.getCreationTime()+"</h1><br>");
out.println("<h1>last
accessed time"+session.getLastAccessedTime()+"</h1>");
out.print("<a
href='servlet2'>visit</a>");
out.close();
}catch(Exception
e){System.out.println(e);}
} }
SecondServlet.java:
import
java.io.*;
import
java.util.*;
import
javax.servlet.*;
import
javax.servlet.http.*;
public class SecondServlet extends
HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,IOException
{
response.setContentType("text/html");
PrintWriter out =
response.getWriter();
HttpSession session=request.getSession(false);
out.println("<h1>the
session id:"+session.getId()+"</h1><br>");
out.println("<h1>"+new
Date(session.getCreationTime())+"</h1><br>");
out.println("<h1>"+new
Date(session.getLastAccessedTime())+"</h1><br>");
String n=(String)session.getAttribute("uname");
out.print("Hello "+n);
session.setMaxInactiveInterval(5);
out.println("<h1>expiration
time"+session.getMaxInactiveInterval()+"</h1>");
out.close();
} }
Web.xml:
<?xml
version="1.0" encoding="ISO-8859-1" ?>
<web-app
>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
Input&Output:
Name:
Welcome
siddaiah Nelaballi
the
session id:C7D09EC9F8710B5D10CA8B6A500E6D77
creation
time1490247672537
last
accessed time1490247672537
the session
id:C7D09EC9F8710B5D10CA8B6A500E6D77
Thu Mar 23 11:11:12 IST
2017
Thu Mar 23 11:15:12 IST
2017
Hello siddaiah Nelaballi
expiration time5
17.Write a JSP Program to Display the number of
visitors visited the page.
Source
Code
Visitors.jsp
<%@
page import="java.io.*,java.util.*" %>
<html>
<head>
<title>Applcation
object in JSP</title>
</head>
<body>
<%
Integer hitsCount =
(Integer)application.getAttribute("hitCounter");
if( hitsCount ==null || hitsCount == 0 ){
out.println("<h1>Welcome to
my website!</h1>");
hitsCount = 1;
}else{
out.println("<h1>Welcome back
to my website!</h1>");
hitsCount += 1;
}
application.setAttribute("hitCounter",
hitsCount);
%>
<center>
<p><h1>Total
number of visits: <%= hitsCount%></h1></p>
</center>
</body>
</html>
web.xml
<web-app>
</web-app>
Input&Output
Welcome back to my website!
Total number of visits:
3
18.Write a JSP Program to implement the Book
Information using Database.
Source
Code
Bookinfo.jsp
<%@page
contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC
"-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta
http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<center>
<h1>Book Store</h1>
<%@ page language="java"
%>
<%@ page
import="java.sql.*" %>
<%@ page
import="java.sql.DriverManager.*" %>
<%
Connection con= null;
ResultSet rs= null;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con =
DriverManager.getConnection("jdbc:odbc:bookinfo");
Statement st=con.createStatement();
rs=st.executeQuery("select * from
book ");
while(rs.next())
{
out.println("<h1>");
out.println("<pre>");
out.println("ID is =" +rs.getInt(1));
out.println("<br>");
out.println("book
title=" +rs.getString(2));
out.println("<br>");
out.println("book
category=" +rs.getString(3));
out.println("<br>");
out.println("book
author=" +rs.getString(4));
out.println("<br>");
out.println("book
edition=" +rs.getString(5));
out.println("<br>");
out.println("book
price=" +rs.getInt(6));
out.println("</pre>");
out.println("</h1>");
}
%> </center> </body> </html>
Web.xml
<web-app>
</web-app>
Input&Output
http://localhost:8080/bookinfojsp/bookinfo.jsp
Book Store
ID is
=6
book title=c
book category=engg
book author=anandrao
book edition=3rd
book price=344
ID is
=7
book title=c++
book category=engg
book author=balaguruswamy
book edition=4th
book price=455
19.Write a JSP Program to implement the
Telephone Directory
Source
Code
Input.html
<html>
<head>
<meta
http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>JSP Page</title>
</head>
<body><h1>
<center>Enter
Information<br>
<form
action="telephone.jsp">
Enter the name :: <input
type="text" name="n" >
<br><br><input
type="submit" value="Submit">
</form>
</center></h1>
</body>
</html>
<%@page
contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE
HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta
http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<center>
<h1>Telephone
Directory</h1>
<%@ page language="java"
%>
<%@ page
import="java.sql.*" %>
<%@ page
import="java.sql.DriverManager.*" %>
<%
String m=null, mn=null;
String
s=request.getParameter("n");
PreparedStatement ps=null;
Connection con= null;
ResultSet rs= null;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con =
DriverManager.getConnection("jdbc:odbc:telephone");
Statement st=con.createStatement();
rs=st.executeQuery("select *
from phone where name='"+ s+"' ");
while(rs.next())
{
m=rs.getString(2);
mn=rs.getString(3);
}
out.println("<br>");
out.println("<h1>");
out.println("<pre>");
out.println("name =" +m);
out.println("<br>");
out.println("ph no. ="
+mn);
out.println("</pre>");
out.println("</h1>");
%>
</center>
</body>
</html>
Web.xml
<web-app>
</web-app>
Input&Output
Enter Information
Enter the name ::
Telephone Directory
name
=lakshmi
ph no. =9704602062
2 Comments:
cool...!!!!
Great Article
Final Year Projects in Python
Python Training in Chennai
FInal Year Project Centers in Chennai
Python Training in Chennai
Post a Comment
Subscribe to Post Comments [Atom]
<< Home