Anda di halaman 1dari 51

Write a Servlet that will count the number of times a client has accessed the

web page.

// countaccess.html
<html>
<body>
<form action="http://localhost:8080/examples/servlet/countAccess"
method="POST">
<input type="hidden"value='<%=new java.util.Date()%>' name="clientDate">
<input type=submit value= submit>
</form>
</body>
</html>

countAccess.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.Date;
publicclass countAccess extends HttpServlet
{

privateint accessCount = 0;

protected synchronized void IncrementCount() {


accessCount++;
}

protected synchronized int getCount() {


return accessCount;
}

publicvoid doPost(HttpServletRequest req, HttpServletResponse res)


throws ServletException, IOException
{
IncrementCount();
PrintWriter out= res.getWriter();
try
{
res.setContentType("text/html");
Date serverDate=new Date();
String clientDateStr = req.getParameter("clientDate");

out.println("<P><B>Server Side Date and time in millisecond= "+serverDate);


out.println("<P><B>Client Side Date and time in millisecond= "+clientDateStr);
out.println("<P><B>Page Accesed "+getCount()+" Times");

}
catch(Exception e)
{
System.out.println(e);
}
}
}

res.setContentType("text/html");
Date serverDate=new Date();
String clientDateStr = req.getParameter("clientDate");

out.println("<P><B>Server Side Date and time in millisecond= "+serverDate);


out.println("<P><B>Client Side Date and time in millisecond= "+clientDateStr);
out.println("<P><B>Page Accesed "+getCount()+" Times");

}
catch(Exception e)
{
System.out.println(e);
}
}
}

Write a Java program to read, update & delete records from Student(studno,
name, phone) Database using command line arguments [R-Read, U-Update, D-
Delete]
Eg:- java program name U
This will update & show the contents of the student tables.

import java.sql.*;
public class mysql4
{
public static void main(String[] args) throws Exception
{
Connection con;
ResultSet rs;
Statement t;
PreparedStatement pr;
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost/chemical","root","")
;
char ch=args[0].charAt(0);
switch(ch)
{
case 'R':
t=con.createStatement();
rs=t.executeQuery("select * from element");
while(rs.next())
{
System.out.println("name="+rs.getString(2));
System.out.println("automic wt="+rs.getInt(1));
System.out.println("symbol="+rs.getString(3));
}
break;
case 'D':
String name=args[1];
t=con.createStatement();
t.executeUpdate("delete from element where name='"+name+"'");
break;
case 'U':
name=args[1];
int awt=Integer.parseInt(args[2]);
String sm=args[3];
t=con.createStatement();
t.executeUpdate("update element set
automicwt="+awt+",chemical_sym='"+sm+"' where name='"+name+"'");
break;
}
}
}

Write a java program to accept the details of Teacher (TId, Name, Address)
from the user and insert it into the Database.(use Awt).

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.sql.*;
public class Employee extends Frame implements ActionListener
{
Label l1,l2,l3;
TextField t1,t2,t3;
Button b;
Connection cn;
Statement st;
ResultSet rs;
public Teacher()
{
setLayout(null);
l1=new Label("Tid");
l2=new Label("Name");
l3=new Label("Address");
t1=new TextField();
t2=new TextField();
t3=new TextField();
b=new Button("Save");
l1.setBounds(50,50,100,30);
t1.setBounds(160,50,100,30);
l2.setBounds(50,90,100,30);
t2.setBounds(160,90,100,30);
l3.setBounds(50,130,100,30);
t3.setBounds(160,130,100,30);
b.setBounds(50,170,100,30);
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(t3);
add(b);
b.addActionListener(this);
setSize(500,500);
setVisible(true);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent oe)
{
String str=oe.getActionCommand();
if(str.equals("Save"))
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
cn=DriverManager.getConnection("jdbc:odbc:Emp","","");
st =cn.createStatement();
int Tid=Integer.parseInt(t1.getText());
String name=t2.getText();
int address=Integer.parseInt(t3.getText());
String strr="insert into teacher values(" + Tid + " ,'" + name + "'," +
adderss + ")";
int k=st.executeUpdate(strr);
if(k>0)
{

JOptionPane.showMessageDialog(null,"Record Is Added");
}
}
catch(Exception er)
{
System.out.println("Error");
}
}
}
public static void main(String args[])
{
new Employee().show();
}

Write a JSP program that accepts the Mobile phone details from user and
display the details on the next page.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="mobileaction.jsp">
Enter Your Mobile No Details <br />
Enter Mobile No : <input type="text" name="mobileno" /> <br />
Service Provider : <input type="text" name="serviceprovider" /> <br />
Network : <input type="radio" name="network" value="GSM" checked
/>GSM
<input type="radio" name="network" value="CDMA" />CDMA

<input type="submit" value="submit" />


