Ajava1 To 23prac
Ajava1 To 23prac
TERM WORK
DEPARTMENT OF
COMPUTER ENGINEERING
Submitted by
Enrollment No 186140307110
Name Thakkar Dhara Manishbhai
CERTIFICATE
satisfactorily completed the term work in course Advance Java Programming with Subject
UNIT 1
JAVA APPLETS
JAVA APPLETS
An Applet is a Java program that can be embedded into a web page. It runs inside the web browser and
works at client side. An Applet is embedded in an HTML page using the APPLET tag and hosted on a
web server. Applets are used to make the web site more dynamic and entertaining.
Important points:
All applets are sub-classes (either directly or indirectly) of java.applet.Applet class.
Applets are not stand-alone programs. Instead, they run within either a web browser or an applet
viewer. JDK provides a standard applet viewer tool called applet viewer.
In general, execution of an Applet does not begin at main() method.
Output of an applet window is not performed by System.out.println(). Rather it is handled with
various AWT methods, such as drawString().
Software Required: JDK, Appletviewer Tool, JAVA enabled Web Browser.
Package: java.applet.*, java.awt.*.
String getParameter(String attr) Returns the value of the named parameter in the HTML tag.
Practical No. 1
Develop 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).
Prac1Circle.java
import java.applet.Applet;
import java.awt.*;
Circle.html
<HTML>
<BODY>
<APPLET CODE="Prac1Circle.class" WIDTH="500" HEIGHT="300">
</APPLET>
</BODY>
</HTML>
Output:
Conclusion/Observation:
This Program is to draw the circle in the center of the Applet. Created an Applet of width 500 and height
300 by setting the attributes of applet tag in html code. Circle is of 100 pixels radius created using
drawOval() Method of graphics Class and “ABC ” written in the center of the circle using drawString()
Method of the Graphics class.
Practical No. 2
Write a program to draw ten red circles in a vertical column in the centre of the applet.
Prac2FillCircle.java
import java.applet.Applet;
import java.awt.*;
}
}
Circle2.html
<HTML>
<BODY>
<APPLET CODE="Prac2FillCircle.class" WIDTH="500" HEIGHT="500">
</APPLET>
</BODY>
</HTML>
Output:
Conclusion/Observation:
This program is to draw ten red circles in a vertical column in the centre of the applet.Created an Applet
of width 500 and height 500 by setting the attributes of applet tag in html code. Circle is created using the
drawOval() method. To draw ten circles in a vertical column I have to write the drawOval() method in the
for loop. Firstly, in the for loop i had set color as red by using setColor method() of the graphics class. In
every iteration of the for loop the height of the circle will increase by 50, if we will not do so then every
circle will overlap each other.
Practical No. 3
Build an applet that displays a horizontal rectangle in its centre. Let the rectangle be filled with colour
from left to right.
Prac3FillRect.java
import java.applet.Applet;
import java.awt.*;
public class Prac3FillRect extends Applet
{
public void paint(Graphics g)
{
String r = getParameter("R");
String gr = getParameter("G");
String b = getParameter("B");
int ri = Integer.parseInt(r);
int gi = Integer.parseInt(gr);
int bi = Integer.parseInt(b);
int w=150;
for(int i=1;i<=5;i++)
{
Color c = new Color(ri,gi,bi);
g.setColor(c);
g.fillRect(w,200,40,70);
w=w+40;
bi = bi-50;
}
}
}
FillRect.html
<HTML>
<BODY>
<APPLET CODE="Prac3FillRect.class" WIDTH="500" HEIGHT="500">
<PARAM NAME="R" VALUE="255">
<PARAM NAME="G" VALUE="0">
<PARAM NAME="B" VALUE="255">
</APPLET>
</BODY>
</HTML>
Output:
Conclusion/Observation:
This Program is to display a horizontal rectangle in its centre and filled with colour from left to
right.Firstly I had to use the getParameter Method to get the value of parameters from the HTML
code.After that converted that value to Integer from string because color class accepts the parameter in
the Integer form.I had user fillRect from displaying rectangle and filling color in it.Every time i am
decrementing the value of bi for changing the color.
Practical No. 4
Write a program to pass parameters to applet to set the message on its status bar.
Prac4ShowStatus .java
import java.applet.Applet;
import java.awt.*;
public class Prac4ShowStatus extends Applet
{
String s;
public void init()
{
s = getParameter("status");
}
public void paint(Graphics g)
{
showStatus(s);
g.drawString("Hello",250,250);
}
}
ShowStatus.html
<HTML>
<BODY>
<APPLET CODE="Prac4ShowStatus.class" WIDTH="500" HEIGHT="500">
<PARAM NAME="status" VALUE="Practical 4 of Applet ">
</APPLET>
</BODY>
</HTML>
Output:
Conclusion/Observation:
This program passes parameters to applet to set the message on its status bar. I had to use getParameter
for getting the value that is to be set in status bar and After that , passess that value to the ShowStatus()
method of the component class for displaying the value in the status bar of an applet.
Practical No. 5
Develop an applet that displays moving banner. Consider string “Advance Java Programming”.
Prac5MovingBanner.java
import java.applet.Applet;
import java.awt.*;
public class Prac5MovingBanner extends Applet implements Runnable
{
String msg=" Advance Java Programming ";
Thread t= null;
int state;
volatile boolean stopflag;
MovingBanner.html
<HTML>
<BODY>
<APPLET CODE="Prac5MovingBanner.class" WIDTH="500" HEIGHT="500">
</APPLET>
</BODY>
</HTML>
Output:
Conclusion/Observation:
This program is about to display a moving banner. For displaying the moving banner we have to use
threads concept . In this program there are a total 5 methods init(), start(),stop() methods of Applet class ,
run() method of thread and paint() method of graphics class.
UNIT 2
ABSTRACT WINDOW
TOOLKIT
UI elements: These are the core visual elements the user eventually sees and interacts with.
Layouts: They define how UI elements should be organized on the screen and provide a final
look and feel to the GUI (Graphical User Interface).
Behavior: These are events which occur when the user interacts with UI elements.
Software Required: JAVA Editors, JDK, Appletviewer Tool, JAVA enabled Web Browser.
AWT UI Elements
SrNo Elements and Description.
Component
Component class is at the top of AWT hierarchy. All the elements like buttons, text fields,
1. scrollbars etc are known as components. Component is an abstract class that encapsulates all the
attributes of visual component. A component object is responsible for remembering the current
foreground and background colors and the currently selected text font.
Container
Container is a component in AWT that contains another component like button, text field, tables
2.
etc. Container is a subclass of component class. Container class keeps track of components that
are added to another component.
Panel
Panel class is a concrete subclass of Container. Panel does not contain title bar, menu bar or
3.
border. It is container that is used for holding components.
Window
4.
Window class creates a top level window. Window does not have borders and MenuBar.
Frame
5. Frame is a subclass of Window and has resizing canvas. The Frame is the container that contain
title bar and can have menu bars.
Label
6. A Label object is a component for placing text in a container. It is a passive control because it
does not create any event when accessed by the user. It displays a single line of read-only text.
Button
7.
Button is a control component that has a label and generates an event when pressed.
Checkbox
Checkbox control is used to turn an option on(true) or off(false). There is label for each
8.
checkbox representing what the checkbox does.The state of a checkbox can be changed by
clicking on it.
List
9. The List represents a list of text items. The list can be configured that user can choose either one
item or multiple items.
TextField
10.
The TextField component allows the user to edit single line of text.
TextArea
The TextArea control in AWT provide us multiline editor area. When the text in the text area
11.
become larger than the viewable area the scroll bar is automatically appears which help us to
scroll the text up & down and right & left.
Choice
12. Choice control is used to show pop up menu of choices. Selected choice is shown on the top of
the menu.
Prac6.java
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/* <APPLET CODE="Prac6.class" WIDTH="500" HEIGHT="500"></APPLET>*/
public class Prac6 extends Applet implements MouseMotionListener
{
String str="";
int x,y;
public void init()
{
addMouseMotionListener(this);
}
public void mouseMoved(MouseEvent me)
{
x= me.getX();
y= me.getY();
str= "Mouse Moved at location X : "+x+ " Y: "+y;
repaint();
}
public void mouseDragged(MouseEvent me)
{
x= me.getX();
y= me.getY();
str= "Mouse Dragged at location X : "+x+ " Y: "+y;
repaint();
}
public void paint(Graphics g)
{
g.drawString(str,20,20);
g.fillRect(x,y,10,10);
}
Output:
Conclusion/Observation:
This Program is to develop an applet that displays the position of the mouse at the upper left corner of the
applet when it is dragged or moveda and draw a 10x10 pixel rectangle filled with black at the current
mouse position. For that first we have to import java.awt.event.* package to perform to do programs
related to events . As we saw here our source is mouse so i had implement MouseMotionListner interface
and implemented all the method of MouseMotionListner interface and i had get the coordinates through
getX() and getY() methods of recorder and draw the rectangle according to that coordinates.
Prac7.java
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
/*
<APPLET CODE="Prac7.class" WIDTH="250" HEIGHT="250"></APPLET>
*/
public class Prac7 extends Applet implements ActionListener
{
Button btn1;
public void init()
{
btn1 = new Button("Start");
add(btn1);
btn1.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String str = btn1.getActionCommand();
if(str.equals("Start"))
{
btn1.setLabel("Stop");
}
else
{
btn1.setLabel("Start");
Conclusion/Observation:
This Program is to develop an applet that contains a toggle button , that contains two values Start and
Stop ,if the value is start and we click on the button the value should change to stop and vice versa .For
that first i had created a button , added it in applet container and register it via addActionListener()
method of Action listener interface. Then i get the value to button through getActionCommand() and
compare the value with the start , if the value is start then set label again using setLabel() method.
Practical8.java
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="Practical8.class" width=500 height=500>
</applet>*/
public class Practical8 extends Applet
{
public void init()
{
MyAdapter ma = new MyAdapter(this);
addMouseListener(ma);
setBackground(Color.black);
}
}
class MyAdapter extends MouseAdapter
{
Practical8 p8;
MyAdapter(Practical8 p8)
{
this.p8=p8;
}
public void mouseReleased(MouseEvent m)
{
p8.setBackground(Color.red);
p8.showStatus("mouse released");
}
public void mousePressed(MouseEvent m)
{
p8.setBackground(Color.blue);
p8.showStatus("mouse pressed");
}
}
Output:
Conclusion/Observation:
In this program , the MouseAdapter concept is used . This program is about to create an applet that uses
the mouse listener, which overrides only two methods which are mouse Pressed and mouse Released ,
and on mouse Pressed and mouse released Background color of an applet changes.
Practical9.java
import java.awt.*;
import java.awt.event.*;
public class Practical9 extends Frame implements ActionListener
{
Button b;
public Practical9()
{
MyAdapter ma =new MyAdapter(this);
addWindowListener(ma);
FlowLayout fl = new FlowLayout();
setLayout(fl);
b = new Button("Change");
add(b);
b.addActionListener(this);
}
public static void main(String args[])
{
Practical9 f = new Practical9();
f.setVisible(true);
f.setSize(500,500);
f.setTitle("Window");
f.setBackground(Color.RED);
}
public void actionPerformed(ActionEvent ae)
{
Color cur_c=getBackground();
Color r_c= new Color(255,0,0);
Color g_c= new Color(0,255,0);
Output:
Conclusion/Observation:
In this program the concept of Frame and WindowAdapter is used . Frame is a container that contains one
button . On a single click of the button the background color changes from red to green ,green to blue ,
blue to red and so on.
Practical No. 10
Develop a program 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.
Practical10.java
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
/*
<APPLET CODE="Practical10.java" WIDTH="400" HEIGHT="400">
</APPLET>
*/
public class Practical10 extends Applet implements ItemListener
{
Checkbox ch_r,ch_g,ch_b;
Canvas c;
public void init()
{
ch_r = new Checkbox("Red");
ch_g = new Checkbox("Green");
ch_b = new Checkbox("Blue");
c = new Canvas();
c.setSize(30,30);
c.setBackground(Color.BLACK);
add(ch_r);
add(ch_g);
add(ch_b);
add(c);
ch_r.addItemListener(this);
ch_g.addItemListener(this);
ch_b.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
int r =0 ,g=0 , b=0;
if(ch_r.getState())
{
r=255;
}
if(ch_g.getState())
{
g=255;
}
if(ch_b.getState())
{
b=255;
}
Color co = new Color(r,g,b);
c.setBackground(co);
}
}
Output:
Conclusion/Observation:
In this Program , Applet is a container that contains 3 Checkbox named “Red”,”Green”,”Blue” and on
canvas or size 30 x 30 pixels . On selecting the checkbox the canvas background color changes
accordingly, for that getState() method is used to see that which checkbox is checked accordingly that
created a color using Color class and set that created color.
Practical No. 11
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
Practical11.java
import java.awt.*;
import java.awt.event.*;
class Frame1 extends Frame implements ActionListener
{
TextArea ta;
Frame1()
{
FlowLayout fl = new FlowLayout();
setLayout(fl);
MenuBar mb = new MenuBar();
setMenuBar(mb);
Menu m1 = new Menu("File");
Menu m2 = new Menu("Edit");
mb.add(m1);
mb.add(m2);
MenuItem mi1 = new MenuItem("New");
MenuItem mi2 = new MenuItem("Open");
MenuItem mi3 = new MenuItem("Save");
MenuItem mi4 = new MenuItem("Cut");
MenuItem mi5 = new MenuItem("Copy");
MenuItem mi6 = new MenuItem("Paste");
m1.add(mi1);
m1.add(mi2);
m1.add(mi3);
m2.add(mi4);
m2.add(mi5);
m2.add(mi6);
ta = new TextArea("Selected Menuitems are......\n");
add(ta);
mi1.addActionListener(this);
mi2.addActionListener(this);
mi3.addActionListener(this);
mi4.addActionListener(this);
mi5.addActionListener(this);
mi6.addActionListener(this);
MyAdapter ma = new MyAdapter();
addWindowListener(ma);
}
public void actionPerformed(ActionEvent ae)
{
String s = ae.getActionCommand();
ta.append("You Select: "+s+"\n");
}
}
class MyAdapter extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
public class Practical11
{
public static void main(String arg[])
{
Frame1 f1 = new Frame1();
f1.setVisible(true);
f1.setSize(500,500);
f1.setTitle("Practical11");
}
}
Government Polytechnic For Girls-Ahmedabad Page No.
Department of Computer Engineering Advance Java Programming (3360701)
Output:
Conclusion/Observation:
In this program , a frame container that contains a menu bar and a text area .When a user selects any
menu or menu item, display that selection on a text area . Default layer of frame is border layout so firstly
we will set the layout as Flowlayout , then we will create a menu bar in that we will add a menu-like file
and edit.After that we will add menu item in each menu , all this coding is done in the constructor. As we
are implementing the ActionListener interface we need to override actionPerformed() method . In that
method we are getting all the action commands and appending in textarea.
Practical12.java
import java.awt.*;
import java.awt.event.*;
public class Practical12 extends Frame implements ActionListener
{
Button b;
Label l;
public Practical12()
{
MyAdapter ma =new MyAdapter(this);
addWindowListener(ma);
FlowLayout fl = new FlowLayout();
setLayout(fl);
b = new Button("Increment");
l = new Label("1");
add(b);
add(l);
b.addActionListener(this);
}
public static void main(String args[])
{
Practical12 f = new Practical12();
f.setVisible(true);
f.setSize(200,200);
f.setTitle("Window");
}
public void actionPerformed(ActionEvent ae)
{
int i = Integer.parseInt(l.getText());
i =i+1;
l.setText(String.valueOf(i));
}
}
class MyAdapter extends WindowAdapter
{
Practical12 fd;
MyAdapter(Practical12 obj)
{
fd=obj;
}
public void windowClosing(WindowEvent we)
{
//System.exit(0);
fd.setVisible(false);
}
}
Output:
Conclusion/Observation:
In this program , Frame is a container that contains a single button and a label with text ‘1’ . On every
click of button label text increment by 1 . There is also a concept of WindowAdapter.
Practical No. 13
Write a GUI based application using Jlabel, JTextField and JButton that accept your name and display it.
Practical13.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code="Practical13.class" height="200" width="250"></applet>
*/
public class Practical13 extends JApplet implements ActionListener
{
JTextField tf1;
JLabel jl1,jl2;
JButton jb1;
public void init()
{
jl1 = new JLabel("Enter Name : ");
jl2 = new JLabel("");
tf1 = new JTextField(20);
jb1 = new JButton("Enter");
add(jl1);
add(tf1);
add(jb1);
add(jl2);
jb1.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String s = tf1.getText();
jl2.setText("Hello " +s);
Output:
Conclusion/Observation:
This program is all about the swing controls like JButton ,JLabel and JTextField . For that firstly we have
to import a new statement import javax.swing.*; for accessing all the swing controls . Then we have to
declare the controls ,add the control and lastly register the button . As we are implementing the
ActionListener interface we need to override the actionPerformed() method , in that i had just get the text
from textfield and simply set that text in label2.
UNIT 3
JAVA DATABASE
CONNECTIVITY
(JDBC)
Software Required: JAVA Editors, JDK, Appletviewer Tool, JAVA enabled Web Browser, Eclipse,
JDBC Driver (mysql-connector-java-5.1.18-bin)
JDBC Driver
JDBC Driver is required to process SQL requests and generate result. The following are the different
types of driver available in JDBC.
The following 5 steps are the basic steps involve in connecting a Java application with Database using
JDBC.
Example:
Class.forName("com.mysql.jdbc.Driver");
2. Create a Connection
Syntax
getConnection(String url)
Example:
Syntax
Example:
Statement s=con.createStatement();
Syntax
Example
After executing SQL statement you need to close the connection and release the session. The close()
method of Connection interface is used to close the connection.
Syntax
Example
con.close();
Practical No. 14
Develop a database application that uses any JDBC driver.
Practical14.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Practical14
{
public static void main(String args[])
{
Connection con;
Statement stmt;
ResultSet rs;
try
{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/ppd","root","");
System.out.println("Connection Successful");
stmt = con.createStatement();
String sql = "SELECT * FROM stu_info";
rs = stmt.executeQuery(sql);
while(rs.next())
{
System.out.println("Id : "+rs.getInt(1)+ " Name : " +rs.getString(2)+ " Sem
: "+rs.getInt(3));
}
rs.close();
stmt.close();
con.close();
}
catch(ClassNotFoundException e)
Government Polytechnic For Girls-Ahmedabad Page No.
Department of Computer Engineering Advance Java Programming (3360701)
{
System.out.println(e);
}
catch(SQLException e)
{
System.out.println(e);
}
}
}
Output:
Conclusion/Observation:
This program is about to develop a database application using jdbc Driver. For that firstly , load a jdbc
Driver using static method forName() of class Class.Then create a connection with server and database
using getConnection() method of DriverManager . After connection create Statement object and execute
query and parse result at last close connection.
Practical15.java
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
//<APPLET code="Practical15" width="500" height="500"></APPLET>
public class Practical15 extends Applet implements ActionListener{
Label l1,l2,l3;
TextField id,name,sem;
Button ins,up,del;
Connection con;
Statement stmt;
public void init()
{
l1=new Label("Id:");
l2=new Label("Name:");
l3=new Label("Sem:");
id=new TextField();
name=new TextField();
sem=new TextField();
ins=new Button("Insert");
up=new Button("Update");
del=new Button("Delete");
add(l1);
add(id);
add(l2);
add(name);
add(l3);
add(sem);
add(ins);
add(up);
add(del);
ins.addActionListener(this);
up.addActionListener(this);
del.addActionListener(this);
try
{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/ppd", "root","");
stmt=con.createStatement();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
catch (SQLException se)
{
se.printStackTrace();
}
}
public void actionPerformed(ActionEvent ae)
{
String s=ae.getActionCommand();
String query=null;
String sid=id.getText();
int a=Integer.parseInt(sid);
String sname=name.getText();
String ssem=sem.getText();
if(s.equals("Insert"))
{
query="INSERT INTO stu_info VALUES("+sid+",'"+sname+"',"+ssem+")";
System.out.println("Inserted successfully");
}
else if(s.equals("Update"))
{
query="UPDATE stu_info SET name='"+sname+"'WHERE id="+a;
System.out.println("updated successfully");
}
else if(s.equals("Delete"))
{
query="DELETE FROM stu_info WHERE id="+a;
System.out.println("deleted successfully");
}
try
{
stmt.executeUpdate(query);
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public void destroy() {
try {
if(stmt!=null)
stmt.close();
if(con!=null)
con.close();
}
catch (SQLException e) {
e.printStackTrace();
}
}
Conclusion/Observation:
This program is all about to develop GUI for Insert ,Update and Delete . For that firstly we have to create
3 Labels , 3 TextField and 3 Buttons for insert ,update and delete after that do the registration of the
button. Then Create a connection with the database using the getConnection() method. Lastly implement
actionPerformed() method and check which button is clicked using getText() method accordingly that
fires the query and finally closes the connection .
Practical16.java
import java.applet.Applet;
import java.awt.Choice;
import java.awt.Label;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
Output:
Conclusion/Observation:
This program is about presenting a set of choices for users to select a product & display the price of
product.For that firstly created a choice , Create a connection and get all the data from the product_details
table and print all the product names in the choice . Then implement itemStateChanged() method and check
that which item is selected according to that display price and lastly close all the connetions.
UNIT 4
SERVLETS
Servlet Technology is used to create web applications. Servlet technology uses Java language to create
web applications.
Web applications are helper applications that reside at web server and build dynamic web pages. A
dynamic page could be anything like a page that randomly chooses picture to display or even a page that
displays the current time.
Software Required: JAVA Editors, JDK, Web Browser, Eclipse IDK for J2EE, JDBC Driver (mysql-
connector-java-5.1.18-bin), Apache Tomcat Server
Package: java.io.*,java.util.*,javax.servlet.*,javax.servlet.http.*;
Servlet Architecture
7. Better performance: because it creates a thread for each request, not process.
8. Portability: because it uses Java language.
9. Robust: JVM manages Servlets, so we don't need to worry about the memory leak, garbage
collection, etc.
10. Secure: because it uses java language.
Attributes are objects that are attached to various scopes and can be modified, retrieved or removed.
Attributes can be read, created, updated and deleted by the web container as well as our application code.
We have methods in the Servlet API to add, modify, retrieve and remove attributes. When an object is
added to an attribute in any scope, it is called binding as the object is bound into a scoped attribute with a
given name.
The API methods to retrieve the ServletContext initialization parameters from a ServletContext object
are:
ServletContext.getInitParameterNames()
o will always return an enumeration of names.
ServletContext.getInitParameter(String paramName)
o will return a String or null.
The API methods to retrieve the ServletConfig initialization parameters from a ServletConfig object are:
ServletConfig.getInitParameterNames()
o returns an enumeration of all the parameter names available to the servlet.
ServletConfig.getInitParameter(String paramName)
o return a parameter value.
Both the methods are implemented in the GenericServlet abstract class.
Cookies are created using Cookie class present in Servlet API. Cookies are added to response object
using the addCookie() method. This method sends cookie information over the HTTP response stream.
getCookies() method is used to access the cookies that are added to response object.
Practical No. 17
Develop 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.
Practical17.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Practical17 extends HttpServlet {
int i;
public void init() throws ServletException
{
ServletConfig config = getServletConfig();
String s = config.getInitParameter("page_count");
i = Integer.parseInt(s);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
i++;
out.println("<HTML>");
out.println("<BODY>");
out.println("<H1>Page Count is :::"+i+"</H1>");
out.println("</BODY>");
out.println("</HTML>");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
doGet(request,response);
Government Polytechnic For Girls-Ahmedabad Page No.
Department of Computer Engineering Advance Java Programming (3360701)
}
}
web.xml
Output:
Conclusion/Observation:
This Practical is about to develop a servlet program which maintains a counter for the number of times it
has been accessed since its loading; initialize the counter using deployment descriptor. For that firstly
creates an Servlet override init(),doGet(),doPost() methods and add the servlet in web.xml file
Practical No. 18
Write an HTML code to create login form having one submit button, two textboxes labeled as Login
name and Password as respectively. Write a Servlet class named as ReadParameter to read these two
parameters and display entered parameters values on the page using doGet() or doPost() method when the
user clicked on the submit button.
Login.html
<!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="Practical18" method="POST">
Username <input type ="text" name="uname"><br/>
Password<input type="password" name="pass"><br/>
<input type ="submit" value="Submit" name="submit">
</form>
</body>
</html>
Practical18.java
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Practical18 extends HttpServlet {
public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException,
ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String unm = request.getParameter("uname");
String pwd = request.getParameter("pass");
out.println("<html>");
out.println("<body>");
out.println("<h1>Welcome "+unm+" </h1>");
out.println("<h1>Password is "+pwd+" </h1>");
out.println("</body>");
out.println("</html>");
}
public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException,
ServletException
{
doGet(request,response);
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>Servlets</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet-name>Practical18</servlet-name>
<servlet-class>Practical18</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Practical18</servlet-name>
<url-pattern>/Practical18</url-pattern>
</servlet-mapping>
</web-app>
Output:
Conclusion/Observation:
This Practical is about reading the parameters and displaying entered parameters values on the page
using doGet() or doPost() method when the user clicked on the submit button. For that firstly created a
form in HTML file , when we click on button in form it should redirect to the servlet(Practical18.java).
In servlet override the doGet() and doPost() methods , in doGet() method get the value that is inserted in
the form using getParameter() and display it.Lastly add this servlet in web.xml file.
Practical No. 19
Create a web form which processes servlet and demonstrates use of cookies and sessions.
index.html
<!DOCTYPE >
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<form action="Praactical19" method="POST">
Name <input type="text" name="userName"><br/>
<input type="submit" name="submit">
</form>
</body>
</html>
Practical19.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Praactical19 extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<HTML>");
out.println("<BODY>");
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
HttpSession session=request.getSession();
session.setAttribute("uname",n);
Servlet2.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Servlet2 extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<HTML>");
out.println("<BODY>");
//Cookie ck[]=request.getCookies();
//out.print("Hello "+ck[0].getValue());
HttpSession session=request.getSession(false);
String n=(String)session.getAttribute("uname");
out.print("Hello "+n);
out.println("</BODY>");
out.println("</HTML>");
out.close();
}catch(Exception e){System.out.println(e);}
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>Servlets</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet-name>Praactical19</servlet-name>
<servlet-class>Praactical19</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Praactical19</servlet-name>
<url-pattern>/Praactical19</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Servlet2</servlet-name>
<servlet-class>Servlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Servlet2</servlet-name>
<url-pattern>/Servlet2</url-pattern>
</servlet-mapping>
</web-app>
Output:
Conclusion/Observation:
This Practical is about creating a web form which processes servlet and demonstrates use of cookies and
sessions.For that we had created 3 files Index.html ,Practical19.java ,Servlet2.java .In index.html simply
created an html form and redirected to the Practical19.java(first servlet) , in Practical19.java firstly get
the value from html form ,set cookie or session, print it and ask user to click on button , When the user
will click on it will redirect to the Servlet2.java(Second Servlet) , in Servelet2.java get the value from set
cookie or session and simply display it .Lastly added both the servlet to the web.xml file.
UNIT 5
JAVA SERVER PAGES
(JSP)
JSP technology is used to create dynamic web applications. JSP pages are easier to maintain then a
Servlet. JSP pages are opposite of Servlets as a servlet adds HTML code inside Java code, while JSP
adds Java code inside HTML using JSP tags. Everything a Servlet can do, a JSP page can also do it.
JSP enables us to write HTML pages containing tags, inside which we can include powerful Java
programs. Using JSP, one can easily separate Presentation and Business logic as a web designer can
design and update JSP pages creating the presentation layer and java developer can write server side
complex computational code without concerning the web design. And both the layers can easily interact
over HTTP requests.
Software Required: JAVA Editors, JDK, Web Browser, Eclipse IDK for J2EE, JDBC Driver (mysql-
connector-java-5.1.18-bin), Apache Tomcat Server
Following steps includes the JSP Architecture as shown in the above figure.
1. Web client sends request to Web server for a JSP page (extension .jsp).
2. As per the request, the Web server (here after called as JSP container) loads the page.
3. JSP container converts (or translates) the JSP file into Servlet source code file (with extension
.java). This is known as translation.
4. The translated .java file of Servlet is compiled that results to Servlet .class file. This is known as
compilation.
5. The .class file of Servlet is executed and output of execution is sent to the client as response.
Scriptlet Tag allows you to write java code inside JSP page. Scriptlet tag implements the _jspService
method functionality by writing script/java code. Syntax of Scriptlet Tag is as follows :
<html>
<head>
<title>My First JSP Page</title>
</head>
<%
int count = 0;
%>
<body>
Page Count is <% out.println(++count); %>
</body>
</html>
We know that at the end a JSP page is translated into Servlet class. So when we declare a variable or
method in JSP inside Declaration Tag, it means the declaration is made inside the Servlet class but
outside the service(or any other) method. You can declare static member, instance variable and methods
inside Declaration Tag. Syntax of Declaration Tag :
Expression Tag is used to print out java language expression that is put between the tags. An expression
tag can hold any java language expression that can be used as an argument to the out.print() method.
Syntax of Expression Tag
out.print((2*5));
Note: Never end an expression with semicolon inside Expression Tag. Like this:
Welcome.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>
<%! int usercount = 0; %>
<H1>
<%
String nm = request.getParameter("fname");
usercount++;
%>
Welcome <%= nm %><br>
You are <%= usercount %> customer...!!!
</H1>
</body>
</html>
Output:
Conclusion/Observation:
This Practical is about developing a simple JSP program for user registration and then control will be
transferring it into the second page.For that first created a simple form in userreg.jsp file and in second
file welcome.jsp firstly in declaration tag usercount initialize by 0 . Secondly get the inserted name from
tha form in scriptlet tag increment usercount and display using expression tag.
Conclusion/Observation:
This Practical is about developing a simple JSP program for user login form with a static database.For
that first of all create a login form . secondly create a connection with the database and check whether
inputted data is already in table or not . if yes then display Login successfully done otherwise Incorrect
credentials.
Output:
Conclusion/Observation:
This Practical is to develop a form to add two values in jsp. Firstly create a form with 2 textboxes and a
submit button . onclick get the value , parse into integer . Add it , and display using the expression tag.
}
%>
<H1>GRADE for total marks <%= sum %> is <%= Grade %></H1>
<%
}
%>
</BODY>
</HTML>
Output:
Conclusion/Observation:
This Practical is about to display the grade of a student by accepting the marks of five subjects. Firstly
create a form with 5 textboxes and one submit button. onclick get the value , parse into integer . Add it ,
and check the total marks accordingly to display the Grade.