Uploaded by dakshgoti6071

AJAVA LAB MANUAL - Solutions

advertisement
S.T.B.S. COLLEGE OF DIPLOMA ENGG. SURAT – 6
COMPUTER DEPARTMENT
Experiment List-DEC 2014 to APR 2015
SUBJECT :AJAVA
CODE:
FACULTY:-
DIVISION:-1261-CE
3360701
`
Sr. No.
Practical Exercises
1
Write an applet that draws a circle. The dimension of the applet should be 500 X 300 pixels. The
circle should be centered in the applet and have a radius of 100 pixels. Display your name
centered in a circle.
(using drawOval() method)
import java.applet.Applet;
import java.awt.*;
public class OvalWithMyName extends Applet
{
public void paint(Graphics d)
{
d.setColor(Color.red);
d.fillOval(100,100,400,400);
d.setColor(Color.white);
d.setFont(new Font("serif",Font.BOLD,20));
d.drawString("PRATIKSHA",300,300);
}
}
2
Draw ten red circles in a vertical column in the center of the applet.
import java.applet.*;
import java.awt.*;
/*<applet code="FiveOval.class" height="400" width="400">
</applet>*/
public class FiveOval extends Applet
{
public void paint(Graphics g)
{
int a=20,b=20;
for(int i=0;i<10;i++)
{
g.setColor(Color.red);
g.drawOval(a,b,50,50);
b=b+50;
}
}
}
3
Built an applet that displays a horizontal rectangle in its center. Let the rectangle fill with color
from left to right.
import
import
import
import
java.awt.*;
java.applet.*;
java.awt.Event;
java.awt.event.*;
/*
<applet code="Pract5.class" width=500 height=500></applet>
*/
public class Pract5 extends Applet implements Runnable
{
Thread t=new Thread(this);
public void init()
{
}
public void paint(Graphics G)
{
for(int i=0;i<=4;i++)
{
try
{
G.fillRect(100, 100, 50*i, 200);
Thread.sleep(1000);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
@Override
public void run() {
// TODO Auto-generated method stub
}
}
4
Write an applet that displays the position of the mouse at the upper left corner of the applet
when it is dragged or moved. Draw a 10x10 pixel rectangle filed with black at the current mouse
position.
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class Pract4 extends Applet implements MouseMotionListener
{
int x=0,y=0;
public void paint(Graphics G)
{
G.drawRect(x, y , 10, 10);
G.drawString("x=" +x +" Y="+y, x, y)
}
public void init()
{
addMouseMotionListener(this);
}
public void mouseMoved(MouseEvent me)
{
x=me.getX();
y=me.getY();
showStatus("x=" +x +"
repaint();
Y="+y);
}
public void mouseDragged(MouseEvent me)
{
}
}
5
Write an applet that contains one button. Initialize the label on the button to “start”, when the
user presses the button change the label between these two values each time the button is
pressed.
import
import
import
import
java.io.*;
java.awt.*;
java.applet.*;
java.awt.event.*;
public class Pract5a extends Applet implements ActionListener
{
Button B=new Button("START");
public void init()
{
add(B);
B.addActionListener(this);
}
public void paint()
{
}
public void actionPerformed(ActionEvent Ae)
{
if(B.getLabel()=="START")
{
B.setLabel("STOP");
}
else
{
B.setLabel("START");
}
}
}
6
Write an applet that uses the mouse listener, which overrides only two methods which are
mousePressed and mouseReleased.
import
import
import
import
java.io.*;
java.applet.*;
java.awt.*;
java.awt.event.*;
public class Pract6b extends Applet
{
public void init()
{
addMouseListener(new MouseAdapter()
{
@Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
super.mouseEntered(arg0);
setBackground(Color.BLUE);
}
@Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
super.mouseExited(arg0);
setBackground(Color.BLACK);
}
});
}
}
7
Write a program that has only one button in the frame, clicking on the button cycles through
the colors: red->green->blue-> and so on.one color change per click.(use getBackground()
method to get the current color)
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class Pract7a extends Applet implements ActionListener
{
Button button ;
public void init()
{
button =new Button("RED");
add(button);
button.addActionListener(this);
}
public void paint(Graphics G)
{
}
public void actionPerformed(ActionEvent AE)
{
if(getBackground()==Color.red)
{
setBackground(Color.green);
button.setLabel("Blue");
}
else if(getBackground()==Color.green)
{
setBackground(Color.blue);
button.setLabel("RED");
}
else
{
setBackground(Color.red);
button.setLabel("GREEN");
}
}
}
8
Write an applet that contains three check boxes and 30 x 30 pixel canvas. The three checkboxes
should be labeled “Red”, “Green”, “Blue”. The selection of the check boxes determines the color
of the canvas. For example, if the user selects both “Red” and “Blue”, the canvas should be
purple.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*<applet height='300' width='300' code='CheckBoxColor' >
</applet>*/
public class CheckBoxColor extends Applet implements ItemListener
{
Checkbox ch1,ch2,ch3;
public void init()
{
ch1=new Checkbox("Red");
ch2=new Checkbox("Green");
ch3=new Checkbox("Blue");
add(ch1);
add(ch2);
add(ch3);
ch1.addItemListener(this);
ch2.addItemListener(this);
ch3.addItemListener(this);
}
public void itemStateChanged(ItemEvent e)
{
repaint();
}
public void paint(Graphics g)
{
if(ch1.getState())
{
g.setColor(Color.RED);
}
if(ch2.getState())
{
g.setColor(Color.GREEN);
}
if(ch3.getState())
{
g.setColor(Color.BLUE);
}
if(ch1.getState() && ch2.getState())
{
g.setColor(new Color(255,255,0));
}
if(ch1.getState() && ch3.getState())
{
g.setColor(new Color(255,0,255));
}
if(ch2.getState() && ch3.getState())
{
g.setColor(new Color(0,255,255));
}
if(ch1.getState() && ch2.getState() && ch3.getState())
{
g.setColor(new Color(255,255,255));
}
if(!ch1.getState() && !ch2.getState() && !ch3.getState())
{
g.setColor(new Color(0,0,0));
}
g.fillRect(10,10,100,100);
}
}
9
Create an application that displays a frame with a menu bar. When a user selects any menu or
menu item, display that selection on a text area in the center of the frame
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class Pract8 extends Applet implements ActionListener
{
Frame f=new Frame();
MenuItem i1,i2,i3;
MenuBar mb=new MenuBar();
Menu file=new Menu("File");
Menu edit=new Menu("Edit");
public void init()
{
// create a menubar with some menuitems
f.setMenuBar(mb);
mb.add(file);
mb.add(edit);
file.add(i1=new MenuItem("Open"));
file.add(i2=new MenuItem("Close"));
f.setSize(250,250);
f.setVisible(true);
i1.addActionListener(this);
i2.addActionListener(this);
}
public void paint(Graphics gh)
{
}
@Override
public void actionPerformed(ActionEvent ae)
{
// TODO Auto-generated method stub
if(ae.getSource()==i1)
{
showStatus("Open Pressed");
}
if(ae.getSource()==i2)
{
showStatus("Close Pressed");
}
}
}
10
Write an applet that draws two sets of ever-decreasing rectangles one in outline form and one
filled alternately in black and white.
import java.io.*;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code="Pract10.class width=1000 height=1000></applet>"
*/
public class Pract10 extends Applet implements Runnable {
int x = 10, y = 10,i=0;
Thread T = new Thread();
public void paint(Graphics G)
{
for (i = 1; i <=10; i++)
{
x=10*i;
y=10*i;
try {
if(i%2==0)
{
G.setColor(Color.black);
G.fillRect(25+x, 25+y, 250-x*2,250-y*2 );
}
else
{
G.setColor(Color.white);
G.fillRect(25+x, 25+y, 250-x*2,250-y*2);
}
Thread.sleep(200);
} catch (Exception se) {
}
}
repaint();
}
@Override
public void run()
{
// TODO Auto-generated method stub
}
}
11
Write a database application that use any JDBC driver
import java.sql.*;
public class Serv_DB extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
PrintWriter out=response.getWriter();
Connection conn=null;
Statement st=null;
ResultSet rs=null;
try
{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:mysql://localhost:3308/servlet",
"root","root");
st=conn.createStatement();
}
catch (ClassNotFoundException | SQLException e)
{
e.printStackTrace();
}
}
12
Develop a UI that performs the following SQL operations:1) Insert 2)Delete 3)Update.
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 java.sql.*;
public class Serv_DB extends HttpServlet
{
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
String name=request.getParameter("name");
String pass=request.getParameter("email");
PrintWriter out=response.getWriter();
out.println("Username = " +name);
out.println("Username = " +pass);
Connection conn=null;
Statement st=null;
ResultSet rs=null;
try
{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:mysql://localhost:3308/servlet","root","root");
st=conn.createStatement();
String sql ="Insert into login(Username,Password) values('"+name+"','"+pass+"')";
int x= st.executeUpdate(sql);
if(x>0)
{
out.println("Data inserted Successfully ");
}
rs=st.executeQuery("select *from login");
while(rs.next())
{
//Retrieve by column name
int id = rs.getInt("srno");
name = rs.getString("Username");
pass = rs.getString("Password");
//Display values
out.println("ID: " + id + "<br>");
out.println("First: " + name + "<br>");
out.println("Last: " + pass + "<br>");
}
String sql ="Update login set Username = “ADMIN” where ID = “1” ”;
int x= st.executeUpdate(sql);
if(x>0)
{
out.println("Data Updated Successfully ");
}
String sql ="Delete from login where ID= “5” ”;
int x= st.executeUpdate(sql);
if(x>0)
{
out.println("Data Deleted Successfully ");
}
}catch (ClassNotFoundException | SQLException e)
{
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
}
}
13
Write a program to present a set of choice for user to select a product & display the price of
product.
import java.awt.*;
import java.sql.*;
import java.awt.event.*;
public class price extends Frame implements ItemListener
{
Connection c;
ResultSet rs;
Choice ch;
TextField t1;
price()
{
setLayout(new FlowLayout(FlowLayout.LEFT));
ch=new Choice();
t1=new TextField(10);
try{
Class.forName("com.mysql.jdbc.Driver");
c=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","");
}
catch(Exception e)
{
System.out.println(e);
}
try
{
Statement st=c.createStatement();
ResultSet rs=st.executeQuery("select * from price");
while(rs.next())
{
ch.addItem(rs.getString(1));
}
}
catch(Exception e)
{
System.out.println(e);
}
ch.addItemListener(this);
add(ch);
add(t1);
setSize(300,300);
show();
}
public void itemStateChanged(ItemEvent e)
{
System.out.println("selected"+ch.getSelectedItem());
String pname=ch.getSelectedItem();
t1.setText("selected"+pname);
try
{
Statement st=c.createStatement();
ResultSet rs=st.executeQuery("select price from price where p_name="+"'"+pname+"'");
while(rs.next())
{
t1.setText(String.valueOf(rs.getInt(1)));
}
}
//System.out.println("selected"+pname);
catch(Exception l)
{
System.out.println(l);
}
}
public static void main(String args[])
{
new price();
}
}
14
Write a simple servlet program which maintains a counter for the number of times it has been
accessed since its loading; initialize the counter using deployment descriptor.
import java.io.*;
import java.awt.*;
import java.httpservlet.*;
public class Pract14 extends HttpServlet
{
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
HttpSession session =request.getSession();
Integer access=(Integer)session.getAttribute("access");
if(access==null)
{
ServletContext conn=request.getServletContext();
access =Integer.parseInt(conn.getInitParameter("access-count"));
}
else
{
access=access + 1;
}
session.setAttribute("access", access);
PrintWriter out =response.getWriter();
out.println("Access Count"+access);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// TODO Auto-generated method stub
}
}
15
Create a form processing servlet which demonstrates use of cookies and sessions.
COOKIES
index.html
<form method="post" action="validate">
Name:<input type="text" name="user" /><br/>
Password:<input type="text" name="pass" ><br/>
<input type="submit" value="submit">
</form>
MyServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String name = request.getParameter("user");
String pass = request.getParameter("pass");
if(pass.equals("1234"))
{
Cookie ck = new Cookie("username",name);
response.addCookie(ck);
response.sendRedirect("First");
}
}
}
First.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class First extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
Cookie[] cks = request.getCookies();
out.println("Welcome "+cks[0].getValue());
}}
16
Write a simple JSP program for user Registration & then control will be transfer it into second page.
Index.html
<body>
<form method="get" action="./Serv_DB" >
Enter Name : <input type="text" name="name">
Enter Email:<input type="text" name="email">
<input type ="submit" value="Submit" >
</form>
</body>
Serv_DB.java (Servlet File)
import java.io.IOException;
import java.io.PrintWriter;
import java.servlet.*;
import java.sql.*;
public class Serv_DB extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
String name=request.getParameter("name");
String pass=request.getParameter("email");
PrintWriter out=response.getWriter();
out.println("Username = " +name);
out.println("Username = " +pass);
Connection conn=null;
Statement st=null;
ResultSet rs=null;
try
{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:mysql://localhost:3308/servlet","root","root");
st=conn.createStatement();
String sql ="Insert into login(Username,Password) values('"+name+"','"+pass+"')";
int x= st.executeUpdate(sql);
if(x>0)
{
out.println("Data inserted Successfully ");
}
rs=st.executeQuery("select *from login");
while(rs.next())
{
//Retrieve by column name
int id
= rs.getInt("srno");
name = rs.getString("Username");
pass = rs.getString("Password");
//Display values
out.println("ID: " + id + "<br>");
out.println("First: " + name + "<br>");
out.println("Last: " + pass + "<br>");
}
}
catch (ClassNotFoundException | SQLException e)
{
e.printStackTrace();
out.println("Connection not Succeeded");
out.println(e.getMessage().toString());
}
}
}
SESSION
index.html
<form method="post" action="Validate">
User: <input type="text" name="user" /><br/>
Password: <input type="text" name="pass" ><br/>
<input type="submit" value="submit">
</form>
Validate.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Validate extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String name = request.getParameter("user");
String pass = request.getParameter("pass");
if(pass.equals("1234"))
{
//creating a session
HttpSession session = request.getSession();
session.setAttribute("user", name);
response.sendRedirect("Welcome");
}
}
}
Welcome.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Welcome extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
HttpSession session = request.getSession();
String user = (String)session.getAttribute("user");
out.println("Hello "+user);
}
}
17
Write a simple JSP program for user login form with static & dynamic database.
Index.html
<body>
<form method="get" action="login.jsp">
User Name:
<label>
<input type="text" name="name">
</label>
<p>Password:
<label>
<input type="password" name="pass">
</label>
</p>
<p>
<label>
<input type="submit" name="Submit" value="Submit">
</label>
</p>
<p> </p>
</form>
</body>
Login-process.jsp
<%@page import="java.sql.*"%>
<%
Connection conn = null;
Statement st = null;
ResultSet rs = null;
String name = request.getParameter("name");
String pass = request.getParameter("pass");
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3308/servlet", "root", "root");
st=conn.createStatement();
String sql="select * from login where Username='"+name+"' and
Password='"+pass+"'";
rs=st.executeQuery(sql);
if(rs.next())
{
HttpSession login =request.getSession(true);
login.setAttribute("uname", name);
response.sendRedirect("home.jsp");
}
else
{
out.println ("USer Does not Exists");
}
} catch (Exception se) {
out.println("Connection error :" + se.getMessage().toString());
}
%>
Home.jsp
<%
try
{
String uname=session.getAttribute("uname").toString();
%>
Welcome ,<% out.print(uname); %>
<%
}
catch(Exception se)
{
out.println(se.getMessage());
}
%>
18
Write a JSP program to display the grade of a student by accepting the marks of five subjects.
<html>
<body>
<% int total=0;
String name=request.getParameter("name");
int sub1=Integer.parseInt(request.getParameter("sub1"));
int sub2=Integer.parseInt(request.getParameter("sub2"));
int sub3=Integer.parseInt(request.getParameter("sub2"));
total=(sub1+sub2+sub3)/3;
if(total>90)
out.print("conratulations "+name+" for obtaining AA grade");
else if(total<=90 && total>=70)
out.print("conratulations "+name+" for obtaining BB grade");
else if(total<70 && total>=36)
out.print("conratulations "+name+" for obtaining cc grade");
else
out.print("sorry u r fail");
%>
</body>
</html>
(FACULTY)
(I/C H.O.D.)
Download