PG - M.Sc. - Computer Science - 341 14 - Lab Advanced Java Programming - Binder
PG - M.Sc. - Computer Science - 341 14 - Lab Advanced Java Programming - Binder
Author
Dr. Kavita Saini, Assistant Professor, School of Computer Science & Engineering, Galgotias University, Greater Noida.
All rights reserved. No part of this publication which is material protected by this copyright notice
may be reproduced or transmitted or utilized or stored in any form or by any means now known or
hereinafter invented, electronic, digital or mechanical, including photocopying, scanning, recording
or by any information storage or retrieval system, without prior written permission from the Alagappa
University, Karaikudi, Tamil Nadu.
Information contained in this book has been published by VIKAS® Publishing House Pvt. Ltd. and has
been obtained by its Authors from sources believed to be reliable and are correct to the best of their
knowledge. However, the Alagappa University, Publisher and its Authors shall in no event be liable for
any errors, omissions or damages arising out of use of this information and specifically disclaim any
implied warranties or merchantability or fitness for any particular use.
Work Order No. AU/DDE/DE1-616/Printing of Course Materials/2019, Dated 19.11.2019 Copies - 200
LAB - ADVANCED JAVA PROGRAMMING
Syllabi
BLOCK 1: INTRODUCTION
1. Simple Java Program
2. Program using JDBC with Create, Insert Table Data
3. SQL Exception, SQL Warning
BLOCK 2 : INETADDRESS
4. Programs using TCP/IP Client Sockets, TCP/IP Server Sockets
5. Program with URL, URL Connection, Data Grams Connection
6. Client/Server Applications using RMI
BLOCK 4 : SERVLETS
10. Create a Servlet to Read the Parameters
11. Programs using Cookies
12. Programs with Session Tracking
Self-Instructional
4 Material
LAB REQUIREMENTS Lab - Advanced Java
Programming
To write and run a Java program, you need to install a software like J2SDK 1.7.
SDK stands for system development kit. SDK is also known as JDK (Java
Development Kit) which contains JRE (Java Runtime Environment). It provides a NOTES
platform that enables the program to run on your computer.
Following are the steps given below that explains how to write and execute
a Java program.
Step 1: Write a Java code using text editor (notepad).
1. Write a program to print Hello Java.
//main class
public class Sample1
{
public static void main(String args[])
{
System.out.println(“Hello Java”);
}
}
Step 2: Save the file as Sample1.Java. We have named the file as Sample1, the
thing is that we should always name the file same as the public classname. In our
program, the public class name is Sample1. So, our file name should
be Sample1.Java.
Step 3: Set environment variable.
Follow the steps to set the environment variable:
Right Click on MyComputer Properties Advanced System settings
Inside Advanced tab
Click Environment variables Inside System Vaiables click New Give
variable name (For example var) Give variable value. It is path in your system
where Java compiler is available (For example variable value :C:\Program
Files\Java\jdk1.6.0_23\bin ). Inside bin Javac is Java compiler.
Click Ok.
Step 4: Go to command prompt by using Start Run cmd OR start type
cmd in search program and file.
Step 5: Write following command for compilation of program.
Javac Sample1.Java
Step 6: To run program, use the following command.
Java Sample1
Self-Instructional
Material 1
Lab - Advanced Java Output:
Programming
NOTES
Output:
Self-Instructional
2 Material
float product = first * second; Lab - Advanced Java
Programming
Output:
System.out.println(“—Before swap—”);
System.out.println(“First number = “ + first);
System.out.println(“Second number = “ + second);
NOTES
5. Write a program to print the largest number among the three numbers.
public class Largest
{
else
System.out.println (n3 + “ is the largest number.”);
}
}
Output:
Self-Instructional
4 Material
Lab - Advanced Java
Try Yourself Programming
1. Write a Java program to divide two numbers and print on the screen.
2. Write a Java program to print the result of the following operations.
NOTES
a. -5 + 8 * 6
b. (55+9) % 9
3. Write a Java program to print the sum (addition), multiply, subtract, divide
and remainder of two numbers.
4. Write a Java program to print the area and perimeter of a circle.
Output:
Self-Instructional
Material 5
Lab - Advanced Java 7. Write a program to demonstrate how to access instance variables and
Programming
methods of a class.
public class Puppy
NOTES {
int puppyAge;
public Puppy(String name)
{
// This constructor has one parameter, name.
System.out.println(“Name chosen is :” + name );
}
public void setAge( int age )
{
puppyAge = age;
}
public int getAge( )
{
System.out.println(“Puppy’s age is :” + puppyAge );
return puppyAge;
}
public static void main(String []args)
{
/* Object creation */
Puppy myPuppy = new Puppy( “tommy” );
/* Call class method to set puppy’s age */
myPuppy.setAge( 2 );
/* Call another class method to get puppy’s age */
myPuppy.getAge( );
/* You can access instance variable as follows as
well */
System.out.println(“Variable Value :” + myPuppy.puppyAge
);
}
}
Self-Instructional
6 Material
Output: Lab - Advanced Java
Programming
NOTES
Output:
Self-Instructional
Material 7
Lab - Advanced Java 9. Write a Java program to print factorial of a given number.
Programming
ImportJava.util.*;
class Factorial
NOTES {
public static void main(String args[])
{ int n, i, fact=1;
Scanner scan= new Scanner (System.in);
System.out.print(“Please Enter a No.”);
n=scan.nextInt();
for (i=n;i>=1;i—)
{
fact =fact*i ;
}
System.out.println(“Factorial of “ + n + “ is “ +
fact);
}
}
Output:
class AddTwoMatrix
{
public static void main(String args[])
{
int m, n, c, d;
Scanner in = new Scanner (System.in);
Self-Instructional
8 Material
System.out.println (“Enter the number of rows and columns Lab - Advanced Java
Programming
of matrix”);
m = in.nextInt ();
n =in.nextInt ();
NOTES
System.out.println();
}
}
}
Self-Instructional
Material 9
Lab - Advanced Java Output:
Programming
NOTES
import Java.util.Scanner;
Self-Instructional
10 Material
System.out.println (“Enter the number of columns”); Lab - Advanced Java
Programming
int columns = s.nextInt();
int matrix1[][] = new int[rows][columns];
int matrix2[][] = new int[rows][columns]; NOTES
int sub[][] = new int[rows][columns];
Self-Instructional
Material 11
Lab - Advanced Java for (int i = 0; i< rows; i++) {
Programming
for (int j = 0; j < columns; j++) {
System.out.print(“\t” + sub[i][j]);
NOTES }
System.out.println ();
}
s.close ();
}
}
Output:
Self-Instructional
12 Material
12. Write a program to multiply two matrices. Lab - Advanced Java
Programming
import Java.util.Scanner;
NOTES
public class MatrixMultiplication
{
public static void main(String args[])
{
int m, n, p, q, sum = 0, i, j, k;
if (n != p)
System.out.println (“The matrices can’t be multiplied
with each other.”);
else
{
Self-Instructional
Material 13
Lab - Advanced Java int second[][] = new int[p][q];
Programming
int multiply[][] = new int[m][q];
System.out.print (“\n”);
}
}
}
}
Self-Instructional
14 Material
Output: Lab - Advanced Java
Programming
NOTES
Output:
Try Yourself
1. Write a program to print sum of diagonal values of a square matrix.
2. Write a program to find largest and smallest element in a matrix.
3. Write a Java program that searches a value in an m x n matrix.
4. Write a program to calculate area of a circle, a rectangle or a triangle
depending on input using overloaded calculate function.
Self-Instructional
16 Material
14. Write a Java program to implement the SQL login ID commands using Lab - Advanced Java
Programming
JDBC.
package Javaapplication5;
import Java.sql.*; NOTES
import Java.awt.*;
import Javax.swing.*;
public class NewJFrame extends Javax.swing.JFrame
{
public NewJFrame() {
initComponents();
}
private void initComponents() {
jTextField1 = new Javax.swing.JTextField();
jTextField2 = new Javax.swing.JTextField();
jButton1 = new Javax.swing.JButton();
jLabel1 = new Javax.swing.JLabel();
jLabel2 = new Javax.swing.JLabel();
setDefaultCloseOperation(Javax.swing.Window
Constants.EXIT_ON_CLOSE);
jButton1.setText(“Login”);
jButton1.addActionListener(new
Java.awt.event.ActionListener()
{
public void actionPerformed(Java.awt.event.ActionEvent
evt)
{
jButton1ActionPerformed(evt);
}
});
private void jButton1ActionPerformed(Java.awt.
event.ActionEvent evt)
{
try
{
// Connection conn;
Self-Instructional
Material 17
Lab - Advanced Java Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Programming
String url = “Jdbc:Odbc:g2”;
Connection conn = DriverManager.getConnection(url);
NOTES ResultSet rs;
Statement stmt=conn.createStatement();
rs=stmt.executeQuery(“select * from mytab”);
while(rs.next())
{
if(((jTextField1.getText()).equals(rs.getString(1)))&&
((jTextField2.getText()).equals(rs.getString(2)))){
JOptionPane.showMessageDialog(this, “login
successfull”);
System.exit(0);
}}
JOptionPane.showMessageDialog(this, “login
unsuccessfull”);
System.exit(0);
conn.close();
}
catch (Exception e) {
System.err.println(“Got an exception! “);
System.err.println(e.getMessage());
}
}
}
Output:
Self-Instructional
18 Material
15. Write a Java program to implement the SQL commands using JDBC. Lab - Advanced Java
Programming
package opertiondemo;
import Java.sql.*;
import Javax.swing.*; NOTES
public class operationdemo1 extends Javax.swing.JFrame {
ResultSet rs1;
/** Creates new form operationdemo1 */
public operationdemo1() {
initComponents();
try
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
String url = “Jdbc:Odbc:g4”;
Connection conn = DriverManager.getConnection(url);
Statement stmt=conn.createStatement
(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_
UPDATABLE);
}
catch (Exception e) {
System.err.println(“Got an exception! “);
System.err.println(e.getMessage());
}
}
private void jButton1ActionPerformed(Java.awt.event.
ActionEvent evt)
{
try
{System.out.println(“Outside rs1”);
if(rs1.next()){
System.out.println(“Inside rs1”);
String r1=rs1.getString(1);
String n1=rs1.getString(2);
Self-Instructional
Material 19
Lab - Advanced Java String a1=rs1.getString(3);
Programming
jTextField1.setText(r1);
jTextField2.setText(n1);
NOTES jTextField3.setText(a1);
}
else
{
JOptionPane.showMessageDialog(this, “eND OF THE
RECORD”);
}
}catch(Exception e)
{}
}
private void jButton3ActionPerformed(Java.awt.event.
ActionEvent evt) {
try
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
String url = “Jdbc:Odbc:g4”;
Connection conn = DriverManager.getConnection(url);
ResultSet rs;
Statement stmt=conn.createStatement();
String qry=(“Insert into student
values(‘“+jTextField1.getText()+”’,’”+jTextField2.getText()+”’,
’”+jTextField3.getText()+”’)”);
stmt.executeUpdate(qry);
JOptionPane.showMessageDialog(this, “Record
inserted”);
conn.close();
}
catch (Exception e)
{
System.err.println(“Got an exception! “);
System.err.println(e.getMessage());
}
}
Self-Instructional
20 Material
private void jButton7ActionPerformed(Java.awt. Lab - Advanced Java
Programming
event.ActionEvent evt) {
try
{System.out.println(“Outside rs1”);
NOTES
if(rs1.previous()){
System.out.println(“Inside rs1”);
String r1=rs1.getString(1);
String n1=rs1.getString(2);
String a1=rs1.getString(3);
jTextField1.setText(r1);
jTextField2.setText(n1);
jTextField3.setText(a1);
}
}catch(Exception e)
{}
}
private void jButton5ActionPerformed(Java.awt.
event.ActionEvent evt) {
// TODO add your handling code here:
try
{
// Connection conn;
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
String url = “Jdbc:Odbc:g4”;
Connection conn = DriverManager.getConnection(url);
ResultSet rs;
Statement stmt=conn.createStatement(ResultSet.
TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
rs=stmt.executeQuery(“select * from student”);
rs.first();
String r=rs.getString(1);
String n=rs.getString(2);
String a=rs.getString(3);
jTextField1.setText(r);
jTextField2.setText(n);
jTextField3.setText(a);
Self-Instructional
Material 21
Lab - Advanced Java conn.close();
Programming
}
catch (Exception e) {
NOTES System.err.println(“Got an exception! “);
System.err.println(e.getMessage());
}
}
private void jButton6ActionPerformed(Java.awt.event.
ActionEvent evt) {
// TODO add your handling code here:
try
{
// Connection conn;
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
String url = “Jdbc:Odbc:g4”;
Connection conn = DriverManager.getConnection(url);
ResultSet rs;
Statement stmt=conn.createStatement(ResultSet.
TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
rs=stmt.executeQuery(“select * from student”);
rs.last();
String r=rs.getString(1);
String n=rs.getString(2);
String a=rs.getString(3);
jTextField1.setText(r);
jTextField2.setText(n);
jTextField3.setText(a);
conn.close();
}
catch (Exception e) {
System.err.println(“Got an exception! “);
Self-Instructional
22 Material
System.err.println(e.getMessage()); Lab - Advanced Java
Programming
}
} NOTES
try
{
// Connection conn;
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
String url = “Jdbc:Odbc:g4”;
Connection conn = DriverManager.getConnection(url);
ResultSet rs;
conn.close();
}
catch (Exception e) {
System.err.println(“Got an exception! “);
System.err.println(e.getMessage());
}
try
NOTES {
// Connection conn;
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
String url = “Jdbc:Odbc:g4”;
Connection conn = DriverManager.getConnection(url);
Statement stmt=conn.createStatement();
stmt.executeUpdate(“delete * from student where
rollnum=”+jTextField1.getText()+””);
JOptionPane.showMessageDialog(this, “Record
deleted”);
jTextField1.setText(“ “);
jTextField2.setText(“ “);
jTextField3.setText(“ “);
conn.close();
}
catch (Exception e) {
System.err.println(“Got an exception! “);
System.err.println(e.getMessage());
}
try
{
// Connection conn;
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
String url = “Jdbc:Odbc:g4”;
Connection conn = DriverManager.getConnection(url);
ResultSet rs;
Statement stmt=conn.createStatement();
rs=stmt.executeQuery(“Select * from student”);
while(rs.next())
{
String r=rs.getString(1);
String n=rs.getString(2);
String a=rs.getString(3);
jTextField1.setText(r);
jTextField2.setText(n);
jTextField3.setText(a);
}
conn.close();
}
catch (Exception e) {
System.err.println(“Got an exception! “);
System.err.println(e.getMessage());
}}}
Self-Instructional
Material 25
Lab - Advanced Java Output:
Programming
NOTES
import Java.sql.*;
import Javax.swing.*;
public class NewJFrame extends Javax.swing.JFrame {
public NewJFrame() {
initComponents();
}
Output:
NOTES /**
* @param args the command line arguments
*/
// Database credentials
static final String USER = “root”;
static final String PASS = “”;
try
{
//STEP 1: Register JDBC driver
Class.forName(“com.mysql.jdbc.Driver”);
Self-Instructional
28 Material
String createTable = “CREATE TABLE REGISTRATION“ + Lab - Advanced Java
Programming
“(id INTEGER not NULL, “ +
“ name VARCHAR(255), “ +
“ age INTEGER, “ + NOTES
“ PRIMARY KEY ( id ))”;
stmt.executeUpdate(createTable);
System.out.println(“Created table in given database...”);
}
catch(SQLException | ClassNotFoundException se)
{
//Handle errors for JDBC
se.printStackTrace ();
}
//Handle errors for Class.forName
Finally
{
Self-Instructional
Material 29
Lab - Advanced Java //finally block used to close resources
Programming
try
{
NOTES if (stmt!=null)
conn.close();
}
catch (SQLException se)
{
System.out.println (“Warnings: “+warn);
se.printStackTrace ();
}// do nothing
try
{
if (conn!=null)
conn.close();
}
catch(SQLException se)
{
se.printStackTrace();
}//end finally try
}//end try
System.out.println(“Goodbye!”);
}//end main
}//end
Output:
Self-Instructional
30 Material
18. Write a program to demonstrate the concept of SQL exception, SQL Lab - Advanced Java
Programming
warning.
package jdbc;
import Java.sql.Connection; NOTES
import Java.sql.DriverManager;
import Java.sql.SQLException;
import Java.sql.SQLWarning;
import Java.sql.Statement;
{
// JDBC database URL
static final String DB_URL = “jdbc:mysql://
localhost:3306/demo”;
// Database credentials
static final String USER = “root”;
static final String PASS = “”;
try
{
//STEP 1: Register JDBC driver
Class.forName(“com.mysql.jdbc.Driver”);
Self-Instructional
Material 31
Lab - Advanced Java //STEP 3: Execute a query for table creation
Programming
System.out.println(“Creating table in given database...”);
stmt = conn.createStatement();
NOTES
String createTable = “CREATE TABLE REGISTRATION “ +
“(id INTEGER not NULL, “ +
“ name VARCHAR(255), “ +
“ age INTEGER, “ +
“ PRIMARY KEY ( id ))”;
stmt.executeUpdate(createTable);
System.out.println(“Created table in given database...”);
}
catch(SQLException | ClassNotFoundException se)
{
Self-Instructional
32 Material
//Handle errors for JDBC Lab - Advanced Java
Programming
se.printStackTrace();
}
//Handle errors for Class.forName NOTES
finally
{
//finally block used to close resources
try
{
if(stmt!=null)
conn.close();
}
catch(SQLException se)
{
System.out.println(“Warnings: “+warn);
se.printStackTrace();
}// do nothing
try
{
if(conn!=null)
conn.close();
}
catch(SQLException se)
{
se.printStackTrace();
}//end finally try
}//end try
System.out.println(“Goodbye!”);
}//end main
}//end JDBCExample
Self-Instructional
Material 33
Lab - Advanced Java Output:
Programming
NOTES
19. Write a program using TCP/IP client sockets and TCP/IP server
sockets.
Client Program
import Java.io.DataInputStream;
import Java.io.DataOutputStream;
import Java.io.IOException;
import Java.io.InputStream;
import Java.io.OutputStream;
import Java.net.Socket;
Self-Instructional
34 Material
port “ + port); Lab - Advanced Java
Programming
try (Socket client = new Socket(serverName,
port))
{
NOTES
System.out.println(“Just connected to “ + client.getRemote
SocketAddress());
OutputStreamoutToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
Server Program
import Java.io.DataInputStream;
import Java.io.DataOutputStream;
import Java.io.IOException;
import Java.net.ServerSocket;
import Java.net.Socket;
import Java.net.SocketTimeoutException;
import Java.util.Scanner;
Self-Instructional
Material 35
Lab - Advanced Java private final ServerSocketserverSocket;
Programming
System.out.println(“Just connected to “ +
server.getRemoteSocketAddress());
DataInputStream in = new DataInputStream
(server.getInputStream());
System.out.println(in.readUTF());
DataOutputStream out = new DataOutputStream
(server.getOutputStream());
out.writeUTF(“Thank you for connecting to “ +
server.getLocalSocketAddress()
+ “\nGoodbye!”);
server.close();
}
catch (SocketTimeoutException s)
{
System.out.println(“Socket timed out!”);
break;
}
Self-Instructional
36 Material
catch (IOException e) Lab - Advanced Java
Programming
{
e.printStackTrace();
break; NOTES
}
}
}
Output:
Self-Instructional
Material 37
Lab - Advanced Java
Programming
NOTES
import Java.rmi.registry.LocateRegistry;
import Java.rmi.registry.Registry;
{
System.err.println(“Client exception: “ + e.toString());
Self-Instructional
38 Material
e.printStackTrace(); Lab - Advanced Java
Programming
}
}
} NOTES
Server Program
import Java.rmi.registry.Registry;
import Java.rmi.registry.LocateRegistry;
import Java.rmi.RemoteException;
import Java.rmi.server.UnicastRemoteObject;
registry.bind(“Hello”, stub);
System.err.println(“Server ready”);
}
catch (Exception e)
{
Self-Instructional
Material 39
Lab - Advanced Java System.err.println(“Server exception: “ + e.toString());
Programming
e.printStackTrace();
}
NOTES }
}
Hello Interface
import Java.rmi.Remote;
import Java.rmi.RemoteException;
import Java.rmi.*;
interface Bank extends Remote
{
double getAmount(double p,double t) throws RemoteException;
}
Self-Instructional
40 Material
Bank Server Lab - Advanced Java
Programming
import Java.rmi.*;
import Java.rmi.server; NOTES
public class BankImpl extends UnicastRemoteObject
implements Bank
{
public BankImpl throws RemoteException
{
}
double getAmount(double p,double t) throws RemoteException
{
return p*Math.pow(1.41,t);
}
}
RMI Registry
import Java.rmi.*;
import Javax.naming.*;
public class BankServer
{
public static void main(String args[])
{
BankImpl centralbank=new BankImpl();
Naming.rebind(“uti”,centralbank);
}
}
Bank Client
import Java.rmi.*;
import Javax.naming.*;
public class Bankclient
{
public static void main(String args[]) throws
RemoteException
Self-Instructional
Material 41
Lab - Advanced Java {
Programming
String url=”rmi://localHost//uti”;
Bank b=(Bank) Naming.lookup(url);
NOTES System.out.println(b.getAmount(4000,3));
}
}
22. Write a simple programs using Bean Development Kit and JAR files.
Main Class
public Student()
{}
Self-Instructional
42 Material
public void setRoll(int roll) Lab - Advanced Java
Programming
{
this.roll=roll;
} NOTES
Output:
Design Patterns
Design Patterns are very popular among software developers. A design pattern is
a well described solution to a common software problem. Design Patterns are
already defined and provides industry standard approach to solve a recurring
problem, so it saves time if we sensibly use the design pattern. There are many
Java design patterns that we can use in our Java based projects. It leads to faster
development since design patterns are already defined and debug.
Self-Instructional
Material 43
Lab - Advanced Java There are two Categories of design patterns:
Programming
1. Core Java (or JSE) design patterns
2. JEE design patterns
NOTES
These categories are further divided in subcategories:
1. Core Java design patterns
Creational design pattern
Structural design pattern
Behavioral design pattern
2. JEE design patterns
Self-Instructional
44 Material
frm.setLayout(null); Lab - Advanced Java
Programming
frm.setVisible(true);
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
} NOTES
public void actionPerformed(ActionEvent e)
{
greet();
}
Output:
Self-Instructional
Material 45
Lab - Advanced Java
Programming
NOTES
Self-Instructional
46 Material
out.println(docType + “<html>\n” + “<head><title>” Lab - Advanced Java
Programming
+ title + “</title></head>\n” +
“<body bgcolor = \”#f0f0f0\”>\n” + “<h1
align = \”center\”>” + title + “</h1>\n” + NOTES
“<ul>\n” +
“ <li><b>First Name</b>: “
+ request.getParameter(“first_name”) +
“\n” + “ <li><b>Last Name</b>: “
+ request.getParameter(“last_name”) + “\n” +
“</ul>\n” +
“</body>\n”+
“</html>”
);
}
doGet(request, response);
}
}
Output:
Self-Instructional
Material 47
Lab - Advanced Java
Programming
NOTES
response.setContentType(“text/html”);
PrintWriter out = response.getWriter();
HttpSession session=request.getSession();
session.setAttribute(“uname”,username);
Self-Instructional
48 Material
out.print(“\n<a href=’servlet2'>visit</a>”); Lab - Advanced Java
Programming
out.close();
NOTES
}
catch(IOException e)
{
System.out.println(e);
}
}
// Program:
import Java.io.*;
import Javax.servlet.http.*;
Self-Instructional
Material 49
Lab - Advanced Java out.println(“<br><br>—————————————————————————<br>”);
Programming
out.println(“Content from session......<br>”);
HttpSession session=request.getSession(false);
NOTES String n=(String)session.getAttribute(“uname”);
out.print(“Hello “+n);
out.close();
}
catch(IOException e)
{
System.out.println(e);
}
}
}
26. Write a servlet program to set some cookies, send it to browser, print
cookie information and send it as HTML response.
package com.journaldev.servlet.cookie;
import Java.io.IOException;
import Java.io.PrintWriter;
import Javax.servlet.ServletException;
import Javax.servlet.annotation.WebServlet;
import Javax.servlet.http.Cookie;
import Javax.servlet.http.HttpServlet;
import Javax.servlet.http.HttpServletRequest;
import Javax.servlet.http.HttpServletResponse;
@WebServlet(“/cookie/SetCookie”)
public class SetCookie extends HttpServlet {
private static final long serialVersionUID = 1L;
private static int count = 0;
Self-Instructional
50 Material
PrintWriter out = response.getWriter(); Lab - Advanced Java
Programming
Cookie[] requestCookies = request.getCookies();
out.write(“<html><head></head><body>”); NOTES
out.write(“<h3>Hello Browser!!</h3>”);
if(requestCookies != null){
out.write(“<h3>Request Cookies:</h3>”);
for(Cookie c : requestCookies){
out.write(“Name=”+c.getName()+”,
Value=”+c.getValue()+”, Comment=”+c.getComment()
+”, Domain=”+c.getDomain()+”,
MaxAge=”+c.getMaxAge()+”, Path=”+c.getPath()
+”, Version=”+c.getVersion());
out.write(“<br>”);
}
}
//Set cookies for counter, accessible to only this
servlet
count++;
Cookie counterCookie = new Cookie(“Counter”,
String.valueOf(count));
//add some description to be viewed in browser
cookie viewer
counterCookie.setComment(“SetCookie Counter”);
//setting max age to be 1 day
counterCookie.setMaxAge(24*60*60);
//set path to make it accessible to only this
servlet
counterCookie.setPath(“/ServletCookie/cookie/
SetCookie”);
out.write(“</body></html>”);
NOTES }
}
27. Write a Java program for session tracking to find out the creation time
and the last accessed time for a session using the HttpSession object.
In the following Java program the HttpSession object is used for finding out the
time of session creation and also the time when the session was last accessed. The
program will create a new session with the request if the session does not exist.
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
Self-Instructional
54 Material
@WebServlet(“/SessionManagementExample”) Lab - Advanced Java
public class SessionManagementExample extends HttpServlet Programming
{
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, NOTES
HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType(“text/html”);
PrintWriter out = response.getWriter();
HttpSession session = request.getSession();
Date creationTime= new Date(session.getCreationTime());
Date lastAccessedTime= new
Date(session.getLastAccessedTime());
session.setMaxInactiveInterval(1000);
Integer count;
count = (Integer)session.getAttribute(“Count”);
if (count == null)
{
count = 0;
}
else
{
count = new Integer(count + 1);
}
session.setAttribute(“Count”, count);
try
{
out.println(“<h2>Sevlet Session Example</h2>”);
if(count==0 || count==1)
{
out.println(“<b>In current session this site is accessed “
+ count + “ time.</b>”);
}
else
out.println(“<b>In current session this site is accessed
“+ count + “times. </b>”);
out.println(“<br>Session ID = (“ + session.getId() + “)</
br>”);
out.println(“<br>Session creation time =
(“+creationTime+”)”);
out.println(“<br>Session last accessed time
(“+lastAccessedTime+”)”);
out.println(“<br>Max inactive interval of session is
“+session.getMaxInactiveInterval());
out.println(“<br>The complete url =
“+request.getRequestURL());
out.println(“<br>Part of this url =
“+request.getRequestURI());
}
catch(Exception ex)
{ Self-Instructional
Material 55
Lab - Advanced Java out.println(ex);
Programming }
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
NOTES throws ServletException, IOException
{
doGet(request,response);
}
}
Output :
Self-Instructional
56 Material
add(button2); Lab - Advanced Java
} Programming
}
Output:
NOTES
Output:
Self-Instructional
Material 57
Lab - Advanced Java 31. Write a program for creating a tree using JApplet.
Programming
import Javax.swing.*;
import Javax.swing.tree.DefaultMutableTreeNode;
public class TreeExample
NOTES {
JFrame f;
TreeExample(){
f=new JFrame();
DefaultMutableTreeNode style=new DefaultMutableTreeNode
(“Style”);
DefaultMutableTreeNodecolor=new DefaultMutableTreeNode
(“color”);
DefaultMutableTreeNode font=new DefaultMutableTreeNode
(“font”);
style.add(color);
style.add(font);
DefaultMutableTreeNode red=new DefaultMutableTreeNode
(“red”);
DefaultMutableTreeNode blue=new DefaultMutableTreeNode
(“blue”);
DefaultMutableTreeNode black=new DefaultMutableTreeNode
(“black”);
DefaultMutableTreeNode green=new DefaultMutableTreeNode
(“green”);
color.add(red); color.add(blue); color.add(black);
color.add(green);
JTreejt=new JTree(style);
f.add(jt);
f.setSize(200,200);
f.setVisible(true);
}
public static void main(String[] args)
{
new TreeExample();
}
}
Output:
Self-Instructional
58 Material
32. Write a program to create panes in Java Applet. Lab - Advanced Java
Programming
import Javax.swing.*;
public class TabbedPaneExample
{
JFrame f; NOTES
TabbedPaneExample()
{
f=new JFrame();
JTextArea ta=new JTextArea(200,200);
JPanel p1=new JPanel();
p1.add(ta);
JPanel p2=new JPanel();
JPanel p3=new JPanel();
JTabbedPanetp=new JTabbedPane();
tp.setBounds(50,50,200,200);
tp.add(“main”,p1);
tp.add(“visit”,p2);
tp.add(“help”,p3);
f.add(tp);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args)
{
new TabbedPaneExample();
}
}
Output:
33. Write a Java program for sum of two numbers using Applet.
import Java.awt.*;
import Java.applet.*;
/*Coding of HTML File <applet code = abc1.class width= 200
Self-Instructional
Material 59
Lab - Advanced Java height=200> </applet> */
Programming public class abc1 extends Applet
{
public void paint(Graphics g)
{
NOTES int a=100;
int b=200;
int sum = a+b;
String s = “The Sum is :” + String.valueOf(sum);
g.drawString( s, 200,100);
} }
Output:
34. Write a Java Program for Applet using drawString (), drawRect () and
drawOval ().
import Java.awt.*;
import Java.applet.*;
/*<applet code= “Objectdraw.class” height=400 width=400>
</applet>*/
public class Objectdraw extends Applet
{
public void paint(Graphics g)
{
g.drawString(“Hello World”,20,20);
g.drawRect(40,40,30,50);
g.drawOval(150,150,40,50);
} }
Self-Instructional
60 Material
Output: Lab - Advanced Java
Programming
NOTES
Output:
Output:
Self-Instructional
Material 63
Lab - Advanced Java
Programming
NOTES
37. Write a Java program that prints a message by clicking on the button
using AWT Events and Applets.
import Java.applet.*;
import Java.awt.*;
import Java.awt.event.*;
public class EventApplet extends Applet implements
ActionListener
{
Button b;
TextField tf;
public void init()
{
tf=new TextField();
tf.setBounds(30,40,150,20);
b=new Button(“Click”);
b.setBounds(80,150,60,50);
add(b);add(tf);
b.addActionListener(this);
setLayout(null);
}
NOTES
Output:
Self-Instructional
Material 65
Lab - Advanced Java 39. Write a Java program to demonstrate an application involving GUI
Programming
with controls menus and event handling.
import Javax.swing.*;
public class SwingMenu
NOTES {
public static void main(String[] args)
{
SwingMenu s = new SwingMenu();
}
public SwingMenu()
{
JFrame frame = new JFrame(“Creating a JMenuBar, JMenu,
JMenuItem and seprator Component”);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menubar = new JMenuBar();
JMenu filemenu = new JMenu(“File”);
filemenu.add(new JSeparator());
JMenu editmenu = new JMenu(“Edit”);
editmenu.add(new JSeparator());
JMenuItem fileItem1 = new JMenuItem(“New”);
JMenuItem fileItem2 = new JMenuItem(“Open”);
JMenuItem fileItem3 = new JMenuItem(“Close”);
fileItem3.add (new JSeparator());
JMenuItem fileItem4 = new JMenuItem (“Save”);
JMenuItem editItem1 = new JMenuItem (“Cut”);
JMenuItem editItem2 = new JMenuItem (“Copy”);
editItem2.add (new JSeparator());
JMenuItem editItem3 = new JMenuItem (“Paste”);
JMenuItem editItem4 = new JMenuItem (“Insert”);
filemenu.add(fileItem1); filemenu.add(fileItem2);
filemenu.add(fileItem3); filemenu.add(fileItem4);
editmenu.add(editItem1);
editmenu.add(editItem2);
editmenu.add(editItem3);
editmenu.add(editItem4);
menubar.add(filemenu);
menubar.add(editmenu);
frame.setJMenuBar(menubar);
frame.setSize(400,400);
frame.setVisible(true);
} }
Output:
Self-Instructional
66 Material
Lab - Advanced Java
Programming
NOTES
@Override
public void paint(Graphics g)
{
Graphics2D g1 = (Graphics2D) g;
Font font1 = new Font (“Serif”, Font.PLAIN, 24);
g1.setFont (font1);
g1.setColor (Color.BLUE);
g1.drawString (“Welcome in Java AWT class”, 50, 70);
Self-Instructional
Material 67
Lab - Advanced Java Graphics2D g2 = (Graphics2D) g;
Programming Font font2 = new Font (“Times New Roman”, 2, 24);
g2.setFont (font2);
g2.setColor (Color.BLACK);
g2.drawString (“Welcome in Java AWT class”, 50, 120);
NOTES }
}
Self-Instructional
68 Material