Advancedjava Labmanual

Download as pdf or txt
Download as pdf or txt
You are on page 1of 56

PRACTICAL-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)
Program :
/* <applet code="centerCircle" width=500 height=300> </applet> */
import java.awt.*;
import java.applet.*;
public class centerCircle extends Applet
{
public void paint(Graphics g)
{
Dimension d = getSize();
int x = d.width/2;
int y = d.height/2;
int radius = 100;
g.drawOval(x-radius, y-radius, 2*radius, 2*radius);
}
}
Output:

1
PRACTICAL-2
Draw ten red circles in a vertical column in the center of the applet.
Program :
import java.awt.*;
import java.applet.Applet;
public class TenCircles extends Applet{
int w,h;
public void init()
{
w=getWidth();
h=getHeight();
}
public void paint(Graphics g)
{
for(int i=0;i<10;i++)
g.drawOval(w/2-5,i*10,10,10);
}
Output:

2
PRACTICAL-3
Built an applet that displays a horizontal rectangle in its center. Let the rectangle fill with color from left
to right.
Program :
/* <applet code="RectanglesDrawing" width="500" height="400"></applet> */
import java.awt.*;
import java.applet.*;
public class RectanglesDrawing extends Applet
{
public void paint(Graphics g)
{
Dimension d = getSize();
int x = (d.width/2)-150;
int y = (d.height/2)-50;
//g.setColor(Color.blue);
g.drawRect(x, y, 300, 100);
//g.setColor(Color.magenta);
g.fillRect(x, y, 200, 100);
}
}
Output:

3
PRACTICAL-4

Write an applet that display 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

Program:

/* <applet code="Mouse1" width="500" height="400"> </applet> */


import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class Mouse1 extends Applet implements MouseListener, MouseMotionListener
{
int width, height;
int mx, my
boolean isButtonPressed = false;
public void init()
{
width = getSize().width;
height = getSize().height;
mx = width/2;
my = height/2;
addMouseListener( this );
addMouseMotionListener( this );
}
public void mouseEntered( MouseEvent e ) {}
public void mouseExited( MouseEvent e ) {}
public void mouseClicked( MouseEvent e ) {}
public void mousePressed( MouseEvent e )
{
isButtonPressed = true;
setBackground(Color.yellow);

4
repaint();
e.consume();
}
public void mouseReleased( MouseEvent e )
{
isButtonPressed = false;
setBackground( Color.blue );
repaint();
e.consume();
}
public void mouseMoved( MouseEvent e )
{ // called during motion when no buttons are down
mx = e.getX();
my = e.getY();
showStatus( "Mouse at (" + mx + "," + my + ")" );
repaint();
e.consume();
}
public void mouseDragged( MouseEvent e )
{ // called during motion with buttons down
mx = e.getX();
my = e.getY();
showStatus( "Mouse at (" + mx + "," + my + ")" );
repaint();
e.consume();
}
public void paint( Graphics g )
{
if ( isButtonPressed )
{

5
g.setColor( Color.yellow );
}
else
{
g.setColor( Color.black )
g.fillRect( mx, my, 10, 10 );
}
}
}
Output:

6
PRACTICAL-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.
Program :
/*<applet code="ButtonApplet.class" width="300" height="200"> </applet>*/
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class ButtonApplet extends Applet implements ActionListener
{
Button btn;
String str1="Start";
public void init()
{
btn = new Button("Click ");
btn.setLabel(str1);
btn.addActionListener(this);
add(btn);
}
public void actionPerformed(ActionEvent e)
{
String str =btn.getLabel();
if(str=="Start")
btn.setLabel("stop");
else if(str=="stop")
btn.setLabel("Start");
}
}

Output:

7
8
PRACTICAL-6
Write an applet that uses the mouse listener, which overrides only two methods which are mousePressed
and mouseReleased.
Program:
import java.awt.*;
import java.applet.*;
import java.awt.event.*; /*
<applet code="Demo1" width=500 height=500></applet>*/
public class Demo1 extends Applet implements MouseListener
{
public void init()
{
addMouseListener(this);
} // override all the five abstract methods of MouseListener
public void mouseClicked(MouseEvent e) { }
public void mousePressed(MouseEvent e)
{
setBackground(Color.blue);
}
public void mouseReleased(MouseEvent e)
{
setBackground(Color.yellow);
}
public void mouseEntered(MouseEvent e){ }
public void mouseExited(MouseEvent e){ }
}

9
Output:

10
PRACTICAL NO: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)
Program :
import java.awt.*;
import java.awt.event.*;
public class A extends Frame implements ActionListener
{
int c=1;
A()
{
setLayout(new FlowLayout());
Button b1=new Button("Submit");
add(b1);
b1.addActionListener(this);
}
public static void main(String args[])
{
A a1=new A();
WindowQuitter wquit = new WindowQuitter();
a1.addWindowListener( wquit );
a1.setSize(200,200);
a1.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(c==1)
{
setBackground(Color.red);

11
c++;
}
else if(c==2)
{
setBackground(Color.green);
c++;
}
else if(c==3)
{
setBackground(Color.blue);
c=1;
}
}
}
Output:

12
PRACTICAL-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 determine the color of the canvas. For
example, if the user selects both “Red” and “Blue”, the canvas should be purple.
Program:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="demo" width=300 height=300 ></applet>*/
public class demo extends Applet implements ItemListener
{
Checkbox Red,Blue,Green;
Canvas can;
public void init()
{
Red = new Checkbox("Red",false);
Blue = new Checkbox("Blue",false);
Green = new Checkbox("Green",false);
add(Red);
add(Blue);
add(Green);
Red.addItemListener(this);
Blue.addItemListener(this);
Green.addItemListener(this);
can= new Canvas();
can.setSize(30,30);
add(can);
}
public void itemStateChanged(ItemEvent ie)
{

13
repaint();
}
public void paint(Graphics g)
{
int i,j,k;
if(Red.getState())
i=255;
else
i=0;
if(Blue.getState())
j=255;
else
j=0;
if(Green.getState())
k=255;
else
k=0;
Color c=new Color(i,j,k);
g.setColor(c);
can.setBackground(c);
can.repaint();
}
}
Output:

14
PRACTICAL-9

Create an application that displays a frame with a menubar. When a user selects any menu or menu
item, display that selection on a text area in the center of the frame
Program:
import java.awt.*;
import java.awt.event.*;
class menu extends Frame implements ActionListener
{
MenuBar mbar;
Menu file,edit;
String msg="";
MenuItem nw,open,save,saveas,ps,print,exit,ud,cut,copy,paste,del,f,fn,re,gt,sall,td;
menu()
{
setTitle("Menu Example");
mbar=new MenuBar();
setMenuBar(mbar);
file=new Menu("File");
nw=new MenuItem("New");
open=new MenuItem("Open");
save=new MenuItem("Save");
saveas=new MenuItem("Save As....");
ps=new MenuItem("Page Setup....");
print=new MenuItem("Print");
exit=new MenuItem("Exit");
mbar.add(file);
file.add(nw);
file.add(open);
file.add(save);
file.add(saveas);

15
file.add(ps);
file.add(print);
file.add(exit);
edit=new Menu("Edit");
ud=new MenuItem("Undo");
cut=new MenuItem("Cut");
copy=new MenuItem("Copy");
paste=new MenuItem("Paste");
del=new MenuItem("Delete");
f=new MenuItem("Find");
fn=new MenuItem("Find Next...");
re=new MenuItem("Replace");
gt=new MenuItem("Go To....");
sall=new MenuItem("Select All");
td=new MenuItem("Time/Date");
mbar.add(edit);
edit.add(ud);
edit.add(cut);
edit.add(copy);
edit.add(paste);
edit.add(del);
edit.add(f);
edit.add(fn);
edit.add(re);
edit.add(gt);
edit.add(sall);
edit.add(td);
nw.addActionListener(this);
open.addActionListener(this);
save.addActionListener(this);

16
saveas.addActionListener(this);
ps.addActionListener(this);
print.addActionListener(this);
exit.addActionListener(this);
ud.addActionListener(this);
cut.addActionListener(this);
copy.addActionListener(this);
paste.addActionListener(this);
del.addActionListener(this);
f.addActionListener(this);
fn.addActionListener(this);
re.addActionListener(this);
gt.addActionListener(this);
sall.addActionListener(this);
td.addActionListener(this);
}
public static void main(String args[])
{
Frame m=new menu();
WindowQuitter wquit = new WindowQuitter();
m.addWindowListener( wquit );
m.setBounds(1,1,500,500);
m.setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getActionCommand().equals("New"))
msg="New";
if(ae.getActionCommand().equals("Open"))
msg="Open";

17
if(ae.getActionCommand().equals("Save"))
msg="Save";
if(ae.getActionCommand().equals("Save As...."))
msg="Save As....";
if(ae.getActionCommand().equals("Page Setup...."))
msg="Page Setup....";
if(ae.getActionCommand().equals("Print"))
msg="Print";
if(ae.getActionCommand().equals("Exit"))
msg="Exit";
if(ae.getActionCommand().equals("Undo"))
msg="Undo";
if(ae.getActionCommand().equals("Cut"))
msg="Cut";
if(ae.getActionCommand().equals("Copy"))
msg="Copy";
if(ae.getActionCommand().equals("Paste"))
msg="Paste";
if(ae.getActionCommand().equals("Delete"))
msg="Delete";
if(ae.getActionCommand().equals("Find"))
msg="Find";
if(ae.getActionCommand().equals("Find Next..."))
msg="Find Next....";
if(ae.getActionCommand().equals("Replace"))
msg="Replace";
if(ae.getActionCommand().equals("Go To...."))
msg="Go To....";
if(ae.getActionCommand().equals("Select All"))
msg="Select All";

18
if(ae.getActionCommand().equals("Time/Date"))
msg="Time/Date";
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,300,300);
}
}
Output:

19
PRACTICAL-10

Write an applet that draws two sets of ever-decreasing rectangles one in outline form and one filled
alternately in black and white.
Program:
/*<Applet code="demo" height="500" width="500"></Applet>*/
import java.applet.*;
import java.awt.*;
public class demo extends Applet
{
Public void paint(Graphics g)
{
int a=330,b=250,c=150,d=150;
for(int i=0;i<50;i++)
{
g.drawRect(a,b,c,d);
a=a-5;
b=b-5;
c=c-5;
d=d-5;
}
}
}
Output:

20
PRACTICAL NO:11
Write a database application that use any JDBC driver
Program:
For Creating Database:
MS access Database table
For creating DataSource:
Control PanelAdministrative Tools DataSource(ODBC)ADD user DSN
Microsoft Access Driver(*.mdb,*.accdb)  DataSourceName and Select Database OK
import java.sql.*;
class jdbc1
{
public static void main(String args[]) throws Exception
{
Connection con = DriverManager.getConnection("jdbc:odbc:c2");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Statement st = con.createStatement();
String sql1 = "select * from student";
ResultSet rs = st.executeQuery(sql1);
System.out.println("No Name ");
while (rs.next())
{
System.out.println(rs.getInt(1) + " " + rs.getString(2) );
}
rs.close();
}
}

21
Output:

22
PRACTICAL-12
Develop a UI that performs the following SQL operations:1) Insert 2)Delete 3)Update.
Program:
import java.sql.*;
import java.io.*;
public class mysql3
{
public static void main(String[] args) throws Exception
{
Connection con;
ResultSet rs;
Statement t;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost/student","root","");
do
{
System.out.println("\n1.Insert\n2.Modify\n3.Delete\n4.Search\n5.View all\n6.Exit");
System.out.println("Enter the choice");
int ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1:
System.out.println("Enter the Rollno");
int roll=Integer.parseInt(br.readLine());
System.out.println("Enter the name");
String n=br.readLine();
System.out.println("Enter the percentage");
int per=Integer.parseInt(br.readLine());
t=con.createStatement();

23
t.executeUpdate("insert into student values("+roll+",'"+n+"',"+per+")");
break;
case 2:
System.out.println("Enter the roll no for update record");
roll=Integer.parseInt(br.readLine());
System.out.println("Enter the name");
n=br.readLine();
System.out.println("Enter the percentage");
per=Integer.parseInt(br.readLine());
t=con.createStatement();
t.executeUpdate("update student set name='"+n+"',per="+per+" where
rollno="+roll);
break;
case 3:
System.out.println("Enter the roll no for delete record");
int no=Integer.parseInt(br.readLine());
t=con.createStatement();
t.executeUpdate("delete from student where rollno="+no);
break;
case 4:
t=con.createStatement();
rs=t.executeQuery("select * from student");
while(rs.next())
{
System.out.println("Roll no="+rs.getInt(1));
System.out.println("name="+rs.getString(2));
System.out.println("percentage="+rs.getInt(3));
}
break;
case 5:

24
System.exit(0);
break;
}
}while(true);
}
}
Output:-
1.Insert
2.Modify
3.Delete
4.View all
5.Exit
Enter the choice 1
Enter the Rollno
4
Enter the name
Rutuja
Enter the percentage
85