</form>
</body>
</html>
ACTION:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String mobileno=request.getParameter("mobileno");
String serviceprovider=request.getParameter("serviceprovider");
String network=request.getParameter("network");

out.println("Mobile No : " + mobileno + "<br />");


out.println("Service Provider : " + serviceprovider + "<br />");
out.println("Network : " + network + "<br />");
%>
</body>
</html>

Write a Java program using JSP which accepts string from user and display
only vowel characters on a next page.

import java.io.*;
class q5vowels
{
public static void main(String args[]) throws IOException
{
String str;
int vowels = 0, digits = 0, blanks = 0;
char ch;

BufferedReader br = new BufferedReader(new


InputStreamReader(System.in));
System.out.print("Enter a String : ");
str = br.readLine();

for(int i = 0; i < str.length(); i ++)


{
ch = str.charAt(i);

if(ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' ||


ch == 'I' || ch == 'o' || ch == 'O' || ch == 'u' || ch == 'U')
vowels ++;
else if(Character.isDigit(ch))

System.out.println("Vowels : " + vowels);

}
}

Output:

Enter a String : ABC DE 123


Vowels : 2

Write a programs that create 2 threads each displaying a message (Pass the
message as a parameter to the constructor). The threads should display the
messages continuously till the user presses ctrl-c. Also display the thread
information as it is running

import java.io.*;
class Ass_seta1 extends Thread
{
String msg="";
Ass_seta1(String msg)
{
this.msg=msg;
}
public void run()
{
try
{ while(true)
{
System.out.println(msg);
Thread.sleep(200);
}
}
catch(Exception e){}
}
}
public class seta1
{
public static void main(String a[])
{
Ass_seta1 t1=new Ass_seta1("Hello............");
t1.start();
}
}
/******************************output***************************
Hello............
Hello............
Hello............
Hello............
Hello............
Hello............
Hello............
Hello............
Hello............

Create a JSP page, which accepts user name in a text box and greets the user
according to the system time. Example: User name : XYZ
Good morning xyz (if it is morning)

// user.html
<form method='post' action='user.jsp'>
User Name:<input type='text' name='uname'><br>
<input type='submit'><input type='reset'>
</form>

// user.jsp
<%@page import="java.util.*"%>
<%
String name = request.getParameter("uname");
Date d = new Date();
if(d.getHours()<12)
{
%>
Good Morning <%=name%>
<%
}
else if(d.getHours()<16)
{
%>
Good Afternoon <%=name%>
<%
}
else
{
%>
Good Evening <%=name%>
<%
}
%>

Write a Java program to perform insert and delete operations on employee


(id, name, salary) using Prepared Statement.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class MyPreparedStatement {

public static void main(String a[]){


Connection con = null;
PreparedStatement prSt = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:@<hostname>:<port
num>:<DB name>","user","password");
String query = "insert into employee (id,name,salary) values(?,?,?)";
prSt = con.prepareStatement(query);
prSt.setInt(1, 101);
prSt.setString(2, "John");
prSt.setInt(2, 10000);
prSt.executeUpdate();
System.out.println("Record is Inserted!");
String deleteSQL = "DELETE from employee WHERE USER_ID = ?";
prSt = con.prepareStatement(deleteSQL);
prSt.setInt(2, 101);
prSt.executeUpdate();
System.out.println("Record is deleted!");

} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
try{
if(prSt != null) prSt.close();
if(con != null) con.close();
} catch(Exception ex){}
}
}
}

Write a Java program using Servlet which accept color name from user and
change the background color of page.
Change background color using servlet
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ColorServlet extends HttpServlet


{
public void doGet(HttpServletRequest req,HttpServletResponse res)throws
IOException,ServletException
{
res.setContentType("Text/Html");
String c=req.getParameter("color");
PrintWriter pw=res.getWriter();
if(c.equals("red"))
pw.println("<body BGCOLOR=red>");
if(c.equals("green"))
pw.println("<body BGCOLOR=green>");
if(c.equals("green"))
pw.println("<body BGCOLOR=green>");

if(c.equals("blue"))
pw.println("<body BGCOLOR=blue>");
if(c.equals("yellow"))
pw.println("<body BGCOLOR=yellow>");
if(c.equals("black"))
pw.println("<body BGCOLOR=black>");
pw.println("<center><h2>The selected color is:"+c+"</h2></center>");;
pw.close();

}
}

HTML code
<HTML>
<HEAD>
<TITLE>
Color Change
</TITLE>
</HEAD>
<BODY>
<FORM method=get
action="http://127.0.0.1:8080/examples/servlets/servlet/ColorServlet">
<CENTER>
Select Color :
<select name="color" id="color">
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
<option value="yellow">yellow</option>
<option value="black">Black</option>
</Select>
<input type="submit" value="Submit">
</FORM>
</BODY>
</HTML>

Write a Java Socket program that runs on a server & echo back all the strings
sent by a client. If the client sends a string Exit the server program should
terminate.

Server java file : SocketServerExample


-------------------------------------------
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.ClassNotFoundException;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketServerExample {

//static ServerSocket variable


private static ServerSocket server;
//socket server port on which it will listen
private static int port = 9876;

public static void main(String args[]) throws IOException,


ClassNotFoundException{
//create the socket server object
server = new ServerSocket(port);
//keep listens indefinitely until receives 'exit' call or program terminates
while(true){
System.out.println("Waiting for client request");
//creating socket and waiting for client connection
Socket socket = server.accept();
//read from socket to ObjectInputStream object
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
//convert ObjectInputStream object to String
String message = (String) ois.readObject();
System.out.println("Message Received: " + message);
//create ObjectOutputStream object
ObjectOutputStream oos = new
ObjectOutputStream(socket.getOutputStream());
//write object to Socket
oos.writeObject("Hi Client "+message);
//close resources
ois.close();
oos.close();
socket.close();
//terminate the server if client sends exit request
if(message.equalsIgnoreCase("exit")) break;
}
System.out.println("Shutting down Socket server!!");
//close the ServerSocket object
server.close();
}

Client java file : SocketClientExample


-------------------------------------------------
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class SocketClientExample {


public static void main(String[] args) throws UnknownHostException,
IOException, ClassNotFoundException, InterruptedException{
//get the localhost IP address, if server is running on some other IP, you need
to use that
InetAddress host = InetAddress.getLocalHost();
Socket socket = null;
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
for(int i=0; i<5;i++){
//establish socket connection to server
socket = new Socket(host.getHostName(), 9876);
//write to socket using ObjectOutputStream
oos = new ObjectOutputStream(socket.getOutputStream());
System.out.println("Sending request to Socket Server");
if(i==4)oos.writeObject("exit");
else oos.writeObject(""+i);
//read the server response message
ois = new ObjectInputStream(socket.getInputStream());
String message = (String) ois.readObject();
System.out.println("Message: " + message);
//close resources
ois.close();
oos.close();
Thread.sleep(100);
}
}
}

Write a Menu-driven program which will perform the following options on


Customer (custno, custname, address) database.
1) Insert
2) Update
3) Delete
4) Search
Raise exception if negative data is entered for custno.

import java.sql.*;
import java.io.*;
import javax.sql.*;

class MenuDriven
{
public static void main(String args[])
{
Connection con;
Statement state;
ResultSet rs;
int ch;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("Driver Loaded");
con=DriverManager.getConnection("jdbc:odbc:zzz");
System.out.println("Statement object created");

do
{
System.out.println("\n");
System.out.println("Menu:");
System.out.println("1.Insert Record into the Table");
System.out.println("2.Update The Existing Record.");
System.out.println("3.Display all the Records from the Table");
System.out.println("4.Exit");
System.out.println("Enter your choice: ");

BufferedReader br=new BufferedReader(new


InputStreamReader(System.in));
ch=Integer.parseInt(br.readLine());
if(ch < 0)
System.out.println("You have entered Negative Number .
Kinldy enter number between 1 to 4 ");
else{
switch(ch)
{
case 1:
System.out.println("Enter Customer Number: ");
int no=Integer.parseInt(br.readLine());
System.out.println("Enter Customer Name: ");
String name=br.readLine();
System.out.println("Enter Customer Address: ");
String add=br.readLine();
String sql="insert into customer values(?,?,?)";
PreparedStatement p=con.prepareStatement(sql);
p.setInt(1,no);
p.setString(2,name);
p.setInt(3,add);
p.executeUpdate();
System.out.println("Record Added");
//p.close();
//con.close();
break;

case 2:
System.out.println("Enter Customer Number for the record you wish
to Update: ");
no=Integer.parseInt(br.readLine());
System.out.println("Enter new Name for Existing Customer: ");
name=br.readLine();
System.out.println("Enter new address: ");
add=br.readLine();
sql="update employee set custname=?, address=? where custno=?";
p=con.prepareStatement(sql);
p.setString(1,name);
p.setString(2,add);
p.setInt(3,no);
p.executeUpdate();
System.out.println("Record Updated");
//p.close();
//con.close();
break;

case 3:
state=con.createStatement();
sql="select * from customer";
rs=state.executeQuery(sql);
while(rs.next())
{
System.out.println("\n");
System.out.print("\t" +rs.getInt(1));
System.out.print("\t" +rs.getString(2));
System.out.print("\t" +rs.getInt(3));
}
break;

case 4:
System.exit(0);

default:
System.out.println("Invalid Choice");
break;
}
}
}while(ch!=4);

}catch(Exception e)
{
System.out.println(e);
}
}
}

Write a SDK program to create menu like this: File Edit View Font. Display
proper message on clicking particular menu item

void MyForm::InitializeMenuBar()
{
auto self = As<MyForm>();
auto fileNewMenuItem = make_component<TextMenuItem>(self,L"&New");
auto fileOpenMenuItem = make_component<TextMenuItem>(self,L"&Open");
auto fileSaveMenuItem = make_component<TextMenuItem>(self,L"&Save");
auto fileSeparator = make_component<SeparatorMenuItem>(self);
auto fileExitMenuItem = make_component<TextMenuItem>(self,L"E&xit");

fileNewMenuItem->OnClick.connect([&](MenuItem*){ text = L"New


selected"; InvalidateRect(); });
fileOpenMenuItem->OnClick.connect([&](MenuItem*){ text = L"Open
selected"; InvalidateRect(); });
fileSaveMenuItem->OnClick.connect([&](MenuItem*){ text = L"Save
selected"; InvalidateRect(); });
fileExitMenuItem->OnClick.connect([&](MenuItem*){ Close(); });

auto fileSubMenu = make_component<SubMenuItem>(self,L"&File");

fileSubMenu->Add(fileNewMenuItem);
fileSubMenu->Add(fileOpenMenuItem);
fileSubMenu->Add(fileSaveMenuItem);
fileSubMenu->Add(fileSeparator);
fileSubMenu->Add(fileExitMenuItem);

auto editSubMenu = make_component<SubMenuItem>(self,L"&Edit");

auto editCutMenuItem = editSubMenu->AddMenuItem(L"Cu&t");


auto editCopyMenuItem = editSubMenu->AddMenuItem(L"&Copy");
auto editPasteMenuItem = editSubMenu->AddMenuItem(L"&Paste");
editCutMenuItem->OnClick.connect([&](MenuItem*){ text = L"Cut selected";
InvalidateRect(); });
editCopyMenuItem->OnClick.connect([&](MenuItem*){ text = L"Copy
selected"; InvalidateRect(); });
editPasteMenuItem->OnClick.connect([&](MenuItem*){ text = L"Paste
selected"; InvalidateRect(); });

auto viewSubMenu = make_component<SubMenuItem>(self,L"&View");


auto viewTime = viewSubMenu->AddMenuItem(L"&Time");
viewTime->OnClick.connect([&](MenuItem*)
{
DateTime now = DateTime::Now();
if(now.IsDaylightSavingTime())
{
text = now.ToString() + L" Daylight saving time";
}
else
{
text = now.ToString() + L" Standard time";
}
InvalidateRect();
});
auto menuBar = make_component<MenuBar>(self);

menuBar->Add(fileSubMenu);
menuBar->Add(editSubMenu);
menuBar->Add(viewSubMenu);

SetMenu(menuBar);
}

Write a client-server program which displays the server machines date and
time on the client machine.

DateClient.java

import java.io.*;
import java.net.*;
class DateClient
{
public static void main(String args[]) throws Exception
{
Socket soc=new Socket(InetAddress.getLocalHost(),5217);
BufferedReader in=new BufferedReader(new
InputStreamReader(soc.getInputStream() ));
System.out.println(in.readLine());
}
}

DateServer.java

import java.net.*;
import java.io.*;
import java.util.*;
class DateServer
{
public static void main(String args[]) throws Exception
{
ServerSocket s=new ServerSocket(5217);
while(true)
{
System.out.println("Waiting For Connection ...");
Socket soc=s.accept();
DataOutputStream out=new DataOutputStream(soc.getOutputStream());
out.writeBytes("Server Date: " + (new Date()).toString() + "\n");
out.close();
soc.close();
}
}
}
Write a JAVA program which will generate following threads
To display 10 terms of Fibonacci series.
To display 1 to 20 in reverse order

import java.io.*;
class fib extends Thread

{
public void run()
{
try

int a=0,b=1,c=0;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the Limit");
int n=Integer.parseInt(br.readLine());
System.out.println("Fibonacci series:");
while(n>0)
{
System.out.println(c);
a=b;
b=c;
c=a+b;
n=n-1;
}
}
catch(Exception e)
{
}
}
}
class rev extends Thread
{
public void run()
{
try
{
System.out.println("Reverse is");
for(int i=20;i>=1;i--)
System.out.println(i);
}

catch(Exception e)
{
}
}
}
class s16
{
public static void main(String args[])
{
try
{
fib t1=new fib();
t1.start();
t1.sleep(5000);
rev t2=new rev();
t2.start();
}
catch(Exception e)
{
}
}
}

Create an Html page that contains 4 option buttons Java, UNIX, DDBMS,
OOSE and 2 buttons Submit and Reset. When the user clicks on Submit
button the server responds by adding cookie containing the selected Subject
and sends the html page to the client. Program should not allow duplicate
cookie to be written.

index.html

<!doctype html>
<head>
<title>CookiesExample</title>
</head>
<body>
<form method='post' action='servlet/cookies'>
<fieldset style="width:14%; background-color:#ccffcc">
<h2>Select Course</h2> <hr>
<input type='radio' name='course' value='Java'>Java<br>
<input type='radio' name='course' value='UNIX'>UNIX<br>
<input type='radio' name='course' value='MCA'>DBMS<br>
<input type='radio' name='course' value='OOSE '>OOSE<br><br>
<input type='submit'> <input type='reset'><br>
</fieldset>
</form>
</body>
</html>

AddCookie.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class AddCookie extends HttpServlet
{
public void doPost(HttpServletRequest req, HttpServletResponse res) throws
ServletException,IOException
{
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
Cookie []c = req.getCookies();
int id=1;
if(c!=null) id = c.length+1;
String value = req.getParameter("course");
Cookie newCookie = new Cookie("course:"+id,value);
res.addCookie(newCookie);
pw.println("<h4>Cookie added with value "+value+"</h4>");
}

web.xml

<web-app>
<servlet>
<servlet-name>AddCookie</servlet-name>
<servlet-class>AddCookie</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AddCookie</servlet-name>
<url-pattern>/servlet/cookies</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>

Write a JSP program to design a Login Screen which checks the username
and password. If valid then the user is allowed to login otherwise it should
display some error message

Login Form :
========================
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Login Page</h1>
<center>
<h2>Signup Details</h2>
<form action="LoginCheck.jsp" method="post">
<br/>Username:<input type="text" name="username">
<br/>Password:<input type="password" name="password">
<br/><input type="submit" value="Submit">
</form>
</center>
</body>
</html>

LoginCheck.jsp
=========================
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
String username=request.getParameter("username");
String password=request.getParameter("password");

if((username.equals("admin") && password.equals("admin")))


{
session.setAttribute("username",username);
response.sendRedirect("Home.jsp");
}
else
response.sendRedirect("Error.jsp");
%>
</body>
</html>

Write a java program to display the Records of Doctor (DNo, DName, Salary)
from the database and display on screen(use AWT).

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import java.sql.*;

class one extends JFrame implements ActionListener


{

JFrame f;
JLabel l1,l2,l3;
JTextField t1,t2,t3;
JButton b1,b2;
one()
{
f=new JFrame("slp5");
l1=new JLabel("dno");
l2=new JLabel("dname");
l3=new JLabel("salary");
t1=new JTextField(15);
t2=new JTextField(15);
t3=new JTextField(15);
b1=new JButton("Insert ");
b2=new JButton("clear ");
f.setLayout(new FlowLayout());
f.setVisible(true);
f.setSize(300,300);
b1.addActionListener(this);
b2.addActionListener(this);
f.add(l1);
f.add(t1);
f.add(l2);
f.add(t2);
f.add(l3);
f.add(t3);
f.add(b1);
f.add(b2);
}

public void actionPerformed(ActionEvent e)


{
if(e.getSource()==b1)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
con=DriverManager.getConnection("jdbc:odbc:emp");
Statement stmt=con.createStatement();

String name=t2.getText();
int eno=Integer.parseInt(t1.getText());
int sal=Integer.parseInt(t3.getText());
String sql="insert into emp values(";
sql=sql+dno+",'"+name+"',"+sal+")";
System.out.println(sql);
int i=stmt.executeUpdate(sql);
if(i>0)
{
System.out.println("record added ");
}
con.close();
}//try close
catch(Exception a)
{
}
}

if(e.getSource()==b2)
{
t1.setText("");
t2.setText("");
t3.setText("");
}
}//action performed close
}//one close

class slp1
{
public static void main(String args[])
{
one o=new one();
}
}

Write a Servlet program that accepts the age and name from and display
message whether user is eligible for voting or not.

//VoterId.java

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class VoterId extends HttpServlet {


protected void doGet(HttpServletRequest req, HttpServletResponse resp)hrows
ServletException, IOException
{
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
String name = req.getParameter("vname");
int age = Integer.parseInt(req.getParameter("vage"));
f (18<=age)
{
out.print("<fontcolor='green'> <h1> hi "+name+" You have a right to elect the
people</h1></font>");

} else {
out.print("<fontcolor='red'> <h1>Sorry "+name+" you have to wait for upto 18
age</h1></font>");
}
out.print("<align=right><img src='images/HARISHKUMAR.jpg' width=100
height=100 >");
}

//web.xml
<web-app>
<servlet>
<servlet-name>hai</servlet-name>
<servlet-class>com.nareshit.voterid.VoterId</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hai</servlet-name>
<url-pattern>/hai</url-pattern>
</servlet-mapping>

</web-app>

//home.html
<!DOCTYPE html>
<html>
<head>
<title>Voter Id Verification</title>
</head>
<body>
<center>
<table>
<form action="./hai" method="get">
<tr>
<td>Name :</td>
<td><input type="text" name="vname" /></td>
</tr>
<tr>
<td>Age :</td>
<td><input type="text" name="vage" /></td>
<tr><td><center><input type="submit" value="Submit"></center></td></tr>
</form>
</table>
<center>
</body>
</html>

Write a JAVA program to accept the details of Doctor (Dno, DName, Salary)
from the user and insert it into the database. (Use PreparedStatement class).

import java.awt.*;
import java.sql.*;
import javax.swing.*;
import java.awt.event.*;

class cre
{
public static void main(String []args)
{
Frame f=new Frame();
Label label1=new Label("D No:");
Label label2=new Label("DName:");
Label label3=new Label("Salary:");

final TextField text1=new TextField(20);


final TextField text2=new TextField(20);
final TextField text3=new TextField(20);

Button b=new Button("Save");


b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
int v1=Integer.parseInt(text1.getText());
String v2=text2.getText();
int v3=Integer.parseInt(text3.getText());

try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:my1dsn.dsn");
String sql="insert into doctor(dno,dname,salary)values(?,?,?)";
PreparedStatement pst=con.prepareStatement(sql);

pst.setInt(1,v1);
pst.setString(2,v2);
pst.setInt(3,v3);
pst.executeUpdate();
JOptionPane.showMessageDialog(null,"Data is inserted successfully");
}
catch(Exception ex)
{ System.out.println(ex);
}}});
Panel p=new Panel(new GridLayout(5,2));
p.add(label1);
p.add(text1);
p.add(label2);
p.add(text2);
p.add(label3);
p.add(text3);
p.add(b);
f.add(p);
f.setVisible(true);
f.pack();
}
}

Write a SDK program to Create a cursor and icon.

ICONDEMO.C

#include <windows.h>
#include "resource.h"
LRESULT CALLBACK WndProc (HWND, UINT, WPARAM, LPARAM) ;

int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance,


PSTR szCmdLine, int iCmdShow)
{
TCHAR szAppName[] = TEXT ("IconDemo") ;
HWND hwnd ;
MSG msg ;
WNDCLASS wndclass ;

wndclass.style = CS_HREDRAW | CS_VREDRAW ;


wndclass.lpfnWndProc = WndProc ;
wndclass.cbClsExtra = 0 ;
wndclass.cbWndExtra = 0 ;
wndclass.hInstance = hInstance ;
wndclass.hIcon = LoadIcon (hInstance, MAKEINTRESOURCE
(IDI_ICON)) ;
wndclass.hCursor = LoadCursor (NULL, IDC_ARROW) ;
wndclass.hbrBackground = GetStockObject (WHITE_BRUSH) ;
wndclass.lpszMenuName = NULL ;
wndclass.lpszClassName = szAppName ;
if (!RegisterClass (&wndclass))
{
MessageBox (NULL, TEXT ("This program requires Windows NT!"),
szAppName, MB_ICONERROR) ;
return 0 ;
}

hwnd = CreateWindow (szAppName, TEXT ("Icon Demo"),


WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT,
CW_USEDEFAULT, CW_USEDEFAULT,
NULL, NULL, hInstance, NULL) ;

ShowWindow (hwnd, iCmdShow) ;


UpdateWindow (hwnd) ;

while (GetMessage (&msg, NULL, 0, 0))


{
TranslateMessage (&msg) ;
DispatchMessage (&msg) ;
}
return msg.wParam ;
}

LRESULT CALLBACK WndProc (HWND hwnd, UINT message, WPARAM


wParam, LPARAM lParam)
{
static HICON hIcon ;
static int cxIcon, cyIcon, cxClient, cyClient ;
HDC hdc ;
HINSTANCE hInstance ;
PAINTSTRUCT ps ;
int x, y ;

switch (message)
{
case WM_CREATE :
hInstance = ((LPCREATESTRUCT) lParam)->hInstance ;
hIcon = LoadIcon (hInstance, MAKEINTRESOURCE (IDI_ICON)) ;
cxIcon = GetSystemMetrics (SM_CXICON) ;
cyIcon = GetSystemMetrics (SM_CYICON) ;
return 0 ;

case WM_SIZE :
cxClient = LOWORD (lParam) ;
cyClient = HIWORD (lParam) ;
return 0 ;

case WM_PAINT :
hdc = BeginPaint (hwnd, &ps) ;

for (y = 0 ; y < cyClient ; y += cyIcon)


for (x = 0 ; x < cxClient ; x += cxIcon)
DrawIcon (hdc, x, y, hIcon) ;

EndPaint (hwnd, &ps) ;


return 0 ;
case WM_DESTROY :
PostQuitMessage (0) ;
return 0 ;
}
return DefWindowProc (hwnd, message, wParam, lParam) ;
}

Write a Java Socket program that runs on a server & echoe back all the
strings sent by a client. If the client sends a string Exit the server program
should terminate.

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Server


{

private static Socket socket;

public static void main(String[] args)


{
try
{

int port = 25000;


ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server Started and listening to the port 25000");

//Server is running always. This is done using this while(true) loop


while(true)
{
//Reading the message from the client
socket = serverSocket.accept();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String number = br.readLine();
System.out.println("Message received from client is "+number);

//Multiplying the number by 2 and forming the return message


String returnMessage;
try
{
int numberInIntFormat = Integer.parseInt(number);
int returnValue = numberInIntFormat*2;
returnMessage = String.valueOf(returnValue) + "\n";
}
catch(NumberFormatException e)
{
//Input was not a number. Sending proper message back to client.
returnMessage = "Please send a proper number\n";
}

//Sending the response back to the client.


OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage);
System.out.println("Message sent to the client is "+returnMessage);
bw.flush();
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
try
{
socket.close();
}
catch(Exception e){}
}
}
}

Client java

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;

public class Client


{

private static Socket socket;

public static void main(String args[])


{
try
{
String host = "localhost";
int port = 25000;
InetAddress address = InetAddress.getByName(host);
socket = new Socket(address, port);

//Send the message to the server


OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);

String number = "2";

String sendMessage = number + "\n";


bw.write(sendMessage);
bw.flush();
System.out.println("Message sent to the server : "+sendMessage);

//Get the return message from the server


InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String message = br.readLine();
System.out.println("Message received from the server : " +message);
}
catch (Exception exception)
{
exception.printStackTrace();
}
finally
{
//Closing the socket
try
{
socket.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

Define a thread called PrintText_Thread for printing text on command


prompt for n number of times. Create two threads and run them. Pass the text
and n as parameters to the thread constructor. For Example:
1. First Thread prints text as Gate way Of India for 10 Times
2. Second Thread prints text as India Gate for 20 times

import java.io.*;
import java.lang.String.*;

class India extends Thread


{
String msg="";
int n;
India(String msg,int n)
{
this.msg=msg;
this.n=n;
}
public void run()
{
try
{ for(int i=1;i<=n;i++)
{
System.out.println(msg+" "+i+" times");
}
}
catch(Exception e){}
}
}
public class City
{
public static void main(String a[])
{
int n=Integer.parseInt(a[0]);
India t1=new Ass_seta3("Gate way Of India",n);
t1.start();
India t2=new Ass_seta3("India Gate",n+20);
t2.start();
}
}

Write a JAVA program which will create two child threads by implementing
Runnable interface, one thread will print even nos. from 1 to 50 and other
display odd nos.

import java.io.*;
import java.util.*;

public class EvenOdd implements Runnable


{
int i,j;
Thread t1, t2;
public EvenOdd()
{
t1=new Thread(this,"Even");
System.out.println("EVEN NUMBER'S ARE");
t1.start();

t2=new Thread(this,"Odd");
System.out.println("ODD NUMBER'S ARE");
t2.start();
}
public void run()
{
try
{
for(i=2;i<=50;i=i+2)
{
System.out.print(" " + "\t" +i);
}
System.out.println();

for(j=1;j<=50;j=j+2)
{
System.out.print(" " + "\t" +j);
}
System.out.println();
}
catch(Exception oo)
{
System.out.println(oo);
}
}
}

class OddEven
{
public static void main(String args[])
{
try
{
EvenOdd s=new EvenOdd();
}
catch(Exception obj)
{
System.out.println(obj);
}

Write a java program to accept the details of Product (Pno, PName, Price,
qty) from the user and insert it into the Database.(use Awt).

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.sql.*;

public class Product extends Frame implements ActionListener


{
Label l1,l2,l3,l4;
TextField t1,t2,t3,t4;
Button b;
Connection cn;
Statement st;
ResultSet rs;

public Product()
{
setLayout(null);
l1=new Label("P_No");
l2=new Label("P_Name");
l3=new Label("P_Price");
l4=new Label("P_Qty");
t1=new TextField();
t2=new TextField();
t3=new TextField();
t4=new TextField();
b=new Button("Save");
l1.setBounds(50,50,100,30);
t1.setBounds(160,50,100,30);

l2.setBounds(50,90,100,30);
t2.setBounds(160,90,100,30);

l3.setBounds(50,130,100,30);
t3.setBounds(160,130,100,30);

l4.setBounds(50,170,100,30);
t4.setBounds(160,170,100,30);

b.setBounds(50,210,100,30);

add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(t3);
add(b);
b.addActionListener(this);

setSize(500,500);
setVisible(true);

addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
}

public void actionPerformed(ActionEvent oe)


{
String str=oe.getActionCommand();
if(str.equals("Save"))
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
cn=DriverManager.getConnection("jdbc:odbc:Practical","","");
st =cn.createStatement();

int p_no=Integer.parseInt(t1.getText());
String p_name=t2.getText();
int p_price=Integer.parseInt(t3.getText());
int p_qty=Integer.parseInt(t4.getText());

String strr="insert into emp values(" + p_no + " ,'" + p_name + "'," +
p_price + " , " + p_qty + ")";
int k=st.executeUpdate(strr);
if(k>0)
{

JOptionPane.showMessageDialog(null,"Record Is Added");
}
}
catch(Exception er)
{
System.out.println("Error");
}
}
}
public static void main(String args[])
{
new Product().show();
}
}

Write a JSP program that accepts the registration details from user and
display the details on the next page.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="registrationaction.jsp">
Registration Form<br />

First Name : <input type="text" name="fname" /> <br />


Last Name : <input type="text" name="lname" /> <br />
Age : <input type="text" name="age" /> <br />
Gender : <input type="radio" name="gender" value="Male" checked />Male
<input type="radio" name="gender" value="Female" />Female <br />
Mobile No : <input type="text" name="mobile" /> <br />

<input type="submit" value="submit" />


</form>
</body>
</html>

ACTION:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String fname=request.getParameter("fname");
String lname=request.getParameter("lname");
String age=request.getParameter("age");
String gender=request.getParameter("gender");
String mobile=request.getParameter("mobile");
out.println("First Name : " + fname + "<br />");
out.println("Last Name : " + lname + "<br />");
out.println("Age : " + age + "<br />");
out.println("Gender : " + gender + "<br />");
out.println("Mobile No : " + mobile + "<br />");
%>
</body>
</html>

Write a client-server program which displays the server machines date and
time on the client machine.

DateClient.java

import java.io.*;
import java.net.*;
class DateClient
{
public static void main(String args[]) throws Exception
{
Socket soc=new Socket(InetAddress.getLocalHost(),5217);
BufferedReader in=new BufferedReader(new
InputStreamReader(soc.getInputStream() ));
System.out.println(in.readLine());
}
}

DateServer.java

import java.net.*;
import java.io.*;
import java.util.*;
class DateServer
{
public static void main(String args[]) throws Exception
{
ServerSocket s=new ServerSocket(5217);
while(true)
{
System.out.println("Waiting For Connection ...");
Socket soc=s.accept();
DataOutputStream out=new
DataOutputStream(soc.getOutputStream());
out.writeBytes("Server Date: " + (new Date()).toString() + "\n");
out.close();
soc.close();
}
}
}
Output:

First compile the client code on console and then compile the server code on
different console.
Run the server code, after that client code. Now the client console shows the
time and date of server machine.
Server Date: Fri Apr 16 17:05:42 IST 2017
Write a Java program to display Movie(moviename,actorname,release-year)
details specified by the user using jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="actoraction.jsp">
Actor<br />

Actor Name : <input type="text" name="name" /> <br />


Age : <input type="text" name="age" /> <br />
Gender : <input type="radio" name="gender" value="Male" checked />Male
<input type="radio" name="gender" value="Female" />Female <br />
Latest Movie Name : <input type="text" name="movie" /> <br />

<input type="submit" value="submit" />


</form>
</body>
</html>

ACTION:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String name=request.getParameter("name");
String age=request.getParameter("age");
String gender=request.getParameter("gender");
String movie=request.getParameter("movie");

out.println("Actor Name : " + name + "<br />");


out.println("Age : " + age + "<br />");
out.println("Gender : " + gender + "<br />");
out.println("Latest Movie Name : " + movie + "<br />");
%>
</body>
</html>
Create a JSP page which accepts a number from the user, and on submit
button, calculates the factorial of the number and displays it.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="factorialaction.jsp">
Factorial<br />

Enter No : <input type="text" name="no" /> <br />

<input type="submit" value="submit" />


</form>
</body>
</html>

ACTION:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
int c, fact = 1;

int no=Integer.parseInt(request.getParameter("no"));

if ( no < 0 )
out.println("Number should be non-negative.");
else
{
for ( c = 1 ; c <= no ; c++ )
fact = fact*c;

out.println("Factorial of "+no+" is = "+fact);


}
%>
</body>
</html>
Create a JSP page to accept a number from the user and display it in
words:
Example: 123 One Two Three.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="noaction.jsp">
Number in words<br />

Enter No : <input type="text" name="no" /> <br />

<input type="submit" value="submit" />


</form>
</body>
</html>

ACTION:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
int no = Integer.parseInt(request.getParameter("no"));

out.println(no + "<br />");

String intStringValue = new Integer(no).toString();

for( char c : intStringValue.toCharArray() ) {


int digit = Integer.parseInt(new String(new char[] {c}));

switch(digit){
case 0: out.print("zero "); break;
case 1: out.print("one "); break;
case 2: out.print("two "); break;
case 3: out.print("three "); break;
case 4: out.print("four "); break;
case 5: out.print("five "); break;
case 6: out.print("six "); break;
case 7: out.print("seven "); break;
case 8: out.print("eight "); break;
case 9: out.print("nine "); break;
}
}

%>
</body>
</html>

Anda mungkin juga menyukai