1.Insert
2.Modify
3.Delete
4.Search
5.View all
6.Exit
Enter the choice 2
Enter the roll no for update record
4
Enter the name

25
Rutuja
Enter the percentage
35

1.Insert
2.Modify
3.Delete
4.Search
5.View all
6.Exit
Enter the choice 3
Enter the roll no for delete record
4

1.Insert
2.Modify
3.Delete
4.Search
5.View all
6.Exit
Enter the choice 4
Roll no=1
name=Pallavi
percentage=67
Roll no=2
name=Vinaya
percentage=63
Roll no=3
name=Trupti
percentage=61

26
Roll no=4
name=Rutuja
percentage=85

1.Insert
2.Modify
3.Delete
4.Search
5.View all
6.Exit
Enter the choice
6

27
PRACTICAL-13

Write a program to present a set of choice for user to select a product & display the price of product
Program:
import java.sql.*;
import java.io.*;
class p13
{
public static void main(String[] args) throws Exception
{
Connection con;
ResultSet rs;
Statement t;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:access");
do
{
System.out.println("\n1.Mobile\n2.Laptop\n3.Keyboard\n4.Car\n5.Exit");
System.out.println("Enter the choice");
int ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1:
t=con.createStatement();
rs= t.executeQuery("select * from product where ID=2");
while(rs.next())
{
System.out.println("Product Name="+rs.getString(2));
System.out.println("Product Price="+rs.getString(3));
}

28
break;
case 2:
t=con.createStatement();
rs= t.executeQuery("select * from product where ID=3 ");
while(rs.next())
{
System.out.println("Product Name="+rs.getString(2));
System.out.println("Product Price="+rs.getString(3));
}
break;
case 3:
t=con.createStatement();
rs=t.executeQuery("select * from product where ID=4 ");
while(rs.next())
{
System.out.println("Product Name="+rs.getString(2));
System.out.println("Product Price="+rs.getString(3));
}
break;
case 4:
t=con.createStatement();
rs= t.executeQuery("select * from product where ID=5");
while(rs.next())
{
System.out.println("Product Name="+rs.getString(2));
System.out.println("Product Price="+rs.getString(3));
}
break;
case 5:
System.exit(0);

29
Break;
}
}while(true);
}
}
Output:

30
PRACTICAL-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
Program:
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 Counter extends HttpServlet
{
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try
{
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet Counter</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>"+"No. Of Visitors:");
out.println(RequestHandler.getreqcnt()+"</h1>");
out.println("<h1>"+"No. Of activated Sessoin:");
out.println(RequestHandler.getreqsc() +"</h1>");
out.println("</body>");
out.println("</html>");

31
}
finally
{
out.close();
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)throws
ServletException, IOException
{
processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)throws
ServletException, IOException
{
processRequest(request, response);
}
@Override
public String getServletInfo()
{
return "Short description";
}
}
File Name: RequestHandler.java
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class RequestHandler implements ServletRequestListener,HttpSessionListener

32
{
static int cnt ,sc;
public void requestDestroyed(ServletRequestEvent sre)
{
throw new UnsupportedOperationException("Not supported yet.");
}
public void requestInitialized(ServletRequestEvent sre)
{
cnt++;
}
public void sessionCreated(HttpSessionEvent se)
{
sc++;
}
public void sessionDestroyed(HttpSessionEvent se)
{
sc--;
}
public static int getreqcnt()
{
return cnt;
}
public static int getreqsc()
{
return sc;
}
}
Web.XML
<?xml version="1.0" encoding="UTF-8"?>

33
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<listener>
<listener-class>RequestHandler</listener-class>
</listener>
<servlet>
<servlet-name>Counter</ servlet-name>
<servlet-class>Counter</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Counter</servlet-name>
<url-pattern>/Copunter</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
Output:
1 No of Visitor
Request Handler 1
No of activated Session 1

2 No of Visitor
Request Handler 2
No of activated Session 2

34
PRACTICAL-15
Create a form processing servlet which demonstrates use of cookies and sessions.
Program:
COOKIES:
Index.html
<form action="servlet1" method="post">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response)
{
Try
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
Cookie ck=new Cookie("uname",n);//creating cookie object
response.addCookie(ck);//adding cookie in the response
//creating submit button
out.print("<form action='servlet2'>");
out.print("<input type='submit' value='go'>");
out.print("</form>");
out.close();

35
}
catch(Exception e)
{
System.out.println(e);
}
}
}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response)
{
Try
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Cookie ck[]=request.getCookies();
out.print("Hello "+ck[0].getValue());
out.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
web.xml

36
<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>
SESSION
Index.html
<form action="servlet1" method="post">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet
{

37
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.print("<a href='servlet2'>visit</a>");
out.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
{
Try
{
response.setContentType("text/html");

38
PrintWriter out = response.getWriter();
HttpSession session=request.getSession(false);
String n=(String)session.getAttribute("uname");
out.print("Hello "+n);
out.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
web.xml
<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>

39
</web-app>
Output:

40
PRACTICAL-16
Write a simple JSP program for user Registration & then control will be transfer it into second page
Program:
index.html
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div>TODO write content</div>
</body>
</html>
main.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Registration</title>
</head>
<body>
<form method="post" action="registration.jsp">
<center>
<table border="1" width="30%" cellpadding="5">
<head>
<tr>
<th colspan="2">Enter Information Here</th>
</tr>

41
</head>
<body>
<tr>
<td>First Name</td>
<td><input type="text" name="fname" value="" /></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" name="lname" value="" /></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email" value="" /></td>
</tr>
<tr>
<td>User Name</td>
<td><input type="text" name="uname" value="" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="pass" value="" /></td>
</tr>
<tr>
<td><input type="submit" value="Submit" /></td>
<td><input type="reset" value="Reset" /></td>
</tr>
<tr>
<td colspan="2">Already registered!! <a href="main.html">Login
Here</a></td>
</tr>

42
</body>
</table>
</center>
</form>
</body>
</html>
registration.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCtml>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
%@page import ="java.sql.*" %
<%
String user = request.getParameter("uname");
String pwd = request.getParameter("pass");
String fname = request.getParameter("fname");
String lname = request.getParameter("lname");
String email = request.getParameter("email");
Connection con = null;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:admin");
Statement st=con.createStatement();
int i = st.executeUpdate("insert into members(first_name, last_name,
email, uname, pass) values ('" + fname + "','" + lname + "','" + email + "','" + user + "','" +
pwd + "')");
session.setAttribute("usernm", fname);

43
response.sendRedirect("success.jsp?" + user);
%>
</body>
</html>
success.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE >
<html>
<head>
<me-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
Hello <%= session.getAttribute("usernm") %>, You are Registered Successfully.
</body>
</html>
Output:

44
PRACTICAL-17
Write a simple JSP program for user login form with static & dynamic database
Program:
For Static Database:
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" 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>Insert title here</title>
</head>
<body>
<form method="post" action="Sample.jsp">
username:<input type="text" name="name"><br>
password:<input type="password" name="password"><br>
<input type="submit" value="submit">
</form>
</body>
</html>
sample.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"
import="java.lang.*"%>
<!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>Insert title here</title>

45
</head>
<body>
<%
/*checking condition:
username:kumar
password:kumar123 */
if(request.getParameter("name").equals("kumar") &&
request.getParameter("password").equals("kumar123"))
{
//redirecting to sucess page
response.sendRedirect("sucess.jsp");
}
Else
{
//redirecting to failure page
response.sendRedirect("failure.jsp");
}
%>
</body>
</html>
success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"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>Insert title here</title>
</head>
<body>

46
<h1>Login sucessfull</h1>
</body>
</html>
failure.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"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>Insert title here</title>
</head>
<body>
<h1>!sorry invalid user</h1>
</body>
</html>
For Dynamic Database:
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"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>Insert title here</title>
</head>
<body>
<form method="post" action="Sample.jsp">
username:<input type="text" name="name"><br>
password:<input type="password" name="password"><br>

47
<input type="submit" value="submit">
</form>
</body>
</html>
sample.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"
import="java.lang.*"%>
<!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>Insert title here</title>
</head>
<body>
<%
<%@ page import ="java.sql.*" %>
<%
String user = request.getParameter("name");
String pwd = request.getParameter("password");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con =
DriverManager.getConnection("jdbc:odbc:admin");
Statement st = con.createStatement();
String qry=”select uname,pass from login where uname =
‘”+usr+”’ and pass=’”+pwd+”’ “;
ResultSet rs = st.executeQuery(qry);
session.setAttribute("usr”);
If(rs==true)
{

48
response.sendRedirect("success.jsp ");
}
Else
{
response.sendRedirect("failure.jsp ");
}
%>
//redirecting to sucess page
response.sendRedirect("sucess.jsp");
}
Else
{
//redirecting to failure page
response.sendRedirect("failure.jsp");
}
%>
</body>
</html>
success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"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>Insert title here</title>
</head>
<body>
<h1>Login sucessfull</h1>
</body>

49
</html>
failure.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"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>Insert title here</title>
</head>
<body>
<h1>!sorry invalid user</h1>
</body>
</html>
Output:

50
PRACTICAL-18
Write a JSP program to display the grade of a student by accepting the marks of five subjects.
Program:
<%@ 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>Student Marks</title>
</head>
<body>
<h2>Student Grading System</h2>
<form action="" method="post">
<table>
<tr>
<td></td>
<td>Select Course
<select name="course">
<option value="select">select</option>
<option value="MCA">MCA</option>
<option value="BCA">BCA</option>
</select>
</td>
</tr>
</table>
<table>
<tr>
<th>Subject</th>
<th>Obtained Marks</th>

51
<th>Total Marks</th>
</tr>
<tr>
<td align="center">C</td>
<td align="center"><input type="text" size="5"
name="c"/></td>
<td align="center">100</td>
</tr>
<tr>
<td align="center">Java</td>
<td align="center"><input type="text" size="5"
name="java"/></td>
<td align="center">100</td>
</tr>
<tr>
<td align="center">.Net</td>
<td align="center"><input type="text" size="5"
name="net"/></td>
<td align="center">100</td>
</tr>
<tr>
<td align="center">VB</td>
<td align="center"><input type="text" size="5"
name="vb"/></td>
<td align="center">100</td>
</tr>
<tr>
<td align="center">DBMS</td>
<td align="center"><input type="text" size="5"
name="dbms"/></td>

52
<td align="center">100</td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td></td>
<td align="center"><input type="submit"
value="submit"/></td>
</tr>
</table>
</form>
<%
String c = request.getParameter("c");
String j = request.getParameter("java");
String n = request.getParameter("net");
String v = request.getParameter("vb");
String d = request.getParameter("dbms");
if(!(c == null || c.isEmpty()))
int cmarks = Integer.parseInt(c);
int jmarks = Integer.parseInt(j);
int nmarks = Integer.parseInt(n);
int vmarks = Integer.parseInt(v);
int dmarks = Integer.parseInt(d);
int total = cmarks+jmarks+nmarks+vmarks+dmarks;
int avg = (total)/5;
int percent = avg;

53
String grade ="";
if(percent < 40)
{
grade = "E";
}
else if(percent >= 40 && percent <=44)
{
grade = "D";
}
else if(percent >=45 && percent <=49)
{
grade = "D+";
}
else if(percent >=50 && percent <=54)
{
grade = "C-";
}
else if(percent >=55 && percent<=59)
{
grade = "C";
}
else if(percent >=60 && percent <=64)
{
grade = "C+";
}
else if(percent >=65 && percent<=69)
{
grade = "B-";
}
else if(percent >=70 && percent <=74)

54
{
grade = "B";
}
else if(percent >=75 && percent <=79)
{
grade = "B+";
}
else if(percent >=80 && percent <=84)
{
grade = "A";
}
else if (percent >=85 && percent <=100)
{
grade = "A+";
}
request.setAttribute("Grade", grade);
%>
<table>
<tr>
<td><b>Course</b></td><td></td>
<td align="center"><%=request.getParameter("course") %>
</tr>
<tr>
<td><b>Aggregate Marks</b></td><td></td>
<td align="center"><%=total %></td>
</tr>
<tr>
<td><b>Grade</b></td><td></td>
<td align="center"><%=grade %></td>
</tr>

55
</table>
<%
}
%>
</body>
</html>
Output:

56

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy