ajp

38
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC - 27001 - 2005 Certified) WINTER 13 EXAMINATION Subject Code: 12259 Model Answer Subject Name: Advanced Java Programming ____________________________________________________________________________________________________ Page 1 of 38 Important Instructions to examiners: 1) The answers should be examined by key words and not as word-to-word as given in themodel answer scheme. 2) The model answer and the answer written by candidate may vary but the examiner may tryto assess the understanding level of the candidate. 3) The language errors such as grammatical, spelling errors should not be given moreImportance (Not applicable for subject English and Communication Skills). 4) While assessing figures, examiner may give credit for principal components indicated in thefigure. The figures drawn by candidate and model answer may vary. The examiner may givecredit for anyequivalent figure drawn. 5) Credits may be given step wise for numerical problems. In some cases, the assumed constantvalues may vary and there may be some difference in the candidate’s answers and model answer. 6) In case of some questions credit may be given by judgement on part of examiner of relevantanswer based on candidate’s understanding. 7) For programming language papers, credit may be given to any other program based on equivalentconcept. 1. A) Attempt any three of the following: Marks 12 a) List any eight controls from java. awt package. 4 (Each ½ Mark any Eight) Ans: 1. Label 2. Button 3. Checkbox 4. Choice list 5. List 6. Scrollbar 7. Text Field 8. Text Area 9. Menu and Menubar 10. Canvas

Upload: arshinchougle

Post on 29-Nov-2014

251 views

Category:

Engineering


4 download

DESCRIPTION

 

TRANSCRIPT

Page 1: AJP

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 1 of 38

Important Instructions to examiners

1) The answers should be examined by key words and not as word-to-word as given in themodel

answer scheme

2) The model answer and the answer written by candidate may vary but the examiner may tryto

assess the understanding level of the candidate

3) The language errors such as grammatical spelling errors should not be given moreImportance

(Not applicable for subject English and Communication Skills)

4) While assessing figures examiner may give credit for principal components indicated in

thefigure The figures drawn by candidate and model answer may vary The examiner may

givecredit for anyequivalent figure drawn

5) Credits may be given step wise for numerical problems In some cases the assumed

constantvalues may vary and there may be some difference in the candidatersquos answers and model

answer

6) In case of some questions credit may be given by judgement on part of examiner of

relevantanswer based on candidatersquos understanding

7) For programming language papers credit may be given to any other program based on

equivalentconcept

1 A) Attempt any three of the following Marks 12

a) List any eight controls from java awt package 4

(Each frac12 Mark any Eight)

Ans

1 Label

2 Button

3 Checkbox

4 Choice list

5 List

6 Scrollbar

7 Text Field

8 Text Area

9 Menu and Menubar

10 Canvas

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 2 of 38

b) Explain use of button control in AWT with example 4

(Defination-1 Mark Methods-1 Mark Example-2 Marks)

Ans A button is a component that contains a label and that generates an event when it is pressed

buttons are object of type Button Button defines

Button()

Button(String str)

After a button has been createdyou can set its label by calling setLabel()

You can retrieve its label by calling getLabel()

Void setLabel(String str)

String getLabel()

Example

import javaawt

import javaapplet

ltapplet code=rdquoMyButtonDemordquo width=250

Height=150gt

ltappletgt

public class mybuttondemo extends Applet

Button okcancelapply

public void init()

ok= new Button(ldquookrdquo)

cancel= new Button(ldquocancelrdquo)

apply= new Button(ldquoapplyrdquo)

add(ok)

add(cancel)

add(apply)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 3 of 38

c) List four differences between TCP and UDP 4

(Any four Points -1 Mark each)

Ans

TCP UDP

It is connection Oriented It is connectionless

It gives acknowledgement It does not give acknowledgement

It is reliable It is unreliable

It is use to transfer for large amount of

data It is use to transfer for small amont of data

Transmission seed is low Transmission seed is High

TCP header size is 20 bytes UDP Header size is 8 bytes

TCP does error checking UDP does error checking but no recovery

options

d) Write three factory method of InetAddress class 4

(Three method- 4 Marks)

Ans The Inet class has no invisible constructor

To create an Inet address objectyou have to use one of the available factory methods

Factory methods are merely aconvention whereby static methods in a class returns an instance of

that class

Three commonly used InetAddress factory methods are

1) static InetAddress getLocalHost()

throws unKnownHostException

This method simply returns the InetAddress object that represents the local host

2) static InetAddress getByName(String hostname)

throws unKnownHostException

This method simply returns the InetAddress for a host name passed to it

3) static InetAddress[] getAllByName(String hostname)

throws unKnownHostException

which takes an IPaddress and returns an InetAddress object

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 4 of 38

B) Attempt any one of the following Marks 6

a) List various types of JDBC drives Explain JDBC-ODBC bridge driver

(Types-2 Marks Bridge driver diagram - 1 Marks Discription-3 Marks)

Ans Type 1 JDBC-ODBC bridge

Type 2 JDBC-native API

Type 3100 pure java JDBC network

Type 4100 java

JDBC-ODBC bridge

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 5 of 38

This category works with ODBC drivers supplied by your database vendor or a third party

To use the bridge you must first have an ODBC driver specifically for you database and

additional software that you need for connectivity

Using ODBC also requires configuring on your system a DNS that represents the target database

Advantages

1) It offers the ability to connect to almost all databases on almost all platforms

2) It may be the only way to gain access to some low and desktop database and application

Disadvantages

1) ODBC driver must also be loaded on the target machine

2) Translation between JDBC and ODBC affects performance

b) Write a program to demonstrate the use of JScrollpane in swing

(Any 1 program- Applet tag-2mark correct logic-4 Marks Synatax-2 Marks)

Ans import javaawt

import javaxswing

ltapplet code=rdquoJScrollPaneDemordquo width=350

Height=250gt

ltappletgt

Public class JscrollPaneDemo extends JApplet

Public void init()

Container contentPane= get ContentPane()

contentPanesetLayout(new BorderLayout())

JPanel jp = new JPanel()

jpsetLayout(new GridLayout(2020))

int b=0

for(int i=0ilt20i++)

jpadd(new JButton(ldquoButtonrdquo+b)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 6 of 38

++b

int v=ScrollPaneConstantsVERTICAL_SCROLLBAR_AS_NEEDED

int h= ScrollPaneConstantsHORIZONTAL_SCROLLBAR_AS_NEEDED

JScrollPane jsp= new JScrollPane(jpvh)

contentPaneadd(jspBorderLayoutCENTER)

2 Attempt any two of the following Marks 16

a) Write an application program making use of menu and menu bar class 8

(Applet tag ndash 1Mark correct logic to add menu and menubar - 5 Marks Synatax-2 Marks)

Ans import javaawt

import javaawtevent

import javaapplet

ltapplet code=rdquo MenuFramerdquo width=350

Height=250gt

ltappletgt

class MenuFrame extends Frame implements ActionListener

String msg=rdquordquo

MenuFrame(String title)

super(title)

MenuBar mbar= new menuBar()

setMentBar(mbar)

Menu file=new Menu(ldquoFilerdquo)

MenuItem item1item2item3item4item5

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 7 of 38

item1= new MenuItem (ldquoNewrdquo)

item2= new MenuItem (ldquoopenrdquo)

item3= new MenuItem (ldquocloserdquo)

item4= new MenuItem (ldquo-rdquo)

item5= new MenuItem (ldquoQuitrdquo)

fileadd(item1)

fileadd(item2)

fileadd(item3)

fileadd(item4)

fileadd(item5)

mbaradd(file)

MenuItem item6item7item8item9

item6= new MenuItem (ldquocutrdquo)

item7= new MenuItem (ldquocopyrdquo)

item8= new MenuItem (ldquopasterdquo)

item9= new MenuItem (ldquo-rdquo)

editadd(item6)

editadd(item7)

editadd(item8)

editadd(item9)

mbaradd(edit)

item1addActionListener(this)

item2addActionListener(this)

item3addActionListener(this)

item4addActionListener(this)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 8 of 38

item5addActionListener(this)

item6addActionListener(this)

item7addActionListener(this)

item8addActionListener(this)

item9addActionListener(this)

Public void paint(Graphics g)

gdrawString(msg10200)

public void actionPerformed(ActionEvent e)

msg= ldquoYou have selected rdquo+ egetActionCommand()

repaint()

public static void main(String args[])

MenuFrame m=new MenuFrame(ldquoMyMenurdquo)

msetVisible(true)

msetSize(100200)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 9 of 38

b) Give the use of Server Socket and Socket class Describe the steps that are 8

required to establish communication between client and server sockets

(Use-2 Marks each class Steps-4 Marks)

Ans Server socket

A Server Socket handles the requests and sends back an appropriate reply The actual tasks that a

server socket must accomplish are implemented by an internal SocketImpl instance A server

socket waits for requests to come in over the network It performs some operation based on that

request and then possibly returns a result to the requester The actual work of the server socket is

performed by an instance of the SocketImpl class An application can change the socket factory

that creates the socket implementation to configure itself to create sockets appropriate to the local

firewall

Client socket

we have used the class named ClientSocketInformationjava that implement the constructor of

the Socket class passing two arguments as hostName and TIME_PORT This program throws an

IOException for the exception handling This exception is thrown to indicate an IO problem of

some sort occurred Here we are going to explore a method to retrieve the host name of the local

system in a very simple way In this way we find out the Local address Local host information

reuseAddress and address of the local system in a very simple manner

Steps to connect

Using TCP socket provides the communication mechanism between two computers A client

program creates a socket at its end of the communication and attempts to connect that socket to a

server

The following is the lists of sequential steps which occur when establishing a TCP connection

between client socket and server socket

1 The server initiates a Server Socket object and mentions which port number communication is

to occur on

2 The server invokes the accept () method of the ServerSocket class This method does the wait

till a client gets connected to the server on the given port

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 10 of 38

After the waiting stages of server a client instantiates a Socket object It also specifies the

server name and port number to which it gets connected

3 The constructor of the Socket class tries to connect the client to the specified server and port

number If the communication is established the client has a Socket object which is capable

of communicating with the server

4 On server side the accept () method returns a reference to a new socket on the server that is

connected to the clientrsquos socket

Once the connection are established communication occur using IO streams Each socket has

both an Outputstream and InputStreams

As we know that the TCP is a two way communication protocol So data can be sent across

both streams at the same time

Two constructors used to create client socket

Socket (String hostnameint port)

Creates a socket connection the localhost to name host and port

Socket(InetAddress ipAddressint port)

Creates a socket using pre existing InetAddress object and a port

A socket can be examined at any time for the address and port information associated with it

InetAddress getInetAddress()

Int getPort()

Int getLocalPort()

Once the socket object has been created it can be examined to gain access to ip and op streams

associated with it

Example (optional)

import javanet

import javaio

class abc

public static void main(String args[])throws Exception

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 11 of 38

int c

Socket s=new socket(ldquointericnetrdquo43)

InputStream in=sgetInputStream()

OutputStream out=sgetOutputStream()

String str=(argslength==0rdquoOsbornecomrdquo)

byte buf[]=strgetBytes()outwrite(buf)

while((c=inread())=-1)

Systemoutprintln(char)c)

sclose()

c) Give sequential steps to use JTabbedPane in an Applet with example

(Steps- 4Marks any one Example- 4Marks)

Ans The general procedure to use a tabbed pane in an applet is

1) Create a JtabbedPane object

2) Call addTab() to add to the pane

3) Repeat step 2 for each tab

4) Add the tabbed pane to the content pane of the applet

Example

import javaxswing

ltapplet code=rdquoJTabbedPaneDemordquo width=350

Height=250gt

ltappletgt

public class JTabbedPaneDemo extends JApplet

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 12 of 38

public void init()

JTabbedPane jtp= new JTabbedPane()

jtpaddTab(ldquocitiesrdquonew citiesPanel())

jtpaddTab(ldquocolorsrdquonew colorsPanel())

jtpaddTab(ldquoFlavourrdquonew flavourPanel())

getContentPane()add(jtp)

class citiespanel extends JPanel

Public citiesPanel()

JButton b1=new Button(ldquoNew Yorkrdquo)

add(b1)

JButton b2=new Button(ldquolondonrdquo)

add(b2)

class colorpanel extends JPanel

Public colorPanel()

JCheckBox cb1=new JCheckBox(ldquoredrdquo)

add(cb1)

JCheckBox cb2=new JCheckBox (ldquogreenrdquo)

add(cb2)

class flavourpanel extends JPanel

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 13 of 38

public flavourPanel()

JComboBox b=new JComboBox()

jcbaddItem(ldquovanillardquo)

jcbaddItem(ldquochocolaterdquo)

add(jcb)

3 Attempt any four of the following Marks 16

a) Example the use of prepared statement with example 4

(Explanation-2 Marks Example-2 Marks)

Ans PrepareStatement ()

The preparedStatement() method creates a PreparedStatement object and returns it as a return

value The Prepared statement object is used to execute dynamic SQL statement against the

databaseA dynamic SQL statement is a statement in which some of the parameters in the

statement are unknown when the statement is created The parameter is placed into the SQL

statement as they are determined by the application When all the parameters are specified for the

SQL statement the dynamic SQL statement will be executed just as a static statement is executed

To create a dynamic SQL statement that takes a first name and last name as parameters use the

following code

try

String sql=rdquoSelect from temployeerdquo + ldquowhere Firstname=rdquo + ldquoand Lastname=rdquo

PreparedStatement p=connectionpreparedStatement(sql)

Catch(SQLException e)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 14 of 38

b) List any four differences between AWT and swing 4

(Any four points ndash 1 Mark each)

Ans

Swing AWT

It uses javaxswing package It uses javaapplet package

It uses JApplet class It uses Applet class

Swing is light weight component AWT is heavy weight component

It does not have add() method to add

control

It has add() method to add control

AWT provides less features than

swing

Swing has variety of component amp

features which is not in AWT

Awt has huge collection of classes amp

interfaces

Swing has bigger collection of classes

amp interfaces than AWT

AWT has predefined formats of

appearance amp behavior of component

Swing provides a facility of different

appearance amp behavior of the same

component

c) List four interfaces in javaxservlet package 4

(Any four points ndash 1 Mark each)

Ans Following are the interfaces in javaxservlet package

1 Servlet All servlets must implement the Servlet interface It declares the init( ) service( )

and destroy( ) methods that are called by the server during the life cycle of a servlet

2 ServletConfig The ServletContextinterface is implemented by the server It enables servlets

to obtain information about their environment

3 ServletContext The ServletContextinterface is implemented by the server It enables

servlets to obtain information about their environment

4 ServletRequest The ServletRequestinterface is implemented by the server It enables a

servlet to obtain information about a client request

5 ServletResponse The ServletResponseinterface is implemented by the server It enables a

servlet to formulate a response for a client

6 SingleThreadModel This interface is used to indicate that only a single thread will execute

the service( ) method of a servlet at a given time It defines no constants and declares no

methods

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 15 of 38

d) Give the use of ImageIcon class with example 4

(Explanation ndash 2 Marks Example- 2 Marks)

Ans In Swing icons are encapsulated by the ImageIconclass which paints an icon from an

image Two of its constructors are shown here

ImageIcon(String filename)

ImageIcon(URL url)

The first form uses the image in the file named filename The second form uses the

image in the resource identified by url

The ImageIconclass implements the Icon interface that declares the methods

As follows

Method Description

intgetIconHeight( ) Returns the height of the iconin pixels

intgetIconWidth( ) Returns the width of the iconin pixels

voidpaintIcon(Component comp Graphics gintx inty)Paints the icon at position x y onthe

graphics context g Additionalinformation about the paintoperation can be provided in comp

Example

import javaawt

import javaxswing

ltapplet code=JLabelDemo width=250 height=150gt

ltappletgt

public class JLabelDemo extends JApplet

public void init()

Get content pane

Container contentPane = getContentPane()

Create an icon

ImageIcon ii = new ImageIcon(francegif)

Create a label

JLabeljl = new JLabel(France ii JLabelCENTER)

Add label to the content pane

contentPaneadd(jl)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 16 of 38

e) Give the use of URL class along with syntax of constructors of URL class 4

(Use - 2 Marks Any two Constructor - 1 Mark each)

Ans The URL provides a reasonably intelligible form to uniquely identify or address information on the

Internet URLs are ubiquitous every browser uses them to identify information on the Web In

fact the Web is really just that same old Internet with all of its resources addressed as URLs plus

HTML

Javas URL class has several constructors One commonly used form specifies the URL with a

string that is identical to what you see displayed in a browser

1 URL(String urlSpecifier)

The next two forms of the constructor allow you to break up the URL into its componentparts

2 URL(String protocolName String hostName intport String path)

3 URL(String protocolName String hostName String path)

Another frequently used constructor allows you to use an existing URL as a referencecontext and

then create a new URL from that context Although this sounds a littlecontorted its really quite

easy and useful

4 URL(URL urlObj String urlSpecifier)

4 A) Attempt any three of the following Marks 12

a) Give the use of following methods of statement interface 4

i) executeQuery( ) ii) execute Update ( )

(Each method ndash 2 Marks)

Ans i) executeQuery()

The executeQuery() method of the statement object enables you to send SQL select statement to

the database and to receive result from the database Executing a query in effect sends a SQL

select statement to the database and returns the appropriate results back in the Resultset object

The executeQuery() method takes a SQL select statement as a parameter and returns a ResultSet

object that contains all the records that match the select statements criteria

ii) executeUpdate()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 17 of 38

The executeUpdate() method of the Statement object enables you to execute SQL update

statements such as delete insert and update The method takes a String containing the SQL update

statement and returns an integers that determines how many records were affected by the SQL

statement

b) Define Layout Manager Describe the use of GridLayout Manager 4

(Layout manager- 2 Marks Use-2 Marks)

Ans Each Container object has a layout manager associated with it A layout manager

is an instance of any class that implements the LayoutManagerinterface The layout

manager is set by the setLayout( ) method If no call to setLayout( ) is made then the

default layout manager is used Whenever a container is resized (or sized for the first

time) the layout manager is used to position each of the components within it

The setLayout( ) method has the following general form

voidsetLayout(LayoutManagerlayoutObj)

GridLayoutManager

GridLayout lays out components in a two-dimensional grid When you instantiate

a GridLayout you define the number of rows and columns The constructors

supported by GridLayoutare shown here

GridLayout( )

GridLayout(intnumRows intnumColumns)

GridLayout(intnumRows intnumColumns inthorz intvert)

c) Explain the use of cookies with example 4

(Explanation - 2 Marks Example - 2 Marks any one)

Ans Cookie is a small piece of information that is passed back and forth in the HTTP request and

response Even though a cookie can be created on the client side using some scripting language

such as JavaScript it is usually created by the server resource such as a Servlet The Cookies sent

by the server when the client requests another page from the same application In Servlet

programming a cookie is represented by a Cookie class in the javaxservlethttp package You can

create a cookie by calling the Cookie class constructor and passing two string objects the name

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 18 of 38

and value of the cookie For instance the following code creates a cookie object called c1The

cookie has the name ldquomyCookierdquo and value of rdquosecretrdquo

Cookie c1=new Cookie(ldquomyCookierdquordquosecretrdquo)

You then can add the cookie to the http response using addCookie method of the

HTTPServletResponse interfaceResponseaddCookie(c1)

Program for Add cookies

import javaio

importjavaxservlet

importjavaxservlethttp

public class AddCookieServlet extends HttpServlet

public void doPost(HttpServletRequest requestHttpServletResponse response)

throwsServletException IOException

Get parameter from HTTP request

String data = requestgetParameter(data)

Create cookie

Cookie cookie = new Cookie(MyCookie data)

Add cookie to HTTP response

responseaddCookie(cookie)

Write output to browser

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgtMyCookie has been set to)

pwprintln(data)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 19 of 38

pwclose()

OR

Program for Get Cookies

import javaio

importjavaxservlet

importjavaxservlethttp

public class GetCookiesServlet extends HttpServlet

public void doGet(HttpServletRequest requestHttpServletResponse response)

throwsServletException IOException

Get cookies from header of HTTP request

Cookie[] cookies = requestgetCookies()

Display these cookies

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgt)

for(inti = 0 iltcookieslength i++)

String name = cookies[i]getName()

String value = cookies[i]getValue()

pwprintln(name = + name +

value = + value)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 20 of 38

pwclose()

d) Give steps to create simple servlet with example 4

(Steps- 2 Marks Any one Example ndash 2 Marks)

Ans Steps 1) Write a java servet code

Steps 2) Compile Servet by setting classpath with servlet-api library

Step 3) Copy the class servlet file in web apps classpath directory

Steps 4) Open the webxml open it and add servlet tag and sevlet mapping tag

Steps 5) Start web server(apche tomcat)

Steps 6) Browse servlet using java compatible browser like IE

Example shows to start create a file named WelcomeServletjava that contains the following

program

import javaio

importjavaxservlet

public class WelcomeServletDemo extends GenericServlet

public void service(ServletRequestrequestServletResponse response) throws

ServletExceptionIOException

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgtWelcome to Servlet)

pwclose()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 21 of 38

B) Attempt any one of the following Marks 6

a) Describe the two ndashtier and three ndashtier database design of JDBC API with neat diagram

(Explanation of Two-tier-2 Marks and Three-tier-2 Marks Diagram ndash 1 Mark each)

Ans Two Tier Architecture

In a two tier model a java application is designed to interact directly with the database

Application functionality is divided into these two layers

1) Application Layer Including the JDBC driver business logic and user interface

2) Database Layer including RDBMS

The interface to the database is handled by the Java Database Connectivity(JDBC) Driver

appropriate to the particularly database management system being accessed The JDBC Driver

passes SQL statements to the database and returns the results of those statements to the

application

A clientserver configuration is the special case of the two tier model where the database is

located on another machine referred to as the server The application runs on the client machine

which is connected to the server over a network Commonly the network is an Intranet using

dedicated database servers to support multiple clients but it can just as easily be the internet

Three Tier Architecture-

In the three tier model the client typically sends requests to an application server forming the

middle tier The application server interprets these requests and formats the necessary SQL

statement to fulfill

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 22 of 38

These requests and sends them to the database The database process the SQL statements and

sends result back to the application server which then sends them to the client

Following are some advantages of Three-tier architecture

1 Performance can be improved by separating the application server and database server

2 Business logic is clearly separated from the database

3 Client application can use a simple protocol such as CGI to access services

The three-tier model show in following fig is a common in web application In this scenario the

client tier is frequently implemented in a browse on a client machine the middle tier is

implemented in a web server with a Servlet engine and the database management system runs on

a dedicated database server

Following are the main components of three tier architecture

1 Client Tier - Typically this is thin presentation layer that may be implemented using a web

browser

2 Middle Tier - This tier handles the business or application logic This may be implemented

using a Servlet engine such as Tomcat or an application server such as JBOSS The JDBC

driver also resides in this layer

3 Data source layer This component includes the RDBMS

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 23 of 38

b) Write servlet which shows how many times user has visited the page in session

(Any Correct Logic ndash4 Marks Syntax ndash 2 Marks)

Ans import javaio

import javaxservlet

import javaxservlethttp

public class Session Travker extends HttpServlet

public void doGet(HttpServletRequest req HttpServletResponse res) throws ServletException

IOException

ressetContentType(ldquotexthtmlrdquo)

PrintWriter out = resgetWriter()

HttpSession session = reqgetSession(true)

Integer count= (Integer)sessiongetValue(ldquotrackercountrdquo)

if(count== null) count=new Interger(1)

else count = new Interger(count intValue() +1)

sessionputValue(ldquotrackercountrdquocount)

outprintln(ldquoltHTMLgtltHEADgtltTITLEgtSession TrackerltTITLEgtltHEADgtrdquo)

outprintln(ldquoltBODYgtltH1gtSession Tracking DemoltH1gtrdquo)

outprintln(ldquoYou have visited this pagerdquo +count +((countintValue() == 1)rdquotimerdquo

ldquotimesrdquo))outprinln(ltPgtrdquo)

outprintln(ldquoltH2gtSesssion dataltH2gtrdquo)

String[] names = sessiongetValueNames()

for(int i=0 ilt nameslength i++)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 24 of 38

outprintln(names[i] + ldquo rdquo + sessiongetvalue(names[i])+ ldquoltBRgtrdquo)

outprintln(ldquoltBODYgtltHTMLgtrdquo)

5 Attempt any two of the following Marks 16

a) Write a program to display all records from Employee table from database using

JDBC

(Assume suitable data for table- Load driver create connection execute Query - 1 Mark

each Display data- 3 Marks Syntax ndash 2 Marks)

Ans import javasql

import javasqlStatement

import javaapplet

import javaawt

public class DisplayTable

public static void main( String args[])

RsultSet rs

Connection conn

try

String s1

ClassforName(sun jdbcodbcJdbcOdbcDriver)

Systemoutprintln(Connecting to a selected database)

String url=rdquojdbcodbcabcrdquo

conn = DriverManagergetConnection(DB_URL USER PASS)

Systemoutprintln(Connected database successfully)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 25 of 38

Systemoutprintln(Creating statement)

stmt = conncreateStatement()

sql = SELECT FROM Employee

ResultSet rs = stmtexecuteQuery(sql)

Tables fields assumed are id first last age

while(rsnext())

int id = rsgetInt(id)

int age = rsgetInt(age)

String first = rsgetString(first)

String last = rsgetString(last)

Systemoutprint(ID + id)

Systemoutprint( Age + age)

Systemoutprint( First + first)

Systemoutprintln( Last + last)

rsclose()

catch(SQLException se)

Handle errors for JDBC

seprintStackTrace()

catch(Exception e)

Handle errors for ClassforName

eprintStackTrace()

finally

finally block used to close resources

try

if(stmt=null)

connclose()

catch(SQLException se)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 26 of 38

b) Define the term

i) Reserved socket ii) proxy server

iii) Datagram iv) URL connection 4

(Each term- 2 Marks)

Ans i) Reserved socket

A socket is one end-point of a two-way communication link between two programs running on

the network Socket classes are used to represent the connection between a client program and a

server program

Reserved socket The socket which are reserved for specific protocols for communication

purpose are known as reseved sockets

TCPIP uses or reserves the lower 1024 ports for specific protocols

Example port number 23 is for Telnet 25 is for smtp 21 is for ftp 13 for daytime 110 for pop3

and so on Protocol decides how a client should interact with the port

ii) Proxy server

A proxy server is a computer that offers a computer network service to allow clients to make

indirect network connections to other network services A client connects to the proxy server

then requests a connection file or other resource available on a different server The proxy

provides the resource either by connecting to the specified server or by serving it from a cache In

some cases the proxy may alter the clients request or the servers response for various purposes

Purposes of the proxy servers

To keep machines behind it anonymous mainly for security

To speed up access to resources (using caching) Web proxies are commonly used to

cache web pages from a web server

To prevent downloading the same content multiple times (and save bandwidth)

To log audit usage eg to provide company employee Internet usage reporting

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 27 of 38

To scan transmitted content for malware before delivery

To scan outbound content eg for data loss prevention

iii) Datagram

Datagrams are bundles of information passed between machines They are somewhat like a hard

throw from a well-trained but blindfolded catcher to the third baseman Once the datagram has

been released to its intended target there is no assurance that it will arrive or even that

someone will be there to catch it Likewise when the datagram is received there is no

assurance that it hasnrsquot been damaged in transit or that whoever sent it is still there to receive a

response

Java implements datagrams on top of the UDP protocol by using two classes

The DatagramPacket object is the data container while the DatagramSocket is the mechanism

used to send or receive the DatagramPackets

iv) URL connection

URLConnection is a general-purpose class for accessing the attributes of a remote resource

Once you make a connection to a remote server you can use URLConnection to inspect the

Properties of the remote object before actually transporting it locally These attributes are

exposed by the HTTP protocol specification and as such only make sense for URL objects

that are using the HTTP protocol

URLConnection defines several methods

int getContentLength( )

String getContentType( )

long getDate( )

long getExpiration( )

String getHeaderField(int idx)

long getLastModified( )

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 28 of 38

c) Write a program to display three text fields and a button below to all an Applet Insert

the integer valuer from three text fields After pressing the button the background colour

of applet will be changed as per the RGB combination of the values given in the text field

(Correct logic - 6 Marks Syntax - 2 Marks)

4

Ans import javaawt

import javaawtevent

import javaapplet

ltapplet code=rdquoClrclassrdquo width=250 heigth=250gtltappletgt

public class Clrextends Applet implements ActionListener

int r g b

TextField t1t2t3

Button b1

Color c1

public void init()

t1= new TextField(5)

t2= new TextField(8)

t3= new TextField(11)

b1 = new Button(ldquo Set Colorrdquo)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 29 of 38

add(t1)

add(t2)

add(t3)

add(b1)

b1addActionListener(this)

public void void paint( )

setBackground(c1)

public void actionPerformed(ActionEvent ae)

r=IntegerparseInt(t1getText())

g=IntegerparseInt(t2getText())

b=IntegerparseInt(t3getText())

c1= new Color(rgb)

repaint()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 30 of 38

6) Attempt any four of the following Marks 16

a) How to check how many fonts are available in the computer system 4

Explain with example

(Explanation -2 Marks Example-2 Marks)

Ans When working with fonts often you need to know which fonts are available on your machine To

ontain this information you can use the getAvailableFontFamilyNames() method defined by the

GraphicsEnvironment classIt is shown here

String[ ] getAvailableFontFamilyNames( )

This method returns an array of string that contains the names of the available font families

Since this methods is members of GraphicsEnvironment you need a GraphicsEnvironment

reference to call itYou can obtain this reference by using the getlocalGrahicsEnvironmet() static

method which is derfined by GraphicsEnvironmentIt is shown here

static GraphicsEnvironment getLocalGraphicsEnvironment( )

Here is an applet that shown how to obtain the names of the available font families

ltapplet code=rdquoAllFontsrdquo width=500 height=100gt

ltappletgt

import javaapplet

import javaawt

public class AllFonts extends Applet

public void paint(Graphics g)

string fonts= ldquo rdquo

stirng allFontsList[]

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 31 of 38

GraphicsEnvironment t = GraphicsEnvironmentgetLocalGraphicsEnvironment()

allFontList = tgetAvailableFontFamilyNames()

for(int i= 0 ilt allFontsListlength i++)

fonts= fonts + allFontList[i] + ldquo rdquo

gdrawString(msg416)

b) Explain following check box class methods with appropriate example 4

i) Void setLable (String str) ii) Boolean getState ( )

(Explanation of each method-1 Marks Example-2 Marks)

Ans

i) void setLable(String str)

This method is used to set the label of check box

ii) Boolean getState()

This method is used to retrieve the current state of a check box It returns the value either true or

false depends on check box is selected or not

Example

Demonstrate check boxes

import javaawt

import javaawtevent

import javaapplet

ltapplet code=CheckboxDemo width=250 height=200gt

ltappletgt

public class CheckboxDemo extends Applet implements ItemListener

String msg =

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 32 of 38

Checkbox winXP winVista solaris mac

public void init()

winXP = new Checkbox(Windows XP null true)

mac = new Checkbox()

macsetLable(ldquoMac OSrdquo)

add(winXP)

add(mac)

winXPaddItemListener(this)

macaddItemListener(this)

public void itemStateChanged(ItemEvent ie)

repaint()

Display current state of the check boxes

public void paint(Graphics g)

msg = Current state

gdrawString(msg 6 80)

msg = Windows XP + winXPgetState()

gdrawString(msg 6 100)

msg = Mac OS + macgetState()

gdrawString(msg 6 120)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 33 of 38

c) Explain the techniques of session tracking management

(Any four techniques with explanation- 1 Mark each)

Ans Session tracking Techniques

1 User Authorization

Users can be authorized to use the web application in different ways Basic concept is that the

user will provide username and password to login to the application Based on that the user can

be identified and the session can be maintained

2 Hidden Fields

ltINPUT TYPE=rdquohiddenrdquo NAME=rdquotechnologyrdquo VALUE=rdquoservletrdquogt

Hidden fields like the above can be inserted in the webpages and information can be sent to the

server for session tracking These fields are not visible directly to the user but can be viewed

using view source option from the browsers This type doesnrsquot need any special configuration

from the browser of server and by default available to use for session tracking This cannot be

used for session tracking when the conversation included static resources lik html pages

3 URL Rewriting

Original URL httpserverportservletServletName

ewritten URL httpserverportservletServletNamesessionid=7456

When a request is made additional parameter is appended with the url In general added

additional parameter will be sessionid or sometimes the userid It will suffice to track the

session This type of session tracking doesnrsquot need any special support from the browser

Disadvantage is implementing this type of session tracking is tedious We need to keep track of

the parameter as a chain link until the conversation completes and also should make sure that

the parameter doesnrsquot clash with other application parameters

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 34 of 38

4 Cookies

Cookies are the mostly used technology for session tracking Cookie is a key value pair of

information sent by the server to the browser This should be saved by the browser in its space

in the client computer Whenever the browser sends a request to that server it sends the cookie

along with it Then the server can identify the client using the cookie

In java following is the source code snippet to create a cookie

Cookie cookie = new Cookie (ldquouserIDrdquo ldquo7456Prime)

resaddCookie(cookie)

5 Session tracking API

Session tracking API is built on top of the first four methods This is inorder to help the

developer to minimize the overhead of session tracking This type of session tracking is

provided by the underlying technology Lets take the java servlet example Then the servlet

container manages the session tracking task and the user need not do it explicitly using the java

servlets This is the best of all methods because all the management and errors related to

session tracking will be taken care of by the container itself

d) Give sequential steps for JTree in swing with example

(Steps- 2 Marks any small Example- 2 Marks)

Ans Steps for JTree

Atree is a component that presents a hierarchical view of data The user has the ability to

expand or collapse individual subtrees in this display Trees are implemented in Swing by

the JTree class

Here are the steps to follow to use a tree

1 Create an instance of JTree

2 Create a JScrollPane and specify the tree as the object to be scrolled

3 Add the tree to the scroll pane

4 Add the scroll pane to the content pane

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 35 of 38

Example

Demonstrate JTree

import javaawt

import javaxswingevent

import javaxswing

import javaxswingtree

ltapplet code=JTreeDemo width=400 height=200gt

ltappletgt

public class JTreeDemo extends JApplet

JTree tree

JLabel jlab

public void init()

try

SwingUtilitiesinvokeAndWait(

new Runnable()

public void run()

makeGUI()

)

catch (Exception exc)

Systemoutprintln(Cant create because of + exc)

private void makeGUI()

Create top node of tree

DefaultMutableTreeNode top = new DefaultMutableTreeNode(Options)

Create subtree of A

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 36 of 38

DefaultMutableTreeNode a = new DefaultMutableTreeNode(A)

topadd(a)

DefaultMutableTreeNode a1 = new DefaultMutableTreeNode(A1)

aadd(a1)

DefaultMutableTreeNode a2 = new DefaultMutableTreeNode(A2)

aadd(a2)

Create subtree of B

DefaultMutableTreeNode b = new DefaultMutableTreeNode(B)

topadd(b)

DefaultMutableTreeNode b1 = new DefaultMutableTreeNode(B1)

badd(b1)

DefaultMutableTreeNode b2 = new DefaultMutableTreeNode(B2)

badd(b2)

DefaultMutableTreeNode b3 = new DefaultMutableTreeNode(B3)

badd(b3)

Create the tree

tree = new JTree(top)

Add the tree to a scroll pane

JScrollPane jsp = new JScrollPane(tree)

Add the scroll pane to the content pane

add(jsp)

Add the label to the content pane

jlab = new JLabel()

add(jlab BorderLayoutSOUTH)

Handle tree selection events

treeaddTreeSelectionListener(new TreeSelectionListener()

public void valueChanged(TreeSelectionEvent tse)

jlabsetText(Selection is + tsegetPath())

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 37 of 38

e) Draw and explain the life cycle of servlet

(Explanation ndash 3 Marks Diagram -1 Marks)

Ans Three methods are central to the life cycle of a servlet

These are init( ) service( ) and destroy( )

They are implemented by every servlet and are invoked at specific times by the server Let

us consider a typical user scenario to understand when these methods are called

First assume that a user enters a Uniform Resource Locator (URL) to a web browser

The browser then generates an HTTP request for this URL This request is then sent to the

appropriate server

Second this HTTP request is received by the web server The server maps this request to

a particular servlet The servlet is dynamically retrieved and loaded into the address space

of the server

Third the server invokes the init( ) method of the servlet This method is invoked only

when the servlet is first loaded into memory It is possible to pass initialization parameters

to the servlet so it may configure itself

Fourth the server invokes the service( ) method of the servlet This method is called to

process the HTTP request You will see that it is possible for the servlet to read data that has

been provided in the HTTP request It may also formulate an HTTP response for the client

The servlet remains in the serverrsquos address space and is available to process any other

HTTP requests received from clients The service( ) method is called for each HTTP request

Finally the server may decide to unload the servlet from its memory The algorithms by

which this determination is made are specific to each server The server calls the destroy( )

method to relinquish any resources such as file handles that are allocated for the servlet

Important data may be saved to a persistent store The memory allocated for the servlet and

its objects can then be garbage collected

A servlet life cycle can be defined as the entire process from its creation till the destruction The

following are the paths followed by a servlet

The servlet is initialized by calling the init () method

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 38 of 38

The servlet calls service() method to process a clients request

The servlet is terminated by calling the destroy() method

Finally servlet is garbage collected by the garbage collector of the JVM

Initialization

(Load Resources)

Services

(Accept Requests)

Destruction

(Unload Resources)

Servlet

Request

Response

Page 2: AJP

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 2 of 38

b) Explain use of button control in AWT with example 4

(Defination-1 Mark Methods-1 Mark Example-2 Marks)

Ans A button is a component that contains a label and that generates an event when it is pressed

buttons are object of type Button Button defines

Button()

Button(String str)

After a button has been createdyou can set its label by calling setLabel()

You can retrieve its label by calling getLabel()

Void setLabel(String str)

String getLabel()

Example

import javaawt

import javaapplet

ltapplet code=rdquoMyButtonDemordquo width=250

Height=150gt

ltappletgt

public class mybuttondemo extends Applet

Button okcancelapply

public void init()

ok= new Button(ldquookrdquo)

cancel= new Button(ldquocancelrdquo)

apply= new Button(ldquoapplyrdquo)

add(ok)

add(cancel)

add(apply)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 3 of 38

c) List four differences between TCP and UDP 4

(Any four Points -1 Mark each)

Ans

TCP UDP

It is connection Oriented It is connectionless

It gives acknowledgement It does not give acknowledgement

It is reliable It is unreliable

It is use to transfer for large amount of

data It is use to transfer for small amont of data

Transmission seed is low Transmission seed is High

TCP header size is 20 bytes UDP Header size is 8 bytes

TCP does error checking UDP does error checking but no recovery

options

d) Write three factory method of InetAddress class 4

(Three method- 4 Marks)

Ans The Inet class has no invisible constructor

To create an Inet address objectyou have to use one of the available factory methods

Factory methods are merely aconvention whereby static methods in a class returns an instance of

that class

Three commonly used InetAddress factory methods are

1) static InetAddress getLocalHost()

throws unKnownHostException

This method simply returns the InetAddress object that represents the local host

2) static InetAddress getByName(String hostname)

throws unKnownHostException

This method simply returns the InetAddress for a host name passed to it

3) static InetAddress[] getAllByName(String hostname)

throws unKnownHostException

which takes an IPaddress and returns an InetAddress object

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 4 of 38

B) Attempt any one of the following Marks 6

a) List various types of JDBC drives Explain JDBC-ODBC bridge driver

(Types-2 Marks Bridge driver diagram - 1 Marks Discription-3 Marks)

Ans Type 1 JDBC-ODBC bridge

Type 2 JDBC-native API

Type 3100 pure java JDBC network

Type 4100 java

JDBC-ODBC bridge

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 5 of 38

This category works with ODBC drivers supplied by your database vendor or a third party

To use the bridge you must first have an ODBC driver specifically for you database and

additional software that you need for connectivity

Using ODBC also requires configuring on your system a DNS that represents the target database

Advantages

1) It offers the ability to connect to almost all databases on almost all platforms

2) It may be the only way to gain access to some low and desktop database and application

Disadvantages

1) ODBC driver must also be loaded on the target machine

2) Translation between JDBC and ODBC affects performance

b) Write a program to demonstrate the use of JScrollpane in swing

(Any 1 program- Applet tag-2mark correct logic-4 Marks Synatax-2 Marks)

Ans import javaawt

import javaxswing

ltapplet code=rdquoJScrollPaneDemordquo width=350

Height=250gt

ltappletgt

Public class JscrollPaneDemo extends JApplet

Public void init()

Container contentPane= get ContentPane()

contentPanesetLayout(new BorderLayout())

JPanel jp = new JPanel()

jpsetLayout(new GridLayout(2020))

int b=0

for(int i=0ilt20i++)

jpadd(new JButton(ldquoButtonrdquo+b)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 6 of 38

++b

int v=ScrollPaneConstantsVERTICAL_SCROLLBAR_AS_NEEDED

int h= ScrollPaneConstantsHORIZONTAL_SCROLLBAR_AS_NEEDED

JScrollPane jsp= new JScrollPane(jpvh)

contentPaneadd(jspBorderLayoutCENTER)

2 Attempt any two of the following Marks 16

a) Write an application program making use of menu and menu bar class 8

(Applet tag ndash 1Mark correct logic to add menu and menubar - 5 Marks Synatax-2 Marks)

Ans import javaawt

import javaawtevent

import javaapplet

ltapplet code=rdquo MenuFramerdquo width=350

Height=250gt

ltappletgt

class MenuFrame extends Frame implements ActionListener

String msg=rdquordquo

MenuFrame(String title)

super(title)

MenuBar mbar= new menuBar()

setMentBar(mbar)

Menu file=new Menu(ldquoFilerdquo)

MenuItem item1item2item3item4item5

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 7 of 38

item1= new MenuItem (ldquoNewrdquo)

item2= new MenuItem (ldquoopenrdquo)

item3= new MenuItem (ldquocloserdquo)

item4= new MenuItem (ldquo-rdquo)

item5= new MenuItem (ldquoQuitrdquo)

fileadd(item1)

fileadd(item2)

fileadd(item3)

fileadd(item4)

fileadd(item5)

mbaradd(file)

MenuItem item6item7item8item9

item6= new MenuItem (ldquocutrdquo)

item7= new MenuItem (ldquocopyrdquo)

item8= new MenuItem (ldquopasterdquo)

item9= new MenuItem (ldquo-rdquo)

editadd(item6)

editadd(item7)

editadd(item8)

editadd(item9)

mbaradd(edit)

item1addActionListener(this)

item2addActionListener(this)

item3addActionListener(this)

item4addActionListener(this)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 8 of 38

item5addActionListener(this)

item6addActionListener(this)

item7addActionListener(this)

item8addActionListener(this)

item9addActionListener(this)

Public void paint(Graphics g)

gdrawString(msg10200)

public void actionPerformed(ActionEvent e)

msg= ldquoYou have selected rdquo+ egetActionCommand()

repaint()

public static void main(String args[])

MenuFrame m=new MenuFrame(ldquoMyMenurdquo)

msetVisible(true)

msetSize(100200)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 9 of 38

b) Give the use of Server Socket and Socket class Describe the steps that are 8

required to establish communication between client and server sockets

(Use-2 Marks each class Steps-4 Marks)

Ans Server socket

A Server Socket handles the requests and sends back an appropriate reply The actual tasks that a

server socket must accomplish are implemented by an internal SocketImpl instance A server

socket waits for requests to come in over the network It performs some operation based on that

request and then possibly returns a result to the requester The actual work of the server socket is

performed by an instance of the SocketImpl class An application can change the socket factory

that creates the socket implementation to configure itself to create sockets appropriate to the local

firewall

Client socket

we have used the class named ClientSocketInformationjava that implement the constructor of

the Socket class passing two arguments as hostName and TIME_PORT This program throws an

IOException for the exception handling This exception is thrown to indicate an IO problem of

some sort occurred Here we are going to explore a method to retrieve the host name of the local

system in a very simple way In this way we find out the Local address Local host information

reuseAddress and address of the local system in a very simple manner

Steps to connect

Using TCP socket provides the communication mechanism between two computers A client

program creates a socket at its end of the communication and attempts to connect that socket to a

server

The following is the lists of sequential steps which occur when establishing a TCP connection

between client socket and server socket

1 The server initiates a Server Socket object and mentions which port number communication is

to occur on

2 The server invokes the accept () method of the ServerSocket class This method does the wait

till a client gets connected to the server on the given port

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 10 of 38

After the waiting stages of server a client instantiates a Socket object It also specifies the

server name and port number to which it gets connected

3 The constructor of the Socket class tries to connect the client to the specified server and port

number If the communication is established the client has a Socket object which is capable

of communicating with the server

4 On server side the accept () method returns a reference to a new socket on the server that is

connected to the clientrsquos socket

Once the connection are established communication occur using IO streams Each socket has

both an Outputstream and InputStreams

As we know that the TCP is a two way communication protocol So data can be sent across

both streams at the same time

Two constructors used to create client socket

Socket (String hostnameint port)

Creates a socket connection the localhost to name host and port

Socket(InetAddress ipAddressint port)

Creates a socket using pre existing InetAddress object and a port

A socket can be examined at any time for the address and port information associated with it

InetAddress getInetAddress()

Int getPort()

Int getLocalPort()

Once the socket object has been created it can be examined to gain access to ip and op streams

associated with it

Example (optional)

import javanet

import javaio

class abc

public static void main(String args[])throws Exception

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 11 of 38

int c

Socket s=new socket(ldquointericnetrdquo43)

InputStream in=sgetInputStream()

OutputStream out=sgetOutputStream()

String str=(argslength==0rdquoOsbornecomrdquo)

byte buf[]=strgetBytes()outwrite(buf)

while((c=inread())=-1)

Systemoutprintln(char)c)

sclose()

c) Give sequential steps to use JTabbedPane in an Applet with example

(Steps- 4Marks any one Example- 4Marks)

Ans The general procedure to use a tabbed pane in an applet is

1) Create a JtabbedPane object

2) Call addTab() to add to the pane

3) Repeat step 2 for each tab

4) Add the tabbed pane to the content pane of the applet

Example

import javaxswing

ltapplet code=rdquoJTabbedPaneDemordquo width=350

Height=250gt

ltappletgt

public class JTabbedPaneDemo extends JApplet

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 12 of 38

public void init()

JTabbedPane jtp= new JTabbedPane()

jtpaddTab(ldquocitiesrdquonew citiesPanel())

jtpaddTab(ldquocolorsrdquonew colorsPanel())

jtpaddTab(ldquoFlavourrdquonew flavourPanel())

getContentPane()add(jtp)

class citiespanel extends JPanel

Public citiesPanel()

JButton b1=new Button(ldquoNew Yorkrdquo)

add(b1)

JButton b2=new Button(ldquolondonrdquo)

add(b2)

class colorpanel extends JPanel

Public colorPanel()

JCheckBox cb1=new JCheckBox(ldquoredrdquo)

add(cb1)

JCheckBox cb2=new JCheckBox (ldquogreenrdquo)

add(cb2)

class flavourpanel extends JPanel

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 13 of 38

public flavourPanel()

JComboBox b=new JComboBox()

jcbaddItem(ldquovanillardquo)

jcbaddItem(ldquochocolaterdquo)

add(jcb)

3 Attempt any four of the following Marks 16

a) Example the use of prepared statement with example 4

(Explanation-2 Marks Example-2 Marks)

Ans PrepareStatement ()

The preparedStatement() method creates a PreparedStatement object and returns it as a return

value The Prepared statement object is used to execute dynamic SQL statement against the

databaseA dynamic SQL statement is a statement in which some of the parameters in the

statement are unknown when the statement is created The parameter is placed into the SQL

statement as they are determined by the application When all the parameters are specified for the

SQL statement the dynamic SQL statement will be executed just as a static statement is executed

To create a dynamic SQL statement that takes a first name and last name as parameters use the

following code

try

String sql=rdquoSelect from temployeerdquo + ldquowhere Firstname=rdquo + ldquoand Lastname=rdquo

PreparedStatement p=connectionpreparedStatement(sql)

Catch(SQLException e)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 14 of 38

b) List any four differences between AWT and swing 4

(Any four points ndash 1 Mark each)

Ans

Swing AWT

It uses javaxswing package It uses javaapplet package

It uses JApplet class It uses Applet class

Swing is light weight component AWT is heavy weight component

It does not have add() method to add

control

It has add() method to add control

AWT provides less features than

swing

Swing has variety of component amp

features which is not in AWT

Awt has huge collection of classes amp

interfaces

Swing has bigger collection of classes

amp interfaces than AWT

AWT has predefined formats of

appearance amp behavior of component

Swing provides a facility of different

appearance amp behavior of the same

component

c) List four interfaces in javaxservlet package 4

(Any four points ndash 1 Mark each)

Ans Following are the interfaces in javaxservlet package

1 Servlet All servlets must implement the Servlet interface It declares the init( ) service( )

and destroy( ) methods that are called by the server during the life cycle of a servlet

2 ServletConfig The ServletContextinterface is implemented by the server It enables servlets

to obtain information about their environment

3 ServletContext The ServletContextinterface is implemented by the server It enables

servlets to obtain information about their environment

4 ServletRequest The ServletRequestinterface is implemented by the server It enables a

servlet to obtain information about a client request

5 ServletResponse The ServletResponseinterface is implemented by the server It enables a

servlet to formulate a response for a client

6 SingleThreadModel This interface is used to indicate that only a single thread will execute

the service( ) method of a servlet at a given time It defines no constants and declares no

methods

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 15 of 38

d) Give the use of ImageIcon class with example 4

(Explanation ndash 2 Marks Example- 2 Marks)

Ans In Swing icons are encapsulated by the ImageIconclass which paints an icon from an

image Two of its constructors are shown here

ImageIcon(String filename)

ImageIcon(URL url)

The first form uses the image in the file named filename The second form uses the

image in the resource identified by url

The ImageIconclass implements the Icon interface that declares the methods

As follows

Method Description

intgetIconHeight( ) Returns the height of the iconin pixels

intgetIconWidth( ) Returns the width of the iconin pixels

voidpaintIcon(Component comp Graphics gintx inty)Paints the icon at position x y onthe

graphics context g Additionalinformation about the paintoperation can be provided in comp

Example

import javaawt

import javaxswing

ltapplet code=JLabelDemo width=250 height=150gt

ltappletgt

public class JLabelDemo extends JApplet

public void init()

Get content pane

Container contentPane = getContentPane()

Create an icon

ImageIcon ii = new ImageIcon(francegif)

Create a label

JLabeljl = new JLabel(France ii JLabelCENTER)

Add label to the content pane

contentPaneadd(jl)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 16 of 38

e) Give the use of URL class along with syntax of constructors of URL class 4

(Use - 2 Marks Any two Constructor - 1 Mark each)

Ans The URL provides a reasonably intelligible form to uniquely identify or address information on the

Internet URLs are ubiquitous every browser uses them to identify information on the Web In

fact the Web is really just that same old Internet with all of its resources addressed as URLs plus

HTML

Javas URL class has several constructors One commonly used form specifies the URL with a

string that is identical to what you see displayed in a browser

1 URL(String urlSpecifier)

The next two forms of the constructor allow you to break up the URL into its componentparts

2 URL(String protocolName String hostName intport String path)

3 URL(String protocolName String hostName String path)

Another frequently used constructor allows you to use an existing URL as a referencecontext and

then create a new URL from that context Although this sounds a littlecontorted its really quite

easy and useful

4 URL(URL urlObj String urlSpecifier)

4 A) Attempt any three of the following Marks 12

a) Give the use of following methods of statement interface 4

i) executeQuery( ) ii) execute Update ( )

(Each method ndash 2 Marks)

Ans i) executeQuery()

The executeQuery() method of the statement object enables you to send SQL select statement to

the database and to receive result from the database Executing a query in effect sends a SQL

select statement to the database and returns the appropriate results back in the Resultset object

The executeQuery() method takes a SQL select statement as a parameter and returns a ResultSet

object that contains all the records that match the select statements criteria

ii) executeUpdate()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 17 of 38

The executeUpdate() method of the Statement object enables you to execute SQL update

statements such as delete insert and update The method takes a String containing the SQL update

statement and returns an integers that determines how many records were affected by the SQL

statement

b) Define Layout Manager Describe the use of GridLayout Manager 4

(Layout manager- 2 Marks Use-2 Marks)

Ans Each Container object has a layout manager associated with it A layout manager

is an instance of any class that implements the LayoutManagerinterface The layout

manager is set by the setLayout( ) method If no call to setLayout( ) is made then the

default layout manager is used Whenever a container is resized (or sized for the first

time) the layout manager is used to position each of the components within it

The setLayout( ) method has the following general form

voidsetLayout(LayoutManagerlayoutObj)

GridLayoutManager

GridLayout lays out components in a two-dimensional grid When you instantiate

a GridLayout you define the number of rows and columns The constructors

supported by GridLayoutare shown here

GridLayout( )

GridLayout(intnumRows intnumColumns)

GridLayout(intnumRows intnumColumns inthorz intvert)

c) Explain the use of cookies with example 4

(Explanation - 2 Marks Example - 2 Marks any one)

Ans Cookie is a small piece of information that is passed back and forth in the HTTP request and

response Even though a cookie can be created on the client side using some scripting language

such as JavaScript it is usually created by the server resource such as a Servlet The Cookies sent

by the server when the client requests another page from the same application In Servlet

programming a cookie is represented by a Cookie class in the javaxservlethttp package You can

create a cookie by calling the Cookie class constructor and passing two string objects the name

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 18 of 38

and value of the cookie For instance the following code creates a cookie object called c1The

cookie has the name ldquomyCookierdquo and value of rdquosecretrdquo

Cookie c1=new Cookie(ldquomyCookierdquordquosecretrdquo)

You then can add the cookie to the http response using addCookie method of the

HTTPServletResponse interfaceResponseaddCookie(c1)

Program for Add cookies

import javaio

importjavaxservlet

importjavaxservlethttp

public class AddCookieServlet extends HttpServlet

public void doPost(HttpServletRequest requestHttpServletResponse response)

throwsServletException IOException

Get parameter from HTTP request

String data = requestgetParameter(data)

Create cookie

Cookie cookie = new Cookie(MyCookie data)

Add cookie to HTTP response

responseaddCookie(cookie)

Write output to browser

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgtMyCookie has been set to)

pwprintln(data)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 19 of 38

pwclose()

OR

Program for Get Cookies

import javaio

importjavaxservlet

importjavaxservlethttp

public class GetCookiesServlet extends HttpServlet

public void doGet(HttpServletRequest requestHttpServletResponse response)

throwsServletException IOException

Get cookies from header of HTTP request

Cookie[] cookies = requestgetCookies()

Display these cookies

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgt)

for(inti = 0 iltcookieslength i++)

String name = cookies[i]getName()

String value = cookies[i]getValue()

pwprintln(name = + name +

value = + value)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 20 of 38

pwclose()

d) Give steps to create simple servlet with example 4

(Steps- 2 Marks Any one Example ndash 2 Marks)

Ans Steps 1) Write a java servet code

Steps 2) Compile Servet by setting classpath with servlet-api library

Step 3) Copy the class servlet file in web apps classpath directory

Steps 4) Open the webxml open it and add servlet tag and sevlet mapping tag

Steps 5) Start web server(apche tomcat)

Steps 6) Browse servlet using java compatible browser like IE

Example shows to start create a file named WelcomeServletjava that contains the following

program

import javaio

importjavaxservlet

public class WelcomeServletDemo extends GenericServlet

public void service(ServletRequestrequestServletResponse response) throws

ServletExceptionIOException

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgtWelcome to Servlet)

pwclose()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 21 of 38

B) Attempt any one of the following Marks 6

a) Describe the two ndashtier and three ndashtier database design of JDBC API with neat diagram

(Explanation of Two-tier-2 Marks and Three-tier-2 Marks Diagram ndash 1 Mark each)

Ans Two Tier Architecture

In a two tier model a java application is designed to interact directly with the database

Application functionality is divided into these two layers

1) Application Layer Including the JDBC driver business logic and user interface

2) Database Layer including RDBMS

The interface to the database is handled by the Java Database Connectivity(JDBC) Driver

appropriate to the particularly database management system being accessed The JDBC Driver

passes SQL statements to the database and returns the results of those statements to the

application

A clientserver configuration is the special case of the two tier model where the database is

located on another machine referred to as the server The application runs on the client machine

which is connected to the server over a network Commonly the network is an Intranet using

dedicated database servers to support multiple clients but it can just as easily be the internet

Three Tier Architecture-

In the three tier model the client typically sends requests to an application server forming the

middle tier The application server interprets these requests and formats the necessary SQL

statement to fulfill

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 22 of 38

These requests and sends them to the database The database process the SQL statements and

sends result back to the application server which then sends them to the client

Following are some advantages of Three-tier architecture

1 Performance can be improved by separating the application server and database server

2 Business logic is clearly separated from the database

3 Client application can use a simple protocol such as CGI to access services

The three-tier model show in following fig is a common in web application In this scenario the

client tier is frequently implemented in a browse on a client machine the middle tier is

implemented in a web server with a Servlet engine and the database management system runs on

a dedicated database server

Following are the main components of three tier architecture

1 Client Tier - Typically this is thin presentation layer that may be implemented using a web

browser

2 Middle Tier - This tier handles the business or application logic This may be implemented

using a Servlet engine such as Tomcat or an application server such as JBOSS The JDBC

driver also resides in this layer

3 Data source layer This component includes the RDBMS

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 23 of 38

b) Write servlet which shows how many times user has visited the page in session

(Any Correct Logic ndash4 Marks Syntax ndash 2 Marks)

Ans import javaio

import javaxservlet

import javaxservlethttp

public class Session Travker extends HttpServlet

public void doGet(HttpServletRequest req HttpServletResponse res) throws ServletException

IOException

ressetContentType(ldquotexthtmlrdquo)

PrintWriter out = resgetWriter()

HttpSession session = reqgetSession(true)

Integer count= (Integer)sessiongetValue(ldquotrackercountrdquo)

if(count== null) count=new Interger(1)

else count = new Interger(count intValue() +1)

sessionputValue(ldquotrackercountrdquocount)

outprintln(ldquoltHTMLgtltHEADgtltTITLEgtSession TrackerltTITLEgtltHEADgtrdquo)

outprintln(ldquoltBODYgtltH1gtSession Tracking DemoltH1gtrdquo)

outprintln(ldquoYou have visited this pagerdquo +count +((countintValue() == 1)rdquotimerdquo

ldquotimesrdquo))outprinln(ltPgtrdquo)

outprintln(ldquoltH2gtSesssion dataltH2gtrdquo)

String[] names = sessiongetValueNames()

for(int i=0 ilt nameslength i++)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 24 of 38

outprintln(names[i] + ldquo rdquo + sessiongetvalue(names[i])+ ldquoltBRgtrdquo)

outprintln(ldquoltBODYgtltHTMLgtrdquo)

5 Attempt any two of the following Marks 16

a) Write a program to display all records from Employee table from database using

JDBC

(Assume suitable data for table- Load driver create connection execute Query - 1 Mark

each Display data- 3 Marks Syntax ndash 2 Marks)

Ans import javasql

import javasqlStatement

import javaapplet

import javaawt

public class DisplayTable

public static void main( String args[])

RsultSet rs

Connection conn

try

String s1

ClassforName(sun jdbcodbcJdbcOdbcDriver)

Systemoutprintln(Connecting to a selected database)

String url=rdquojdbcodbcabcrdquo

conn = DriverManagergetConnection(DB_URL USER PASS)

Systemoutprintln(Connected database successfully)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 25 of 38

Systemoutprintln(Creating statement)

stmt = conncreateStatement()

sql = SELECT FROM Employee

ResultSet rs = stmtexecuteQuery(sql)

Tables fields assumed are id first last age

while(rsnext())

int id = rsgetInt(id)

int age = rsgetInt(age)

String first = rsgetString(first)

String last = rsgetString(last)

Systemoutprint(ID + id)

Systemoutprint( Age + age)

Systemoutprint( First + first)

Systemoutprintln( Last + last)

rsclose()

catch(SQLException se)

Handle errors for JDBC

seprintStackTrace()

catch(Exception e)

Handle errors for ClassforName

eprintStackTrace()

finally

finally block used to close resources

try

if(stmt=null)

connclose()

catch(SQLException se)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 26 of 38

b) Define the term

i) Reserved socket ii) proxy server

iii) Datagram iv) URL connection 4

(Each term- 2 Marks)

Ans i) Reserved socket

A socket is one end-point of a two-way communication link between two programs running on

the network Socket classes are used to represent the connection between a client program and a

server program

Reserved socket The socket which are reserved for specific protocols for communication

purpose are known as reseved sockets

TCPIP uses or reserves the lower 1024 ports for specific protocols

Example port number 23 is for Telnet 25 is for smtp 21 is for ftp 13 for daytime 110 for pop3

and so on Protocol decides how a client should interact with the port

ii) Proxy server

A proxy server is a computer that offers a computer network service to allow clients to make

indirect network connections to other network services A client connects to the proxy server

then requests a connection file or other resource available on a different server The proxy

provides the resource either by connecting to the specified server or by serving it from a cache In

some cases the proxy may alter the clients request or the servers response for various purposes

Purposes of the proxy servers

To keep machines behind it anonymous mainly for security

To speed up access to resources (using caching) Web proxies are commonly used to

cache web pages from a web server

To prevent downloading the same content multiple times (and save bandwidth)

To log audit usage eg to provide company employee Internet usage reporting

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 27 of 38

To scan transmitted content for malware before delivery

To scan outbound content eg for data loss prevention

iii) Datagram

Datagrams are bundles of information passed between machines They are somewhat like a hard

throw from a well-trained but blindfolded catcher to the third baseman Once the datagram has

been released to its intended target there is no assurance that it will arrive or even that

someone will be there to catch it Likewise when the datagram is received there is no

assurance that it hasnrsquot been damaged in transit or that whoever sent it is still there to receive a

response

Java implements datagrams on top of the UDP protocol by using two classes

The DatagramPacket object is the data container while the DatagramSocket is the mechanism

used to send or receive the DatagramPackets

iv) URL connection

URLConnection is a general-purpose class for accessing the attributes of a remote resource

Once you make a connection to a remote server you can use URLConnection to inspect the

Properties of the remote object before actually transporting it locally These attributes are

exposed by the HTTP protocol specification and as such only make sense for URL objects

that are using the HTTP protocol

URLConnection defines several methods

int getContentLength( )

String getContentType( )

long getDate( )

long getExpiration( )

String getHeaderField(int idx)

long getLastModified( )

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 28 of 38

c) Write a program to display three text fields and a button below to all an Applet Insert

the integer valuer from three text fields After pressing the button the background colour

of applet will be changed as per the RGB combination of the values given in the text field

(Correct logic - 6 Marks Syntax - 2 Marks)

4

Ans import javaawt

import javaawtevent

import javaapplet

ltapplet code=rdquoClrclassrdquo width=250 heigth=250gtltappletgt

public class Clrextends Applet implements ActionListener

int r g b

TextField t1t2t3

Button b1

Color c1

public void init()

t1= new TextField(5)

t2= new TextField(8)

t3= new TextField(11)

b1 = new Button(ldquo Set Colorrdquo)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 29 of 38

add(t1)

add(t2)

add(t3)

add(b1)

b1addActionListener(this)

public void void paint( )

setBackground(c1)

public void actionPerformed(ActionEvent ae)

r=IntegerparseInt(t1getText())

g=IntegerparseInt(t2getText())

b=IntegerparseInt(t3getText())

c1= new Color(rgb)

repaint()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 30 of 38

6) Attempt any four of the following Marks 16

a) How to check how many fonts are available in the computer system 4

Explain with example

(Explanation -2 Marks Example-2 Marks)

Ans When working with fonts often you need to know which fonts are available on your machine To

ontain this information you can use the getAvailableFontFamilyNames() method defined by the

GraphicsEnvironment classIt is shown here

String[ ] getAvailableFontFamilyNames( )

This method returns an array of string that contains the names of the available font families

Since this methods is members of GraphicsEnvironment you need a GraphicsEnvironment

reference to call itYou can obtain this reference by using the getlocalGrahicsEnvironmet() static

method which is derfined by GraphicsEnvironmentIt is shown here

static GraphicsEnvironment getLocalGraphicsEnvironment( )

Here is an applet that shown how to obtain the names of the available font families

ltapplet code=rdquoAllFontsrdquo width=500 height=100gt

ltappletgt

import javaapplet

import javaawt

public class AllFonts extends Applet

public void paint(Graphics g)

string fonts= ldquo rdquo

stirng allFontsList[]

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 31 of 38

GraphicsEnvironment t = GraphicsEnvironmentgetLocalGraphicsEnvironment()

allFontList = tgetAvailableFontFamilyNames()

for(int i= 0 ilt allFontsListlength i++)

fonts= fonts + allFontList[i] + ldquo rdquo

gdrawString(msg416)

b) Explain following check box class methods with appropriate example 4

i) Void setLable (String str) ii) Boolean getState ( )

(Explanation of each method-1 Marks Example-2 Marks)

Ans

i) void setLable(String str)

This method is used to set the label of check box

ii) Boolean getState()

This method is used to retrieve the current state of a check box It returns the value either true or

false depends on check box is selected or not

Example

Demonstrate check boxes

import javaawt

import javaawtevent

import javaapplet

ltapplet code=CheckboxDemo width=250 height=200gt

ltappletgt

public class CheckboxDemo extends Applet implements ItemListener

String msg =

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 32 of 38

Checkbox winXP winVista solaris mac

public void init()

winXP = new Checkbox(Windows XP null true)

mac = new Checkbox()

macsetLable(ldquoMac OSrdquo)

add(winXP)

add(mac)

winXPaddItemListener(this)

macaddItemListener(this)

public void itemStateChanged(ItemEvent ie)

repaint()

Display current state of the check boxes

public void paint(Graphics g)

msg = Current state

gdrawString(msg 6 80)

msg = Windows XP + winXPgetState()

gdrawString(msg 6 100)

msg = Mac OS + macgetState()

gdrawString(msg 6 120)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 33 of 38

c) Explain the techniques of session tracking management

(Any four techniques with explanation- 1 Mark each)

Ans Session tracking Techniques

1 User Authorization

Users can be authorized to use the web application in different ways Basic concept is that the

user will provide username and password to login to the application Based on that the user can

be identified and the session can be maintained

2 Hidden Fields

ltINPUT TYPE=rdquohiddenrdquo NAME=rdquotechnologyrdquo VALUE=rdquoservletrdquogt

Hidden fields like the above can be inserted in the webpages and information can be sent to the

server for session tracking These fields are not visible directly to the user but can be viewed

using view source option from the browsers This type doesnrsquot need any special configuration

from the browser of server and by default available to use for session tracking This cannot be

used for session tracking when the conversation included static resources lik html pages

3 URL Rewriting

Original URL httpserverportservletServletName

ewritten URL httpserverportservletServletNamesessionid=7456

When a request is made additional parameter is appended with the url In general added

additional parameter will be sessionid or sometimes the userid It will suffice to track the

session This type of session tracking doesnrsquot need any special support from the browser

Disadvantage is implementing this type of session tracking is tedious We need to keep track of

the parameter as a chain link until the conversation completes and also should make sure that

the parameter doesnrsquot clash with other application parameters

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 34 of 38

4 Cookies

Cookies are the mostly used technology for session tracking Cookie is a key value pair of

information sent by the server to the browser This should be saved by the browser in its space

in the client computer Whenever the browser sends a request to that server it sends the cookie

along with it Then the server can identify the client using the cookie

In java following is the source code snippet to create a cookie

Cookie cookie = new Cookie (ldquouserIDrdquo ldquo7456Prime)

resaddCookie(cookie)

5 Session tracking API

Session tracking API is built on top of the first four methods This is inorder to help the

developer to minimize the overhead of session tracking This type of session tracking is

provided by the underlying technology Lets take the java servlet example Then the servlet

container manages the session tracking task and the user need not do it explicitly using the java

servlets This is the best of all methods because all the management and errors related to

session tracking will be taken care of by the container itself

d) Give sequential steps for JTree in swing with example

(Steps- 2 Marks any small Example- 2 Marks)

Ans Steps for JTree

Atree is a component that presents a hierarchical view of data The user has the ability to

expand or collapse individual subtrees in this display Trees are implemented in Swing by

the JTree class

Here are the steps to follow to use a tree

1 Create an instance of JTree

2 Create a JScrollPane and specify the tree as the object to be scrolled

3 Add the tree to the scroll pane

4 Add the scroll pane to the content pane

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 35 of 38

Example

Demonstrate JTree

import javaawt

import javaxswingevent

import javaxswing

import javaxswingtree

ltapplet code=JTreeDemo width=400 height=200gt

ltappletgt

public class JTreeDemo extends JApplet

JTree tree

JLabel jlab

public void init()

try

SwingUtilitiesinvokeAndWait(

new Runnable()

public void run()

makeGUI()

)

catch (Exception exc)

Systemoutprintln(Cant create because of + exc)

private void makeGUI()

Create top node of tree

DefaultMutableTreeNode top = new DefaultMutableTreeNode(Options)

Create subtree of A

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 36 of 38

DefaultMutableTreeNode a = new DefaultMutableTreeNode(A)

topadd(a)

DefaultMutableTreeNode a1 = new DefaultMutableTreeNode(A1)

aadd(a1)

DefaultMutableTreeNode a2 = new DefaultMutableTreeNode(A2)

aadd(a2)

Create subtree of B

DefaultMutableTreeNode b = new DefaultMutableTreeNode(B)

topadd(b)

DefaultMutableTreeNode b1 = new DefaultMutableTreeNode(B1)

badd(b1)

DefaultMutableTreeNode b2 = new DefaultMutableTreeNode(B2)

badd(b2)

DefaultMutableTreeNode b3 = new DefaultMutableTreeNode(B3)

badd(b3)

Create the tree

tree = new JTree(top)

Add the tree to a scroll pane

JScrollPane jsp = new JScrollPane(tree)

Add the scroll pane to the content pane

add(jsp)

Add the label to the content pane

jlab = new JLabel()

add(jlab BorderLayoutSOUTH)

Handle tree selection events

treeaddTreeSelectionListener(new TreeSelectionListener()

public void valueChanged(TreeSelectionEvent tse)

jlabsetText(Selection is + tsegetPath())

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 37 of 38

e) Draw and explain the life cycle of servlet

(Explanation ndash 3 Marks Diagram -1 Marks)

Ans Three methods are central to the life cycle of a servlet

These are init( ) service( ) and destroy( )

They are implemented by every servlet and are invoked at specific times by the server Let

us consider a typical user scenario to understand when these methods are called

First assume that a user enters a Uniform Resource Locator (URL) to a web browser

The browser then generates an HTTP request for this URL This request is then sent to the

appropriate server

Second this HTTP request is received by the web server The server maps this request to

a particular servlet The servlet is dynamically retrieved and loaded into the address space

of the server

Third the server invokes the init( ) method of the servlet This method is invoked only

when the servlet is first loaded into memory It is possible to pass initialization parameters

to the servlet so it may configure itself

Fourth the server invokes the service( ) method of the servlet This method is called to

process the HTTP request You will see that it is possible for the servlet to read data that has

been provided in the HTTP request It may also formulate an HTTP response for the client

The servlet remains in the serverrsquos address space and is available to process any other

HTTP requests received from clients The service( ) method is called for each HTTP request

Finally the server may decide to unload the servlet from its memory The algorithms by

which this determination is made are specific to each server The server calls the destroy( )

method to relinquish any resources such as file handles that are allocated for the servlet

Important data may be saved to a persistent store The memory allocated for the servlet and

its objects can then be garbage collected

A servlet life cycle can be defined as the entire process from its creation till the destruction The

following are the paths followed by a servlet

The servlet is initialized by calling the init () method

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 38 of 38

The servlet calls service() method to process a clients request

The servlet is terminated by calling the destroy() method

Finally servlet is garbage collected by the garbage collector of the JVM

Initialization

(Load Resources)

Services

(Accept Requests)

Destruction

(Unload Resources)

Servlet

Request

Response

Page 3: AJP

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 3 of 38

c) List four differences between TCP and UDP 4

(Any four Points -1 Mark each)

Ans

TCP UDP

It is connection Oriented It is connectionless

It gives acknowledgement It does not give acknowledgement

It is reliable It is unreliable

It is use to transfer for large amount of

data It is use to transfer for small amont of data

Transmission seed is low Transmission seed is High

TCP header size is 20 bytes UDP Header size is 8 bytes

TCP does error checking UDP does error checking but no recovery

options

d) Write three factory method of InetAddress class 4

(Three method- 4 Marks)

Ans The Inet class has no invisible constructor

To create an Inet address objectyou have to use one of the available factory methods

Factory methods are merely aconvention whereby static methods in a class returns an instance of

that class

Three commonly used InetAddress factory methods are

1) static InetAddress getLocalHost()

throws unKnownHostException

This method simply returns the InetAddress object that represents the local host

2) static InetAddress getByName(String hostname)

throws unKnownHostException

This method simply returns the InetAddress for a host name passed to it

3) static InetAddress[] getAllByName(String hostname)

throws unKnownHostException

which takes an IPaddress and returns an InetAddress object

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 4 of 38

B) Attempt any one of the following Marks 6

a) List various types of JDBC drives Explain JDBC-ODBC bridge driver

(Types-2 Marks Bridge driver diagram - 1 Marks Discription-3 Marks)

Ans Type 1 JDBC-ODBC bridge

Type 2 JDBC-native API

Type 3100 pure java JDBC network

Type 4100 java

JDBC-ODBC bridge

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 5 of 38

This category works with ODBC drivers supplied by your database vendor or a third party

To use the bridge you must first have an ODBC driver specifically for you database and

additional software that you need for connectivity

Using ODBC also requires configuring on your system a DNS that represents the target database

Advantages

1) It offers the ability to connect to almost all databases on almost all platforms

2) It may be the only way to gain access to some low and desktop database and application

Disadvantages

1) ODBC driver must also be loaded on the target machine

2) Translation between JDBC and ODBC affects performance

b) Write a program to demonstrate the use of JScrollpane in swing

(Any 1 program- Applet tag-2mark correct logic-4 Marks Synatax-2 Marks)

Ans import javaawt

import javaxswing

ltapplet code=rdquoJScrollPaneDemordquo width=350

Height=250gt

ltappletgt

Public class JscrollPaneDemo extends JApplet

Public void init()

Container contentPane= get ContentPane()

contentPanesetLayout(new BorderLayout())

JPanel jp = new JPanel()

jpsetLayout(new GridLayout(2020))

int b=0

for(int i=0ilt20i++)

jpadd(new JButton(ldquoButtonrdquo+b)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 6 of 38

++b

int v=ScrollPaneConstantsVERTICAL_SCROLLBAR_AS_NEEDED

int h= ScrollPaneConstantsHORIZONTAL_SCROLLBAR_AS_NEEDED

JScrollPane jsp= new JScrollPane(jpvh)

contentPaneadd(jspBorderLayoutCENTER)

2 Attempt any two of the following Marks 16

a) Write an application program making use of menu and menu bar class 8

(Applet tag ndash 1Mark correct logic to add menu and menubar - 5 Marks Synatax-2 Marks)

Ans import javaawt

import javaawtevent

import javaapplet

ltapplet code=rdquo MenuFramerdquo width=350

Height=250gt

ltappletgt

class MenuFrame extends Frame implements ActionListener

String msg=rdquordquo

MenuFrame(String title)

super(title)

MenuBar mbar= new menuBar()

setMentBar(mbar)

Menu file=new Menu(ldquoFilerdquo)

MenuItem item1item2item3item4item5

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 7 of 38

item1= new MenuItem (ldquoNewrdquo)

item2= new MenuItem (ldquoopenrdquo)

item3= new MenuItem (ldquocloserdquo)

item4= new MenuItem (ldquo-rdquo)

item5= new MenuItem (ldquoQuitrdquo)

fileadd(item1)

fileadd(item2)

fileadd(item3)

fileadd(item4)

fileadd(item5)

mbaradd(file)

MenuItem item6item7item8item9

item6= new MenuItem (ldquocutrdquo)

item7= new MenuItem (ldquocopyrdquo)

item8= new MenuItem (ldquopasterdquo)

item9= new MenuItem (ldquo-rdquo)

editadd(item6)

editadd(item7)

editadd(item8)

editadd(item9)

mbaradd(edit)

item1addActionListener(this)

item2addActionListener(this)

item3addActionListener(this)

item4addActionListener(this)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 8 of 38

item5addActionListener(this)

item6addActionListener(this)

item7addActionListener(this)

item8addActionListener(this)

item9addActionListener(this)

Public void paint(Graphics g)

gdrawString(msg10200)

public void actionPerformed(ActionEvent e)

msg= ldquoYou have selected rdquo+ egetActionCommand()

repaint()

public static void main(String args[])

MenuFrame m=new MenuFrame(ldquoMyMenurdquo)

msetVisible(true)

msetSize(100200)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 9 of 38

b) Give the use of Server Socket and Socket class Describe the steps that are 8

required to establish communication between client and server sockets

(Use-2 Marks each class Steps-4 Marks)

Ans Server socket

A Server Socket handles the requests and sends back an appropriate reply The actual tasks that a

server socket must accomplish are implemented by an internal SocketImpl instance A server

socket waits for requests to come in over the network It performs some operation based on that

request and then possibly returns a result to the requester The actual work of the server socket is

performed by an instance of the SocketImpl class An application can change the socket factory

that creates the socket implementation to configure itself to create sockets appropriate to the local

firewall

Client socket

we have used the class named ClientSocketInformationjava that implement the constructor of

the Socket class passing two arguments as hostName and TIME_PORT This program throws an

IOException for the exception handling This exception is thrown to indicate an IO problem of

some sort occurred Here we are going to explore a method to retrieve the host name of the local

system in a very simple way In this way we find out the Local address Local host information

reuseAddress and address of the local system in a very simple manner

Steps to connect

Using TCP socket provides the communication mechanism between two computers A client

program creates a socket at its end of the communication and attempts to connect that socket to a

server

The following is the lists of sequential steps which occur when establishing a TCP connection

between client socket and server socket

1 The server initiates a Server Socket object and mentions which port number communication is

to occur on

2 The server invokes the accept () method of the ServerSocket class This method does the wait

till a client gets connected to the server on the given port

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 10 of 38

After the waiting stages of server a client instantiates a Socket object It also specifies the

server name and port number to which it gets connected

3 The constructor of the Socket class tries to connect the client to the specified server and port

number If the communication is established the client has a Socket object which is capable

of communicating with the server

4 On server side the accept () method returns a reference to a new socket on the server that is

connected to the clientrsquos socket

Once the connection are established communication occur using IO streams Each socket has

both an Outputstream and InputStreams

As we know that the TCP is a two way communication protocol So data can be sent across

both streams at the same time

Two constructors used to create client socket

Socket (String hostnameint port)

Creates a socket connection the localhost to name host and port

Socket(InetAddress ipAddressint port)

Creates a socket using pre existing InetAddress object and a port

A socket can be examined at any time for the address and port information associated with it

InetAddress getInetAddress()

Int getPort()

Int getLocalPort()

Once the socket object has been created it can be examined to gain access to ip and op streams

associated with it

Example (optional)

import javanet

import javaio

class abc

public static void main(String args[])throws Exception

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 11 of 38

int c

Socket s=new socket(ldquointericnetrdquo43)

InputStream in=sgetInputStream()

OutputStream out=sgetOutputStream()

String str=(argslength==0rdquoOsbornecomrdquo)

byte buf[]=strgetBytes()outwrite(buf)

while((c=inread())=-1)

Systemoutprintln(char)c)

sclose()

c) Give sequential steps to use JTabbedPane in an Applet with example

(Steps- 4Marks any one Example- 4Marks)

Ans The general procedure to use a tabbed pane in an applet is

1) Create a JtabbedPane object

2) Call addTab() to add to the pane

3) Repeat step 2 for each tab

4) Add the tabbed pane to the content pane of the applet

Example

import javaxswing

ltapplet code=rdquoJTabbedPaneDemordquo width=350

Height=250gt

ltappletgt

public class JTabbedPaneDemo extends JApplet

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 12 of 38

public void init()

JTabbedPane jtp= new JTabbedPane()

jtpaddTab(ldquocitiesrdquonew citiesPanel())

jtpaddTab(ldquocolorsrdquonew colorsPanel())

jtpaddTab(ldquoFlavourrdquonew flavourPanel())

getContentPane()add(jtp)

class citiespanel extends JPanel

Public citiesPanel()

JButton b1=new Button(ldquoNew Yorkrdquo)

add(b1)

JButton b2=new Button(ldquolondonrdquo)

add(b2)

class colorpanel extends JPanel

Public colorPanel()

JCheckBox cb1=new JCheckBox(ldquoredrdquo)

add(cb1)

JCheckBox cb2=new JCheckBox (ldquogreenrdquo)

add(cb2)

class flavourpanel extends JPanel

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 13 of 38

public flavourPanel()

JComboBox b=new JComboBox()

jcbaddItem(ldquovanillardquo)

jcbaddItem(ldquochocolaterdquo)

add(jcb)

3 Attempt any four of the following Marks 16

a) Example the use of prepared statement with example 4

(Explanation-2 Marks Example-2 Marks)

Ans PrepareStatement ()

The preparedStatement() method creates a PreparedStatement object and returns it as a return

value The Prepared statement object is used to execute dynamic SQL statement against the

databaseA dynamic SQL statement is a statement in which some of the parameters in the

statement are unknown when the statement is created The parameter is placed into the SQL

statement as they are determined by the application When all the parameters are specified for the

SQL statement the dynamic SQL statement will be executed just as a static statement is executed

To create a dynamic SQL statement that takes a first name and last name as parameters use the

following code

try

String sql=rdquoSelect from temployeerdquo + ldquowhere Firstname=rdquo + ldquoand Lastname=rdquo

PreparedStatement p=connectionpreparedStatement(sql)

Catch(SQLException e)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 14 of 38

b) List any four differences between AWT and swing 4

(Any four points ndash 1 Mark each)

Ans

Swing AWT

It uses javaxswing package It uses javaapplet package

It uses JApplet class It uses Applet class

Swing is light weight component AWT is heavy weight component

It does not have add() method to add

control

It has add() method to add control

AWT provides less features than

swing

Swing has variety of component amp

features which is not in AWT

Awt has huge collection of classes amp

interfaces

Swing has bigger collection of classes

amp interfaces than AWT

AWT has predefined formats of

appearance amp behavior of component

Swing provides a facility of different

appearance amp behavior of the same

component

c) List four interfaces in javaxservlet package 4

(Any four points ndash 1 Mark each)

Ans Following are the interfaces in javaxservlet package

1 Servlet All servlets must implement the Servlet interface It declares the init( ) service( )

and destroy( ) methods that are called by the server during the life cycle of a servlet

2 ServletConfig The ServletContextinterface is implemented by the server It enables servlets

to obtain information about their environment

3 ServletContext The ServletContextinterface is implemented by the server It enables

servlets to obtain information about their environment

4 ServletRequest The ServletRequestinterface is implemented by the server It enables a

servlet to obtain information about a client request

5 ServletResponse The ServletResponseinterface is implemented by the server It enables a

servlet to formulate a response for a client

6 SingleThreadModel This interface is used to indicate that only a single thread will execute

the service( ) method of a servlet at a given time It defines no constants and declares no

methods

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 15 of 38

d) Give the use of ImageIcon class with example 4

(Explanation ndash 2 Marks Example- 2 Marks)

Ans In Swing icons are encapsulated by the ImageIconclass which paints an icon from an

image Two of its constructors are shown here

ImageIcon(String filename)

ImageIcon(URL url)

The first form uses the image in the file named filename The second form uses the

image in the resource identified by url

The ImageIconclass implements the Icon interface that declares the methods

As follows

Method Description

intgetIconHeight( ) Returns the height of the iconin pixels

intgetIconWidth( ) Returns the width of the iconin pixels

voidpaintIcon(Component comp Graphics gintx inty)Paints the icon at position x y onthe

graphics context g Additionalinformation about the paintoperation can be provided in comp

Example

import javaawt

import javaxswing

ltapplet code=JLabelDemo width=250 height=150gt

ltappletgt

public class JLabelDemo extends JApplet

public void init()

Get content pane

Container contentPane = getContentPane()

Create an icon

ImageIcon ii = new ImageIcon(francegif)

Create a label

JLabeljl = new JLabel(France ii JLabelCENTER)

Add label to the content pane

contentPaneadd(jl)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 16 of 38

e) Give the use of URL class along with syntax of constructors of URL class 4

(Use - 2 Marks Any two Constructor - 1 Mark each)

Ans The URL provides a reasonably intelligible form to uniquely identify or address information on the

Internet URLs are ubiquitous every browser uses them to identify information on the Web In

fact the Web is really just that same old Internet with all of its resources addressed as URLs plus

HTML

Javas URL class has several constructors One commonly used form specifies the URL with a

string that is identical to what you see displayed in a browser

1 URL(String urlSpecifier)

The next two forms of the constructor allow you to break up the URL into its componentparts

2 URL(String protocolName String hostName intport String path)

3 URL(String protocolName String hostName String path)

Another frequently used constructor allows you to use an existing URL as a referencecontext and

then create a new URL from that context Although this sounds a littlecontorted its really quite

easy and useful

4 URL(URL urlObj String urlSpecifier)

4 A) Attempt any three of the following Marks 12

a) Give the use of following methods of statement interface 4

i) executeQuery( ) ii) execute Update ( )

(Each method ndash 2 Marks)

Ans i) executeQuery()

The executeQuery() method of the statement object enables you to send SQL select statement to

the database and to receive result from the database Executing a query in effect sends a SQL

select statement to the database and returns the appropriate results back in the Resultset object

The executeQuery() method takes a SQL select statement as a parameter and returns a ResultSet

object that contains all the records that match the select statements criteria

ii) executeUpdate()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 17 of 38

The executeUpdate() method of the Statement object enables you to execute SQL update

statements such as delete insert and update The method takes a String containing the SQL update

statement and returns an integers that determines how many records were affected by the SQL

statement

b) Define Layout Manager Describe the use of GridLayout Manager 4

(Layout manager- 2 Marks Use-2 Marks)

Ans Each Container object has a layout manager associated with it A layout manager

is an instance of any class that implements the LayoutManagerinterface The layout

manager is set by the setLayout( ) method If no call to setLayout( ) is made then the

default layout manager is used Whenever a container is resized (or sized for the first

time) the layout manager is used to position each of the components within it

The setLayout( ) method has the following general form

voidsetLayout(LayoutManagerlayoutObj)

GridLayoutManager

GridLayout lays out components in a two-dimensional grid When you instantiate

a GridLayout you define the number of rows and columns The constructors

supported by GridLayoutare shown here

GridLayout( )

GridLayout(intnumRows intnumColumns)

GridLayout(intnumRows intnumColumns inthorz intvert)

c) Explain the use of cookies with example 4

(Explanation - 2 Marks Example - 2 Marks any one)

Ans Cookie is a small piece of information that is passed back and forth in the HTTP request and

response Even though a cookie can be created on the client side using some scripting language

such as JavaScript it is usually created by the server resource such as a Servlet The Cookies sent

by the server when the client requests another page from the same application In Servlet

programming a cookie is represented by a Cookie class in the javaxservlethttp package You can

create a cookie by calling the Cookie class constructor and passing two string objects the name

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 18 of 38

and value of the cookie For instance the following code creates a cookie object called c1The

cookie has the name ldquomyCookierdquo and value of rdquosecretrdquo

Cookie c1=new Cookie(ldquomyCookierdquordquosecretrdquo)

You then can add the cookie to the http response using addCookie method of the

HTTPServletResponse interfaceResponseaddCookie(c1)

Program for Add cookies

import javaio

importjavaxservlet

importjavaxservlethttp

public class AddCookieServlet extends HttpServlet

public void doPost(HttpServletRequest requestHttpServletResponse response)

throwsServletException IOException

Get parameter from HTTP request

String data = requestgetParameter(data)

Create cookie

Cookie cookie = new Cookie(MyCookie data)

Add cookie to HTTP response

responseaddCookie(cookie)

Write output to browser

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgtMyCookie has been set to)

pwprintln(data)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 19 of 38

pwclose()

OR

Program for Get Cookies

import javaio

importjavaxservlet

importjavaxservlethttp

public class GetCookiesServlet extends HttpServlet

public void doGet(HttpServletRequest requestHttpServletResponse response)

throwsServletException IOException

Get cookies from header of HTTP request

Cookie[] cookies = requestgetCookies()

Display these cookies

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgt)

for(inti = 0 iltcookieslength i++)

String name = cookies[i]getName()

String value = cookies[i]getValue()

pwprintln(name = + name +

value = + value)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 20 of 38

pwclose()

d) Give steps to create simple servlet with example 4

(Steps- 2 Marks Any one Example ndash 2 Marks)

Ans Steps 1) Write a java servet code

Steps 2) Compile Servet by setting classpath with servlet-api library

Step 3) Copy the class servlet file in web apps classpath directory

Steps 4) Open the webxml open it and add servlet tag and sevlet mapping tag

Steps 5) Start web server(apche tomcat)

Steps 6) Browse servlet using java compatible browser like IE

Example shows to start create a file named WelcomeServletjava that contains the following

program

import javaio

importjavaxservlet

public class WelcomeServletDemo extends GenericServlet

public void service(ServletRequestrequestServletResponse response) throws

ServletExceptionIOException

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgtWelcome to Servlet)

pwclose()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 21 of 38

B) Attempt any one of the following Marks 6

a) Describe the two ndashtier and three ndashtier database design of JDBC API with neat diagram

(Explanation of Two-tier-2 Marks and Three-tier-2 Marks Diagram ndash 1 Mark each)

Ans Two Tier Architecture

In a two tier model a java application is designed to interact directly with the database

Application functionality is divided into these two layers

1) Application Layer Including the JDBC driver business logic and user interface

2) Database Layer including RDBMS

The interface to the database is handled by the Java Database Connectivity(JDBC) Driver

appropriate to the particularly database management system being accessed The JDBC Driver

passes SQL statements to the database and returns the results of those statements to the

application

A clientserver configuration is the special case of the two tier model where the database is

located on another machine referred to as the server The application runs on the client machine

which is connected to the server over a network Commonly the network is an Intranet using

dedicated database servers to support multiple clients but it can just as easily be the internet

Three Tier Architecture-

In the three tier model the client typically sends requests to an application server forming the

middle tier The application server interprets these requests and formats the necessary SQL

statement to fulfill

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 22 of 38

These requests and sends them to the database The database process the SQL statements and

sends result back to the application server which then sends them to the client

Following are some advantages of Three-tier architecture

1 Performance can be improved by separating the application server and database server

2 Business logic is clearly separated from the database

3 Client application can use a simple protocol such as CGI to access services

The three-tier model show in following fig is a common in web application In this scenario the

client tier is frequently implemented in a browse on a client machine the middle tier is

implemented in a web server with a Servlet engine and the database management system runs on

a dedicated database server

Following are the main components of three tier architecture

1 Client Tier - Typically this is thin presentation layer that may be implemented using a web

browser

2 Middle Tier - This tier handles the business or application logic This may be implemented

using a Servlet engine such as Tomcat or an application server such as JBOSS The JDBC

driver also resides in this layer

3 Data source layer This component includes the RDBMS

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 23 of 38

b) Write servlet which shows how many times user has visited the page in session

(Any Correct Logic ndash4 Marks Syntax ndash 2 Marks)

Ans import javaio

import javaxservlet

import javaxservlethttp

public class Session Travker extends HttpServlet

public void doGet(HttpServletRequest req HttpServletResponse res) throws ServletException

IOException

ressetContentType(ldquotexthtmlrdquo)

PrintWriter out = resgetWriter()

HttpSession session = reqgetSession(true)

Integer count= (Integer)sessiongetValue(ldquotrackercountrdquo)

if(count== null) count=new Interger(1)

else count = new Interger(count intValue() +1)

sessionputValue(ldquotrackercountrdquocount)

outprintln(ldquoltHTMLgtltHEADgtltTITLEgtSession TrackerltTITLEgtltHEADgtrdquo)

outprintln(ldquoltBODYgtltH1gtSession Tracking DemoltH1gtrdquo)

outprintln(ldquoYou have visited this pagerdquo +count +((countintValue() == 1)rdquotimerdquo

ldquotimesrdquo))outprinln(ltPgtrdquo)

outprintln(ldquoltH2gtSesssion dataltH2gtrdquo)

String[] names = sessiongetValueNames()

for(int i=0 ilt nameslength i++)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 24 of 38

outprintln(names[i] + ldquo rdquo + sessiongetvalue(names[i])+ ldquoltBRgtrdquo)

outprintln(ldquoltBODYgtltHTMLgtrdquo)

5 Attempt any two of the following Marks 16

a) Write a program to display all records from Employee table from database using

JDBC

(Assume suitable data for table- Load driver create connection execute Query - 1 Mark

each Display data- 3 Marks Syntax ndash 2 Marks)

Ans import javasql

import javasqlStatement

import javaapplet

import javaawt

public class DisplayTable

public static void main( String args[])

RsultSet rs

Connection conn

try

String s1

ClassforName(sun jdbcodbcJdbcOdbcDriver)

Systemoutprintln(Connecting to a selected database)

String url=rdquojdbcodbcabcrdquo

conn = DriverManagergetConnection(DB_URL USER PASS)

Systemoutprintln(Connected database successfully)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 25 of 38

Systemoutprintln(Creating statement)

stmt = conncreateStatement()

sql = SELECT FROM Employee

ResultSet rs = stmtexecuteQuery(sql)

Tables fields assumed are id first last age

while(rsnext())

int id = rsgetInt(id)

int age = rsgetInt(age)

String first = rsgetString(first)

String last = rsgetString(last)

Systemoutprint(ID + id)

Systemoutprint( Age + age)

Systemoutprint( First + first)

Systemoutprintln( Last + last)

rsclose()

catch(SQLException se)

Handle errors for JDBC

seprintStackTrace()

catch(Exception e)

Handle errors for ClassforName

eprintStackTrace()

finally

finally block used to close resources

try

if(stmt=null)

connclose()

catch(SQLException se)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 26 of 38

b) Define the term

i) Reserved socket ii) proxy server

iii) Datagram iv) URL connection 4

(Each term- 2 Marks)

Ans i) Reserved socket

A socket is one end-point of a two-way communication link between two programs running on

the network Socket classes are used to represent the connection between a client program and a

server program

Reserved socket The socket which are reserved for specific protocols for communication

purpose are known as reseved sockets

TCPIP uses or reserves the lower 1024 ports for specific protocols

Example port number 23 is for Telnet 25 is for smtp 21 is for ftp 13 for daytime 110 for pop3

and so on Protocol decides how a client should interact with the port

ii) Proxy server

A proxy server is a computer that offers a computer network service to allow clients to make

indirect network connections to other network services A client connects to the proxy server

then requests a connection file or other resource available on a different server The proxy

provides the resource either by connecting to the specified server or by serving it from a cache In

some cases the proxy may alter the clients request or the servers response for various purposes

Purposes of the proxy servers

To keep machines behind it anonymous mainly for security

To speed up access to resources (using caching) Web proxies are commonly used to

cache web pages from a web server

To prevent downloading the same content multiple times (and save bandwidth)

To log audit usage eg to provide company employee Internet usage reporting

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 27 of 38

To scan transmitted content for malware before delivery

To scan outbound content eg for data loss prevention

iii) Datagram

Datagrams are bundles of information passed between machines They are somewhat like a hard

throw from a well-trained but blindfolded catcher to the third baseman Once the datagram has

been released to its intended target there is no assurance that it will arrive or even that

someone will be there to catch it Likewise when the datagram is received there is no

assurance that it hasnrsquot been damaged in transit or that whoever sent it is still there to receive a

response

Java implements datagrams on top of the UDP protocol by using two classes

The DatagramPacket object is the data container while the DatagramSocket is the mechanism

used to send or receive the DatagramPackets

iv) URL connection

URLConnection is a general-purpose class for accessing the attributes of a remote resource

Once you make a connection to a remote server you can use URLConnection to inspect the

Properties of the remote object before actually transporting it locally These attributes are

exposed by the HTTP protocol specification and as such only make sense for URL objects

that are using the HTTP protocol

URLConnection defines several methods

int getContentLength( )

String getContentType( )

long getDate( )

long getExpiration( )

String getHeaderField(int idx)

long getLastModified( )

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 28 of 38

c) Write a program to display three text fields and a button below to all an Applet Insert

the integer valuer from three text fields After pressing the button the background colour

of applet will be changed as per the RGB combination of the values given in the text field

(Correct logic - 6 Marks Syntax - 2 Marks)

4

Ans import javaawt

import javaawtevent

import javaapplet

ltapplet code=rdquoClrclassrdquo width=250 heigth=250gtltappletgt

public class Clrextends Applet implements ActionListener

int r g b

TextField t1t2t3

Button b1

Color c1

public void init()

t1= new TextField(5)

t2= new TextField(8)

t3= new TextField(11)

b1 = new Button(ldquo Set Colorrdquo)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 29 of 38

add(t1)

add(t2)

add(t3)

add(b1)

b1addActionListener(this)

public void void paint( )

setBackground(c1)

public void actionPerformed(ActionEvent ae)

r=IntegerparseInt(t1getText())

g=IntegerparseInt(t2getText())

b=IntegerparseInt(t3getText())

c1= new Color(rgb)

repaint()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 30 of 38

6) Attempt any four of the following Marks 16

a) How to check how many fonts are available in the computer system 4

Explain with example

(Explanation -2 Marks Example-2 Marks)

Ans When working with fonts often you need to know which fonts are available on your machine To

ontain this information you can use the getAvailableFontFamilyNames() method defined by the

GraphicsEnvironment classIt is shown here

String[ ] getAvailableFontFamilyNames( )

This method returns an array of string that contains the names of the available font families

Since this methods is members of GraphicsEnvironment you need a GraphicsEnvironment

reference to call itYou can obtain this reference by using the getlocalGrahicsEnvironmet() static

method which is derfined by GraphicsEnvironmentIt is shown here

static GraphicsEnvironment getLocalGraphicsEnvironment( )

Here is an applet that shown how to obtain the names of the available font families

ltapplet code=rdquoAllFontsrdquo width=500 height=100gt

ltappletgt

import javaapplet

import javaawt

public class AllFonts extends Applet

public void paint(Graphics g)

string fonts= ldquo rdquo

stirng allFontsList[]

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 31 of 38

GraphicsEnvironment t = GraphicsEnvironmentgetLocalGraphicsEnvironment()

allFontList = tgetAvailableFontFamilyNames()

for(int i= 0 ilt allFontsListlength i++)

fonts= fonts + allFontList[i] + ldquo rdquo

gdrawString(msg416)

b) Explain following check box class methods with appropriate example 4

i) Void setLable (String str) ii) Boolean getState ( )

(Explanation of each method-1 Marks Example-2 Marks)

Ans

i) void setLable(String str)

This method is used to set the label of check box

ii) Boolean getState()

This method is used to retrieve the current state of a check box It returns the value either true or

false depends on check box is selected or not

Example

Demonstrate check boxes

import javaawt

import javaawtevent

import javaapplet

ltapplet code=CheckboxDemo width=250 height=200gt

ltappletgt

public class CheckboxDemo extends Applet implements ItemListener

String msg =

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 32 of 38

Checkbox winXP winVista solaris mac

public void init()

winXP = new Checkbox(Windows XP null true)

mac = new Checkbox()

macsetLable(ldquoMac OSrdquo)

add(winXP)

add(mac)

winXPaddItemListener(this)

macaddItemListener(this)

public void itemStateChanged(ItemEvent ie)

repaint()

Display current state of the check boxes

public void paint(Graphics g)

msg = Current state

gdrawString(msg 6 80)

msg = Windows XP + winXPgetState()

gdrawString(msg 6 100)

msg = Mac OS + macgetState()

gdrawString(msg 6 120)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 33 of 38

c) Explain the techniques of session tracking management

(Any four techniques with explanation- 1 Mark each)

Ans Session tracking Techniques

1 User Authorization

Users can be authorized to use the web application in different ways Basic concept is that the

user will provide username and password to login to the application Based on that the user can

be identified and the session can be maintained

2 Hidden Fields

ltINPUT TYPE=rdquohiddenrdquo NAME=rdquotechnologyrdquo VALUE=rdquoservletrdquogt

Hidden fields like the above can be inserted in the webpages and information can be sent to the

server for session tracking These fields are not visible directly to the user but can be viewed

using view source option from the browsers This type doesnrsquot need any special configuration

from the browser of server and by default available to use for session tracking This cannot be

used for session tracking when the conversation included static resources lik html pages

3 URL Rewriting

Original URL httpserverportservletServletName

ewritten URL httpserverportservletServletNamesessionid=7456

When a request is made additional parameter is appended with the url In general added

additional parameter will be sessionid or sometimes the userid It will suffice to track the

session This type of session tracking doesnrsquot need any special support from the browser

Disadvantage is implementing this type of session tracking is tedious We need to keep track of

the parameter as a chain link until the conversation completes and also should make sure that

the parameter doesnrsquot clash with other application parameters

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 34 of 38

4 Cookies

Cookies are the mostly used technology for session tracking Cookie is a key value pair of

information sent by the server to the browser This should be saved by the browser in its space

in the client computer Whenever the browser sends a request to that server it sends the cookie

along with it Then the server can identify the client using the cookie

In java following is the source code snippet to create a cookie

Cookie cookie = new Cookie (ldquouserIDrdquo ldquo7456Prime)

resaddCookie(cookie)

5 Session tracking API

Session tracking API is built on top of the first four methods This is inorder to help the

developer to minimize the overhead of session tracking This type of session tracking is

provided by the underlying technology Lets take the java servlet example Then the servlet

container manages the session tracking task and the user need not do it explicitly using the java

servlets This is the best of all methods because all the management and errors related to

session tracking will be taken care of by the container itself

d) Give sequential steps for JTree in swing with example

(Steps- 2 Marks any small Example- 2 Marks)

Ans Steps for JTree

Atree is a component that presents a hierarchical view of data The user has the ability to

expand or collapse individual subtrees in this display Trees are implemented in Swing by

the JTree class

Here are the steps to follow to use a tree

1 Create an instance of JTree

2 Create a JScrollPane and specify the tree as the object to be scrolled

3 Add the tree to the scroll pane

4 Add the scroll pane to the content pane

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 35 of 38

Example

Demonstrate JTree

import javaawt

import javaxswingevent

import javaxswing

import javaxswingtree

ltapplet code=JTreeDemo width=400 height=200gt

ltappletgt

public class JTreeDemo extends JApplet

JTree tree

JLabel jlab

public void init()

try

SwingUtilitiesinvokeAndWait(

new Runnable()

public void run()

makeGUI()

)

catch (Exception exc)

Systemoutprintln(Cant create because of + exc)

private void makeGUI()

Create top node of tree

DefaultMutableTreeNode top = new DefaultMutableTreeNode(Options)

Create subtree of A

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 36 of 38

DefaultMutableTreeNode a = new DefaultMutableTreeNode(A)

topadd(a)

DefaultMutableTreeNode a1 = new DefaultMutableTreeNode(A1)

aadd(a1)

DefaultMutableTreeNode a2 = new DefaultMutableTreeNode(A2)

aadd(a2)

Create subtree of B

DefaultMutableTreeNode b = new DefaultMutableTreeNode(B)

topadd(b)

DefaultMutableTreeNode b1 = new DefaultMutableTreeNode(B1)

badd(b1)

DefaultMutableTreeNode b2 = new DefaultMutableTreeNode(B2)

badd(b2)

DefaultMutableTreeNode b3 = new DefaultMutableTreeNode(B3)

badd(b3)

Create the tree

tree = new JTree(top)

Add the tree to a scroll pane

JScrollPane jsp = new JScrollPane(tree)

Add the scroll pane to the content pane

add(jsp)

Add the label to the content pane

jlab = new JLabel()

add(jlab BorderLayoutSOUTH)

Handle tree selection events

treeaddTreeSelectionListener(new TreeSelectionListener()

public void valueChanged(TreeSelectionEvent tse)

jlabsetText(Selection is + tsegetPath())

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 37 of 38

e) Draw and explain the life cycle of servlet

(Explanation ndash 3 Marks Diagram -1 Marks)

Ans Three methods are central to the life cycle of a servlet

These are init( ) service( ) and destroy( )

They are implemented by every servlet and are invoked at specific times by the server Let

us consider a typical user scenario to understand when these methods are called

First assume that a user enters a Uniform Resource Locator (URL) to a web browser

The browser then generates an HTTP request for this URL This request is then sent to the

appropriate server

Second this HTTP request is received by the web server The server maps this request to

a particular servlet The servlet is dynamically retrieved and loaded into the address space

of the server

Third the server invokes the init( ) method of the servlet This method is invoked only

when the servlet is first loaded into memory It is possible to pass initialization parameters

to the servlet so it may configure itself

Fourth the server invokes the service( ) method of the servlet This method is called to

process the HTTP request You will see that it is possible for the servlet to read data that has

been provided in the HTTP request It may also formulate an HTTP response for the client

The servlet remains in the serverrsquos address space and is available to process any other

HTTP requests received from clients The service( ) method is called for each HTTP request

Finally the server may decide to unload the servlet from its memory The algorithms by

which this determination is made are specific to each server The server calls the destroy( )

method to relinquish any resources such as file handles that are allocated for the servlet

Important data may be saved to a persistent store The memory allocated for the servlet and

its objects can then be garbage collected

A servlet life cycle can be defined as the entire process from its creation till the destruction The

following are the paths followed by a servlet

The servlet is initialized by calling the init () method

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 38 of 38

The servlet calls service() method to process a clients request

The servlet is terminated by calling the destroy() method

Finally servlet is garbage collected by the garbage collector of the JVM

Initialization

(Load Resources)

Services

(Accept Requests)

Destruction

(Unload Resources)

Servlet

Request

Response

Page 4: AJP

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 4 of 38

B) Attempt any one of the following Marks 6

a) List various types of JDBC drives Explain JDBC-ODBC bridge driver

(Types-2 Marks Bridge driver diagram - 1 Marks Discription-3 Marks)

Ans Type 1 JDBC-ODBC bridge

Type 2 JDBC-native API

Type 3100 pure java JDBC network

Type 4100 java

JDBC-ODBC bridge

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 5 of 38

This category works with ODBC drivers supplied by your database vendor or a third party

To use the bridge you must first have an ODBC driver specifically for you database and

additional software that you need for connectivity

Using ODBC also requires configuring on your system a DNS that represents the target database

Advantages

1) It offers the ability to connect to almost all databases on almost all platforms

2) It may be the only way to gain access to some low and desktop database and application

Disadvantages

1) ODBC driver must also be loaded on the target machine

2) Translation between JDBC and ODBC affects performance

b) Write a program to demonstrate the use of JScrollpane in swing

(Any 1 program- Applet tag-2mark correct logic-4 Marks Synatax-2 Marks)

Ans import javaawt

import javaxswing

ltapplet code=rdquoJScrollPaneDemordquo width=350

Height=250gt

ltappletgt

Public class JscrollPaneDemo extends JApplet

Public void init()

Container contentPane= get ContentPane()

contentPanesetLayout(new BorderLayout())

JPanel jp = new JPanel()

jpsetLayout(new GridLayout(2020))

int b=0

for(int i=0ilt20i++)

jpadd(new JButton(ldquoButtonrdquo+b)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 6 of 38

++b

int v=ScrollPaneConstantsVERTICAL_SCROLLBAR_AS_NEEDED

int h= ScrollPaneConstantsHORIZONTAL_SCROLLBAR_AS_NEEDED

JScrollPane jsp= new JScrollPane(jpvh)

contentPaneadd(jspBorderLayoutCENTER)

2 Attempt any two of the following Marks 16

a) Write an application program making use of menu and menu bar class 8

(Applet tag ndash 1Mark correct logic to add menu and menubar - 5 Marks Synatax-2 Marks)

Ans import javaawt

import javaawtevent

import javaapplet

ltapplet code=rdquo MenuFramerdquo width=350

Height=250gt

ltappletgt

class MenuFrame extends Frame implements ActionListener

String msg=rdquordquo

MenuFrame(String title)

super(title)

MenuBar mbar= new menuBar()

setMentBar(mbar)

Menu file=new Menu(ldquoFilerdquo)

MenuItem item1item2item3item4item5

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 7 of 38

item1= new MenuItem (ldquoNewrdquo)

item2= new MenuItem (ldquoopenrdquo)

item3= new MenuItem (ldquocloserdquo)

item4= new MenuItem (ldquo-rdquo)

item5= new MenuItem (ldquoQuitrdquo)

fileadd(item1)

fileadd(item2)

fileadd(item3)

fileadd(item4)

fileadd(item5)

mbaradd(file)

MenuItem item6item7item8item9

item6= new MenuItem (ldquocutrdquo)

item7= new MenuItem (ldquocopyrdquo)

item8= new MenuItem (ldquopasterdquo)

item9= new MenuItem (ldquo-rdquo)

editadd(item6)

editadd(item7)

editadd(item8)

editadd(item9)

mbaradd(edit)

item1addActionListener(this)

item2addActionListener(this)

item3addActionListener(this)

item4addActionListener(this)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 8 of 38

item5addActionListener(this)

item6addActionListener(this)

item7addActionListener(this)

item8addActionListener(this)

item9addActionListener(this)

Public void paint(Graphics g)

gdrawString(msg10200)

public void actionPerformed(ActionEvent e)

msg= ldquoYou have selected rdquo+ egetActionCommand()

repaint()

public static void main(String args[])

MenuFrame m=new MenuFrame(ldquoMyMenurdquo)

msetVisible(true)

msetSize(100200)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 9 of 38

b) Give the use of Server Socket and Socket class Describe the steps that are 8

required to establish communication between client and server sockets

(Use-2 Marks each class Steps-4 Marks)

Ans Server socket

A Server Socket handles the requests and sends back an appropriate reply The actual tasks that a

server socket must accomplish are implemented by an internal SocketImpl instance A server

socket waits for requests to come in over the network It performs some operation based on that

request and then possibly returns a result to the requester The actual work of the server socket is

performed by an instance of the SocketImpl class An application can change the socket factory

that creates the socket implementation to configure itself to create sockets appropriate to the local

firewall

Client socket

we have used the class named ClientSocketInformationjava that implement the constructor of

the Socket class passing two arguments as hostName and TIME_PORT This program throws an

IOException for the exception handling This exception is thrown to indicate an IO problem of

some sort occurred Here we are going to explore a method to retrieve the host name of the local

system in a very simple way In this way we find out the Local address Local host information

reuseAddress and address of the local system in a very simple manner

Steps to connect

Using TCP socket provides the communication mechanism between two computers A client

program creates a socket at its end of the communication and attempts to connect that socket to a

server

The following is the lists of sequential steps which occur when establishing a TCP connection

between client socket and server socket

1 The server initiates a Server Socket object and mentions which port number communication is

to occur on

2 The server invokes the accept () method of the ServerSocket class This method does the wait

till a client gets connected to the server on the given port

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 10 of 38

After the waiting stages of server a client instantiates a Socket object It also specifies the

server name and port number to which it gets connected

3 The constructor of the Socket class tries to connect the client to the specified server and port

number If the communication is established the client has a Socket object which is capable

of communicating with the server

4 On server side the accept () method returns a reference to a new socket on the server that is

connected to the clientrsquos socket

Once the connection are established communication occur using IO streams Each socket has

both an Outputstream and InputStreams

As we know that the TCP is a two way communication protocol So data can be sent across

both streams at the same time

Two constructors used to create client socket

Socket (String hostnameint port)

Creates a socket connection the localhost to name host and port

Socket(InetAddress ipAddressint port)

Creates a socket using pre existing InetAddress object and a port

A socket can be examined at any time for the address and port information associated with it

InetAddress getInetAddress()

Int getPort()

Int getLocalPort()

Once the socket object has been created it can be examined to gain access to ip and op streams

associated with it

Example (optional)

import javanet

import javaio

class abc

public static void main(String args[])throws Exception

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 11 of 38

int c

Socket s=new socket(ldquointericnetrdquo43)

InputStream in=sgetInputStream()

OutputStream out=sgetOutputStream()

String str=(argslength==0rdquoOsbornecomrdquo)

byte buf[]=strgetBytes()outwrite(buf)

while((c=inread())=-1)

Systemoutprintln(char)c)

sclose()

c) Give sequential steps to use JTabbedPane in an Applet with example

(Steps- 4Marks any one Example- 4Marks)

Ans The general procedure to use a tabbed pane in an applet is

1) Create a JtabbedPane object

2) Call addTab() to add to the pane

3) Repeat step 2 for each tab

4) Add the tabbed pane to the content pane of the applet

Example

import javaxswing

ltapplet code=rdquoJTabbedPaneDemordquo width=350

Height=250gt

ltappletgt

public class JTabbedPaneDemo extends JApplet

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 12 of 38

public void init()

JTabbedPane jtp= new JTabbedPane()

jtpaddTab(ldquocitiesrdquonew citiesPanel())

jtpaddTab(ldquocolorsrdquonew colorsPanel())

jtpaddTab(ldquoFlavourrdquonew flavourPanel())

getContentPane()add(jtp)

class citiespanel extends JPanel

Public citiesPanel()

JButton b1=new Button(ldquoNew Yorkrdquo)

add(b1)

JButton b2=new Button(ldquolondonrdquo)

add(b2)

class colorpanel extends JPanel

Public colorPanel()

JCheckBox cb1=new JCheckBox(ldquoredrdquo)

add(cb1)

JCheckBox cb2=new JCheckBox (ldquogreenrdquo)

add(cb2)

class flavourpanel extends JPanel

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 13 of 38

public flavourPanel()

JComboBox b=new JComboBox()

jcbaddItem(ldquovanillardquo)

jcbaddItem(ldquochocolaterdquo)

add(jcb)

3 Attempt any four of the following Marks 16

a) Example the use of prepared statement with example 4

(Explanation-2 Marks Example-2 Marks)

Ans PrepareStatement ()

The preparedStatement() method creates a PreparedStatement object and returns it as a return

value The Prepared statement object is used to execute dynamic SQL statement against the

databaseA dynamic SQL statement is a statement in which some of the parameters in the

statement are unknown when the statement is created The parameter is placed into the SQL

statement as they are determined by the application When all the parameters are specified for the

SQL statement the dynamic SQL statement will be executed just as a static statement is executed

To create a dynamic SQL statement that takes a first name and last name as parameters use the

following code

try

String sql=rdquoSelect from temployeerdquo + ldquowhere Firstname=rdquo + ldquoand Lastname=rdquo

PreparedStatement p=connectionpreparedStatement(sql)

Catch(SQLException e)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 14 of 38

b) List any four differences between AWT and swing 4

(Any four points ndash 1 Mark each)

Ans

Swing AWT

It uses javaxswing package It uses javaapplet package

It uses JApplet class It uses Applet class

Swing is light weight component AWT is heavy weight component

It does not have add() method to add

control

It has add() method to add control

AWT provides less features than

swing

Swing has variety of component amp

features which is not in AWT

Awt has huge collection of classes amp

interfaces

Swing has bigger collection of classes

amp interfaces than AWT

AWT has predefined formats of

appearance amp behavior of component

Swing provides a facility of different

appearance amp behavior of the same

component

c) List four interfaces in javaxservlet package 4

(Any four points ndash 1 Mark each)

Ans Following are the interfaces in javaxservlet package

1 Servlet All servlets must implement the Servlet interface It declares the init( ) service( )

and destroy( ) methods that are called by the server during the life cycle of a servlet

2 ServletConfig The ServletContextinterface is implemented by the server It enables servlets

to obtain information about their environment

3 ServletContext The ServletContextinterface is implemented by the server It enables

servlets to obtain information about their environment

4 ServletRequest The ServletRequestinterface is implemented by the server It enables a

servlet to obtain information about a client request

5 ServletResponse The ServletResponseinterface is implemented by the server It enables a

servlet to formulate a response for a client

6 SingleThreadModel This interface is used to indicate that only a single thread will execute

the service( ) method of a servlet at a given time It defines no constants and declares no

methods

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 15 of 38

d) Give the use of ImageIcon class with example 4

(Explanation ndash 2 Marks Example- 2 Marks)

Ans In Swing icons are encapsulated by the ImageIconclass which paints an icon from an

image Two of its constructors are shown here

ImageIcon(String filename)

ImageIcon(URL url)

The first form uses the image in the file named filename The second form uses the

image in the resource identified by url

The ImageIconclass implements the Icon interface that declares the methods

As follows

Method Description

intgetIconHeight( ) Returns the height of the iconin pixels

intgetIconWidth( ) Returns the width of the iconin pixels

voidpaintIcon(Component comp Graphics gintx inty)Paints the icon at position x y onthe

graphics context g Additionalinformation about the paintoperation can be provided in comp

Example

import javaawt

import javaxswing

ltapplet code=JLabelDemo width=250 height=150gt

ltappletgt

public class JLabelDemo extends JApplet

public void init()

Get content pane

Container contentPane = getContentPane()

Create an icon

ImageIcon ii = new ImageIcon(francegif)

Create a label

JLabeljl = new JLabel(France ii JLabelCENTER)

Add label to the content pane

contentPaneadd(jl)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 16 of 38

e) Give the use of URL class along with syntax of constructors of URL class 4

(Use - 2 Marks Any two Constructor - 1 Mark each)

Ans The URL provides a reasonably intelligible form to uniquely identify or address information on the

Internet URLs are ubiquitous every browser uses them to identify information on the Web In

fact the Web is really just that same old Internet with all of its resources addressed as URLs plus

HTML

Javas URL class has several constructors One commonly used form specifies the URL with a

string that is identical to what you see displayed in a browser

1 URL(String urlSpecifier)

The next two forms of the constructor allow you to break up the URL into its componentparts

2 URL(String protocolName String hostName intport String path)

3 URL(String protocolName String hostName String path)

Another frequently used constructor allows you to use an existing URL as a referencecontext and

then create a new URL from that context Although this sounds a littlecontorted its really quite

easy and useful

4 URL(URL urlObj String urlSpecifier)

4 A) Attempt any three of the following Marks 12

a) Give the use of following methods of statement interface 4

i) executeQuery( ) ii) execute Update ( )

(Each method ndash 2 Marks)

Ans i) executeQuery()

The executeQuery() method of the statement object enables you to send SQL select statement to

the database and to receive result from the database Executing a query in effect sends a SQL

select statement to the database and returns the appropriate results back in the Resultset object

The executeQuery() method takes a SQL select statement as a parameter and returns a ResultSet

object that contains all the records that match the select statements criteria

ii) executeUpdate()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 17 of 38

The executeUpdate() method of the Statement object enables you to execute SQL update

statements such as delete insert and update The method takes a String containing the SQL update

statement and returns an integers that determines how many records were affected by the SQL

statement

b) Define Layout Manager Describe the use of GridLayout Manager 4

(Layout manager- 2 Marks Use-2 Marks)

Ans Each Container object has a layout manager associated with it A layout manager

is an instance of any class that implements the LayoutManagerinterface The layout

manager is set by the setLayout( ) method If no call to setLayout( ) is made then the

default layout manager is used Whenever a container is resized (or sized for the first

time) the layout manager is used to position each of the components within it

The setLayout( ) method has the following general form

voidsetLayout(LayoutManagerlayoutObj)

GridLayoutManager

GridLayout lays out components in a two-dimensional grid When you instantiate

a GridLayout you define the number of rows and columns The constructors

supported by GridLayoutare shown here

GridLayout( )

GridLayout(intnumRows intnumColumns)

GridLayout(intnumRows intnumColumns inthorz intvert)

c) Explain the use of cookies with example 4

(Explanation - 2 Marks Example - 2 Marks any one)

Ans Cookie is a small piece of information that is passed back and forth in the HTTP request and

response Even though a cookie can be created on the client side using some scripting language

such as JavaScript it is usually created by the server resource such as a Servlet The Cookies sent

by the server when the client requests another page from the same application In Servlet

programming a cookie is represented by a Cookie class in the javaxservlethttp package You can

create a cookie by calling the Cookie class constructor and passing two string objects the name

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 18 of 38

and value of the cookie For instance the following code creates a cookie object called c1The

cookie has the name ldquomyCookierdquo and value of rdquosecretrdquo

Cookie c1=new Cookie(ldquomyCookierdquordquosecretrdquo)

You then can add the cookie to the http response using addCookie method of the

HTTPServletResponse interfaceResponseaddCookie(c1)

Program for Add cookies

import javaio

importjavaxservlet

importjavaxservlethttp

public class AddCookieServlet extends HttpServlet

public void doPost(HttpServletRequest requestHttpServletResponse response)

throwsServletException IOException

Get parameter from HTTP request

String data = requestgetParameter(data)

Create cookie

Cookie cookie = new Cookie(MyCookie data)

Add cookie to HTTP response

responseaddCookie(cookie)

Write output to browser

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgtMyCookie has been set to)

pwprintln(data)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 19 of 38

pwclose()

OR

Program for Get Cookies

import javaio

importjavaxservlet

importjavaxservlethttp

public class GetCookiesServlet extends HttpServlet

public void doGet(HttpServletRequest requestHttpServletResponse response)

throwsServletException IOException

Get cookies from header of HTTP request

Cookie[] cookies = requestgetCookies()

Display these cookies

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgt)

for(inti = 0 iltcookieslength i++)

String name = cookies[i]getName()

String value = cookies[i]getValue()

pwprintln(name = + name +

value = + value)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 20 of 38

pwclose()

d) Give steps to create simple servlet with example 4

(Steps- 2 Marks Any one Example ndash 2 Marks)

Ans Steps 1) Write a java servet code

Steps 2) Compile Servet by setting classpath with servlet-api library

Step 3) Copy the class servlet file in web apps classpath directory

Steps 4) Open the webxml open it and add servlet tag and sevlet mapping tag

Steps 5) Start web server(apche tomcat)

Steps 6) Browse servlet using java compatible browser like IE

Example shows to start create a file named WelcomeServletjava that contains the following

program

import javaio

importjavaxservlet

public class WelcomeServletDemo extends GenericServlet

public void service(ServletRequestrequestServletResponse response) throws

ServletExceptionIOException

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgtWelcome to Servlet)

pwclose()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 21 of 38

B) Attempt any one of the following Marks 6

a) Describe the two ndashtier and three ndashtier database design of JDBC API with neat diagram

(Explanation of Two-tier-2 Marks and Three-tier-2 Marks Diagram ndash 1 Mark each)

Ans Two Tier Architecture

In a two tier model a java application is designed to interact directly with the database

Application functionality is divided into these two layers

1) Application Layer Including the JDBC driver business logic and user interface

2) Database Layer including RDBMS

The interface to the database is handled by the Java Database Connectivity(JDBC) Driver

appropriate to the particularly database management system being accessed The JDBC Driver

passes SQL statements to the database and returns the results of those statements to the

application

A clientserver configuration is the special case of the two tier model where the database is

located on another machine referred to as the server The application runs on the client machine

which is connected to the server over a network Commonly the network is an Intranet using

dedicated database servers to support multiple clients but it can just as easily be the internet

Three Tier Architecture-

In the three tier model the client typically sends requests to an application server forming the

middle tier The application server interprets these requests and formats the necessary SQL

statement to fulfill

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 22 of 38

These requests and sends them to the database The database process the SQL statements and

sends result back to the application server which then sends them to the client

Following are some advantages of Three-tier architecture

1 Performance can be improved by separating the application server and database server

2 Business logic is clearly separated from the database

3 Client application can use a simple protocol such as CGI to access services

The three-tier model show in following fig is a common in web application In this scenario the

client tier is frequently implemented in a browse on a client machine the middle tier is

implemented in a web server with a Servlet engine and the database management system runs on

a dedicated database server

Following are the main components of three tier architecture

1 Client Tier - Typically this is thin presentation layer that may be implemented using a web

browser

2 Middle Tier - This tier handles the business or application logic This may be implemented

using a Servlet engine such as Tomcat or an application server such as JBOSS The JDBC

driver also resides in this layer

3 Data source layer This component includes the RDBMS

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 23 of 38

b) Write servlet which shows how many times user has visited the page in session

(Any Correct Logic ndash4 Marks Syntax ndash 2 Marks)

Ans import javaio

import javaxservlet

import javaxservlethttp

public class Session Travker extends HttpServlet

public void doGet(HttpServletRequest req HttpServletResponse res) throws ServletException

IOException

ressetContentType(ldquotexthtmlrdquo)

PrintWriter out = resgetWriter()

HttpSession session = reqgetSession(true)

Integer count= (Integer)sessiongetValue(ldquotrackercountrdquo)

if(count== null) count=new Interger(1)

else count = new Interger(count intValue() +1)

sessionputValue(ldquotrackercountrdquocount)

outprintln(ldquoltHTMLgtltHEADgtltTITLEgtSession TrackerltTITLEgtltHEADgtrdquo)

outprintln(ldquoltBODYgtltH1gtSession Tracking DemoltH1gtrdquo)

outprintln(ldquoYou have visited this pagerdquo +count +((countintValue() == 1)rdquotimerdquo

ldquotimesrdquo))outprinln(ltPgtrdquo)

outprintln(ldquoltH2gtSesssion dataltH2gtrdquo)

String[] names = sessiongetValueNames()

for(int i=0 ilt nameslength i++)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 24 of 38

outprintln(names[i] + ldquo rdquo + sessiongetvalue(names[i])+ ldquoltBRgtrdquo)

outprintln(ldquoltBODYgtltHTMLgtrdquo)

5 Attempt any two of the following Marks 16

a) Write a program to display all records from Employee table from database using

JDBC

(Assume suitable data for table- Load driver create connection execute Query - 1 Mark

each Display data- 3 Marks Syntax ndash 2 Marks)

Ans import javasql

import javasqlStatement

import javaapplet

import javaawt

public class DisplayTable

public static void main( String args[])

RsultSet rs

Connection conn

try

String s1

ClassforName(sun jdbcodbcJdbcOdbcDriver)

Systemoutprintln(Connecting to a selected database)

String url=rdquojdbcodbcabcrdquo

conn = DriverManagergetConnection(DB_URL USER PASS)

Systemoutprintln(Connected database successfully)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 25 of 38

Systemoutprintln(Creating statement)

stmt = conncreateStatement()

sql = SELECT FROM Employee

ResultSet rs = stmtexecuteQuery(sql)

Tables fields assumed are id first last age

while(rsnext())

int id = rsgetInt(id)

int age = rsgetInt(age)

String first = rsgetString(first)

String last = rsgetString(last)

Systemoutprint(ID + id)

Systemoutprint( Age + age)

Systemoutprint( First + first)

Systemoutprintln( Last + last)

rsclose()

catch(SQLException se)

Handle errors for JDBC

seprintStackTrace()

catch(Exception e)

Handle errors for ClassforName

eprintStackTrace()

finally

finally block used to close resources

try

if(stmt=null)

connclose()

catch(SQLException se)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 26 of 38

b) Define the term

i) Reserved socket ii) proxy server

iii) Datagram iv) URL connection 4

(Each term- 2 Marks)

Ans i) Reserved socket

A socket is one end-point of a two-way communication link between two programs running on

the network Socket classes are used to represent the connection between a client program and a

server program

Reserved socket The socket which are reserved for specific protocols for communication

purpose are known as reseved sockets

TCPIP uses or reserves the lower 1024 ports for specific protocols

Example port number 23 is for Telnet 25 is for smtp 21 is for ftp 13 for daytime 110 for pop3

and so on Protocol decides how a client should interact with the port

ii) Proxy server

A proxy server is a computer that offers a computer network service to allow clients to make

indirect network connections to other network services A client connects to the proxy server

then requests a connection file or other resource available on a different server The proxy

provides the resource either by connecting to the specified server or by serving it from a cache In

some cases the proxy may alter the clients request or the servers response for various purposes

Purposes of the proxy servers

To keep machines behind it anonymous mainly for security

To speed up access to resources (using caching) Web proxies are commonly used to

cache web pages from a web server

To prevent downloading the same content multiple times (and save bandwidth)

To log audit usage eg to provide company employee Internet usage reporting

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 27 of 38

To scan transmitted content for malware before delivery

To scan outbound content eg for data loss prevention

iii) Datagram

Datagrams are bundles of information passed between machines They are somewhat like a hard

throw from a well-trained but blindfolded catcher to the third baseman Once the datagram has

been released to its intended target there is no assurance that it will arrive or even that

someone will be there to catch it Likewise when the datagram is received there is no

assurance that it hasnrsquot been damaged in transit or that whoever sent it is still there to receive a

response

Java implements datagrams on top of the UDP protocol by using two classes

The DatagramPacket object is the data container while the DatagramSocket is the mechanism

used to send or receive the DatagramPackets

iv) URL connection

URLConnection is a general-purpose class for accessing the attributes of a remote resource

Once you make a connection to a remote server you can use URLConnection to inspect the

Properties of the remote object before actually transporting it locally These attributes are

exposed by the HTTP protocol specification and as such only make sense for URL objects

that are using the HTTP protocol

URLConnection defines several methods

int getContentLength( )

String getContentType( )

long getDate( )

long getExpiration( )

String getHeaderField(int idx)

long getLastModified( )

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 28 of 38

c) Write a program to display three text fields and a button below to all an Applet Insert

the integer valuer from three text fields After pressing the button the background colour

of applet will be changed as per the RGB combination of the values given in the text field

(Correct logic - 6 Marks Syntax - 2 Marks)

4

Ans import javaawt

import javaawtevent

import javaapplet

ltapplet code=rdquoClrclassrdquo width=250 heigth=250gtltappletgt

public class Clrextends Applet implements ActionListener

int r g b

TextField t1t2t3

Button b1

Color c1

public void init()

t1= new TextField(5)

t2= new TextField(8)

t3= new TextField(11)

b1 = new Button(ldquo Set Colorrdquo)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 29 of 38

add(t1)

add(t2)

add(t3)

add(b1)

b1addActionListener(this)

public void void paint( )

setBackground(c1)

public void actionPerformed(ActionEvent ae)

r=IntegerparseInt(t1getText())

g=IntegerparseInt(t2getText())

b=IntegerparseInt(t3getText())

c1= new Color(rgb)

repaint()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 30 of 38

6) Attempt any four of the following Marks 16

a) How to check how many fonts are available in the computer system 4

Explain with example

(Explanation -2 Marks Example-2 Marks)

Ans When working with fonts often you need to know which fonts are available on your machine To

ontain this information you can use the getAvailableFontFamilyNames() method defined by the

GraphicsEnvironment classIt is shown here

String[ ] getAvailableFontFamilyNames( )

This method returns an array of string that contains the names of the available font families

Since this methods is members of GraphicsEnvironment you need a GraphicsEnvironment

reference to call itYou can obtain this reference by using the getlocalGrahicsEnvironmet() static

method which is derfined by GraphicsEnvironmentIt is shown here

static GraphicsEnvironment getLocalGraphicsEnvironment( )

Here is an applet that shown how to obtain the names of the available font families

ltapplet code=rdquoAllFontsrdquo width=500 height=100gt

ltappletgt

import javaapplet

import javaawt

public class AllFonts extends Applet

public void paint(Graphics g)

string fonts= ldquo rdquo

stirng allFontsList[]

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 31 of 38

GraphicsEnvironment t = GraphicsEnvironmentgetLocalGraphicsEnvironment()

allFontList = tgetAvailableFontFamilyNames()

for(int i= 0 ilt allFontsListlength i++)

fonts= fonts + allFontList[i] + ldquo rdquo

gdrawString(msg416)

b) Explain following check box class methods with appropriate example 4

i) Void setLable (String str) ii) Boolean getState ( )

(Explanation of each method-1 Marks Example-2 Marks)

Ans

i) void setLable(String str)

This method is used to set the label of check box

ii) Boolean getState()

This method is used to retrieve the current state of a check box It returns the value either true or

false depends on check box is selected or not

Example

Demonstrate check boxes

import javaawt

import javaawtevent

import javaapplet

ltapplet code=CheckboxDemo width=250 height=200gt

ltappletgt

public class CheckboxDemo extends Applet implements ItemListener

String msg =

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 32 of 38

Checkbox winXP winVista solaris mac

public void init()

winXP = new Checkbox(Windows XP null true)

mac = new Checkbox()

macsetLable(ldquoMac OSrdquo)

add(winXP)

add(mac)

winXPaddItemListener(this)

macaddItemListener(this)

public void itemStateChanged(ItemEvent ie)

repaint()

Display current state of the check boxes

public void paint(Graphics g)

msg = Current state

gdrawString(msg 6 80)

msg = Windows XP + winXPgetState()

gdrawString(msg 6 100)

msg = Mac OS + macgetState()

gdrawString(msg 6 120)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 33 of 38

c) Explain the techniques of session tracking management

(Any four techniques with explanation- 1 Mark each)

Ans Session tracking Techniques

1 User Authorization

Users can be authorized to use the web application in different ways Basic concept is that the

user will provide username and password to login to the application Based on that the user can

be identified and the session can be maintained

2 Hidden Fields

ltINPUT TYPE=rdquohiddenrdquo NAME=rdquotechnologyrdquo VALUE=rdquoservletrdquogt

Hidden fields like the above can be inserted in the webpages and information can be sent to the

server for session tracking These fields are not visible directly to the user but can be viewed

using view source option from the browsers This type doesnrsquot need any special configuration

from the browser of server and by default available to use for session tracking This cannot be

used for session tracking when the conversation included static resources lik html pages

3 URL Rewriting

Original URL httpserverportservletServletName

ewritten URL httpserverportservletServletNamesessionid=7456

When a request is made additional parameter is appended with the url In general added

additional parameter will be sessionid or sometimes the userid It will suffice to track the

session This type of session tracking doesnrsquot need any special support from the browser

Disadvantage is implementing this type of session tracking is tedious We need to keep track of

the parameter as a chain link until the conversation completes and also should make sure that

the parameter doesnrsquot clash with other application parameters

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 34 of 38

4 Cookies

Cookies are the mostly used technology for session tracking Cookie is a key value pair of

information sent by the server to the browser This should be saved by the browser in its space

in the client computer Whenever the browser sends a request to that server it sends the cookie

along with it Then the server can identify the client using the cookie

In java following is the source code snippet to create a cookie

Cookie cookie = new Cookie (ldquouserIDrdquo ldquo7456Prime)

resaddCookie(cookie)

5 Session tracking API

Session tracking API is built on top of the first four methods This is inorder to help the

developer to minimize the overhead of session tracking This type of session tracking is

provided by the underlying technology Lets take the java servlet example Then the servlet

container manages the session tracking task and the user need not do it explicitly using the java

servlets This is the best of all methods because all the management and errors related to

session tracking will be taken care of by the container itself

d) Give sequential steps for JTree in swing with example

(Steps- 2 Marks any small Example- 2 Marks)

Ans Steps for JTree

Atree is a component that presents a hierarchical view of data The user has the ability to

expand or collapse individual subtrees in this display Trees are implemented in Swing by

the JTree class

Here are the steps to follow to use a tree

1 Create an instance of JTree

2 Create a JScrollPane and specify the tree as the object to be scrolled

3 Add the tree to the scroll pane

4 Add the scroll pane to the content pane

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 35 of 38

Example

Demonstrate JTree

import javaawt

import javaxswingevent

import javaxswing

import javaxswingtree

ltapplet code=JTreeDemo width=400 height=200gt

ltappletgt

public class JTreeDemo extends JApplet

JTree tree

JLabel jlab

public void init()

try

SwingUtilitiesinvokeAndWait(

new Runnable()

public void run()

makeGUI()

)

catch (Exception exc)

Systemoutprintln(Cant create because of + exc)

private void makeGUI()

Create top node of tree

DefaultMutableTreeNode top = new DefaultMutableTreeNode(Options)

Create subtree of A

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 36 of 38

DefaultMutableTreeNode a = new DefaultMutableTreeNode(A)

topadd(a)

DefaultMutableTreeNode a1 = new DefaultMutableTreeNode(A1)

aadd(a1)

DefaultMutableTreeNode a2 = new DefaultMutableTreeNode(A2)

aadd(a2)

Create subtree of B

DefaultMutableTreeNode b = new DefaultMutableTreeNode(B)

topadd(b)

DefaultMutableTreeNode b1 = new DefaultMutableTreeNode(B1)

badd(b1)

DefaultMutableTreeNode b2 = new DefaultMutableTreeNode(B2)

badd(b2)

DefaultMutableTreeNode b3 = new DefaultMutableTreeNode(B3)

badd(b3)

Create the tree

tree = new JTree(top)

Add the tree to a scroll pane

JScrollPane jsp = new JScrollPane(tree)

Add the scroll pane to the content pane

add(jsp)

Add the label to the content pane

jlab = new JLabel()

add(jlab BorderLayoutSOUTH)

Handle tree selection events

treeaddTreeSelectionListener(new TreeSelectionListener()

public void valueChanged(TreeSelectionEvent tse)

jlabsetText(Selection is + tsegetPath())

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 37 of 38

e) Draw and explain the life cycle of servlet

(Explanation ndash 3 Marks Diagram -1 Marks)

Ans Three methods are central to the life cycle of a servlet

These are init( ) service( ) and destroy( )

They are implemented by every servlet and are invoked at specific times by the server Let

us consider a typical user scenario to understand when these methods are called

First assume that a user enters a Uniform Resource Locator (URL) to a web browser

The browser then generates an HTTP request for this URL This request is then sent to the

appropriate server

Second this HTTP request is received by the web server The server maps this request to

a particular servlet The servlet is dynamically retrieved and loaded into the address space

of the server

Third the server invokes the init( ) method of the servlet This method is invoked only

when the servlet is first loaded into memory It is possible to pass initialization parameters

to the servlet so it may configure itself

Fourth the server invokes the service( ) method of the servlet This method is called to

process the HTTP request You will see that it is possible for the servlet to read data that has

been provided in the HTTP request It may also formulate an HTTP response for the client

The servlet remains in the serverrsquos address space and is available to process any other

HTTP requests received from clients The service( ) method is called for each HTTP request

Finally the server may decide to unload the servlet from its memory The algorithms by

which this determination is made are specific to each server The server calls the destroy( )

method to relinquish any resources such as file handles that are allocated for the servlet

Important data may be saved to a persistent store The memory allocated for the servlet and

its objects can then be garbage collected

A servlet life cycle can be defined as the entire process from its creation till the destruction The

following are the paths followed by a servlet

The servlet is initialized by calling the init () method

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 38 of 38

The servlet calls service() method to process a clients request

The servlet is terminated by calling the destroy() method

Finally servlet is garbage collected by the garbage collector of the JVM

Initialization

(Load Resources)

Services

(Accept Requests)

Destruction

(Unload Resources)

Servlet

Request

Response

Page 5: AJP

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 5 of 38

This category works with ODBC drivers supplied by your database vendor or a third party

To use the bridge you must first have an ODBC driver specifically for you database and

additional software that you need for connectivity

Using ODBC also requires configuring on your system a DNS that represents the target database

Advantages

1) It offers the ability to connect to almost all databases on almost all platforms

2) It may be the only way to gain access to some low and desktop database and application

Disadvantages

1) ODBC driver must also be loaded on the target machine

2) Translation between JDBC and ODBC affects performance

b) Write a program to demonstrate the use of JScrollpane in swing

(Any 1 program- Applet tag-2mark correct logic-4 Marks Synatax-2 Marks)

Ans import javaawt

import javaxswing

ltapplet code=rdquoJScrollPaneDemordquo width=350

Height=250gt

ltappletgt

Public class JscrollPaneDemo extends JApplet

Public void init()

Container contentPane= get ContentPane()

contentPanesetLayout(new BorderLayout())

JPanel jp = new JPanel()

jpsetLayout(new GridLayout(2020))

int b=0

for(int i=0ilt20i++)

jpadd(new JButton(ldquoButtonrdquo+b)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 6 of 38

++b

int v=ScrollPaneConstantsVERTICAL_SCROLLBAR_AS_NEEDED

int h= ScrollPaneConstantsHORIZONTAL_SCROLLBAR_AS_NEEDED

JScrollPane jsp= new JScrollPane(jpvh)

contentPaneadd(jspBorderLayoutCENTER)

2 Attempt any two of the following Marks 16

a) Write an application program making use of menu and menu bar class 8

(Applet tag ndash 1Mark correct logic to add menu and menubar - 5 Marks Synatax-2 Marks)

Ans import javaawt

import javaawtevent

import javaapplet

ltapplet code=rdquo MenuFramerdquo width=350

Height=250gt

ltappletgt

class MenuFrame extends Frame implements ActionListener

String msg=rdquordquo

MenuFrame(String title)

super(title)

MenuBar mbar= new menuBar()

setMentBar(mbar)

Menu file=new Menu(ldquoFilerdquo)

MenuItem item1item2item3item4item5

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 7 of 38

item1= new MenuItem (ldquoNewrdquo)

item2= new MenuItem (ldquoopenrdquo)

item3= new MenuItem (ldquocloserdquo)

item4= new MenuItem (ldquo-rdquo)

item5= new MenuItem (ldquoQuitrdquo)

fileadd(item1)

fileadd(item2)

fileadd(item3)

fileadd(item4)

fileadd(item5)

mbaradd(file)

MenuItem item6item7item8item9

item6= new MenuItem (ldquocutrdquo)

item7= new MenuItem (ldquocopyrdquo)

item8= new MenuItem (ldquopasterdquo)

item9= new MenuItem (ldquo-rdquo)

editadd(item6)

editadd(item7)

editadd(item8)

editadd(item9)

mbaradd(edit)

item1addActionListener(this)

item2addActionListener(this)

item3addActionListener(this)

item4addActionListener(this)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 8 of 38

item5addActionListener(this)

item6addActionListener(this)

item7addActionListener(this)

item8addActionListener(this)

item9addActionListener(this)

Public void paint(Graphics g)

gdrawString(msg10200)

public void actionPerformed(ActionEvent e)

msg= ldquoYou have selected rdquo+ egetActionCommand()

repaint()

public static void main(String args[])

MenuFrame m=new MenuFrame(ldquoMyMenurdquo)

msetVisible(true)

msetSize(100200)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 9 of 38

b) Give the use of Server Socket and Socket class Describe the steps that are 8

required to establish communication between client and server sockets

(Use-2 Marks each class Steps-4 Marks)

Ans Server socket

A Server Socket handles the requests and sends back an appropriate reply The actual tasks that a

server socket must accomplish are implemented by an internal SocketImpl instance A server

socket waits for requests to come in over the network It performs some operation based on that

request and then possibly returns a result to the requester The actual work of the server socket is

performed by an instance of the SocketImpl class An application can change the socket factory

that creates the socket implementation to configure itself to create sockets appropriate to the local

firewall

Client socket

we have used the class named ClientSocketInformationjava that implement the constructor of

the Socket class passing two arguments as hostName and TIME_PORT This program throws an

IOException for the exception handling This exception is thrown to indicate an IO problem of

some sort occurred Here we are going to explore a method to retrieve the host name of the local

system in a very simple way In this way we find out the Local address Local host information

reuseAddress and address of the local system in a very simple manner

Steps to connect

Using TCP socket provides the communication mechanism between two computers A client

program creates a socket at its end of the communication and attempts to connect that socket to a

server

The following is the lists of sequential steps which occur when establishing a TCP connection

between client socket and server socket

1 The server initiates a Server Socket object and mentions which port number communication is

to occur on

2 The server invokes the accept () method of the ServerSocket class This method does the wait

till a client gets connected to the server on the given port

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 10 of 38

After the waiting stages of server a client instantiates a Socket object It also specifies the

server name and port number to which it gets connected

3 The constructor of the Socket class tries to connect the client to the specified server and port

number If the communication is established the client has a Socket object which is capable

of communicating with the server

4 On server side the accept () method returns a reference to a new socket on the server that is

connected to the clientrsquos socket

Once the connection are established communication occur using IO streams Each socket has

both an Outputstream and InputStreams

As we know that the TCP is a two way communication protocol So data can be sent across

both streams at the same time

Two constructors used to create client socket

Socket (String hostnameint port)

Creates a socket connection the localhost to name host and port

Socket(InetAddress ipAddressint port)

Creates a socket using pre existing InetAddress object and a port

A socket can be examined at any time for the address and port information associated with it

InetAddress getInetAddress()

Int getPort()

Int getLocalPort()

Once the socket object has been created it can be examined to gain access to ip and op streams

associated with it

Example (optional)

import javanet

import javaio

class abc

public static void main(String args[])throws Exception

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 11 of 38

int c

Socket s=new socket(ldquointericnetrdquo43)

InputStream in=sgetInputStream()

OutputStream out=sgetOutputStream()

String str=(argslength==0rdquoOsbornecomrdquo)

byte buf[]=strgetBytes()outwrite(buf)

while((c=inread())=-1)

Systemoutprintln(char)c)

sclose()

c) Give sequential steps to use JTabbedPane in an Applet with example

(Steps- 4Marks any one Example- 4Marks)

Ans The general procedure to use a tabbed pane in an applet is

1) Create a JtabbedPane object

2) Call addTab() to add to the pane

3) Repeat step 2 for each tab

4) Add the tabbed pane to the content pane of the applet

Example

import javaxswing

ltapplet code=rdquoJTabbedPaneDemordquo width=350

Height=250gt

ltappletgt

public class JTabbedPaneDemo extends JApplet

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 12 of 38

public void init()

JTabbedPane jtp= new JTabbedPane()

jtpaddTab(ldquocitiesrdquonew citiesPanel())

jtpaddTab(ldquocolorsrdquonew colorsPanel())

jtpaddTab(ldquoFlavourrdquonew flavourPanel())

getContentPane()add(jtp)

class citiespanel extends JPanel

Public citiesPanel()

JButton b1=new Button(ldquoNew Yorkrdquo)

add(b1)

JButton b2=new Button(ldquolondonrdquo)

add(b2)

class colorpanel extends JPanel

Public colorPanel()

JCheckBox cb1=new JCheckBox(ldquoredrdquo)

add(cb1)

JCheckBox cb2=new JCheckBox (ldquogreenrdquo)

add(cb2)

class flavourpanel extends JPanel

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 13 of 38

public flavourPanel()

JComboBox b=new JComboBox()

jcbaddItem(ldquovanillardquo)

jcbaddItem(ldquochocolaterdquo)

add(jcb)

3 Attempt any four of the following Marks 16

a) Example the use of prepared statement with example 4

(Explanation-2 Marks Example-2 Marks)

Ans PrepareStatement ()

The preparedStatement() method creates a PreparedStatement object and returns it as a return

value The Prepared statement object is used to execute dynamic SQL statement against the

databaseA dynamic SQL statement is a statement in which some of the parameters in the

statement are unknown when the statement is created The parameter is placed into the SQL

statement as they are determined by the application When all the parameters are specified for the

SQL statement the dynamic SQL statement will be executed just as a static statement is executed

To create a dynamic SQL statement that takes a first name and last name as parameters use the

following code

try

String sql=rdquoSelect from temployeerdquo + ldquowhere Firstname=rdquo + ldquoand Lastname=rdquo

PreparedStatement p=connectionpreparedStatement(sql)

Catch(SQLException e)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 14 of 38

b) List any four differences between AWT and swing 4

(Any four points ndash 1 Mark each)

Ans

Swing AWT

It uses javaxswing package It uses javaapplet package

It uses JApplet class It uses Applet class

Swing is light weight component AWT is heavy weight component

It does not have add() method to add

control

It has add() method to add control

AWT provides less features than

swing

Swing has variety of component amp

features which is not in AWT

Awt has huge collection of classes amp

interfaces

Swing has bigger collection of classes

amp interfaces than AWT

AWT has predefined formats of

appearance amp behavior of component

Swing provides a facility of different

appearance amp behavior of the same

component

c) List four interfaces in javaxservlet package 4

(Any four points ndash 1 Mark each)

Ans Following are the interfaces in javaxservlet package

1 Servlet All servlets must implement the Servlet interface It declares the init( ) service( )

and destroy( ) methods that are called by the server during the life cycle of a servlet

2 ServletConfig The ServletContextinterface is implemented by the server It enables servlets

to obtain information about their environment

3 ServletContext The ServletContextinterface is implemented by the server It enables

servlets to obtain information about their environment

4 ServletRequest The ServletRequestinterface is implemented by the server It enables a

servlet to obtain information about a client request

5 ServletResponse The ServletResponseinterface is implemented by the server It enables a

servlet to formulate a response for a client

6 SingleThreadModel This interface is used to indicate that only a single thread will execute

the service( ) method of a servlet at a given time It defines no constants and declares no

methods

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 15 of 38

d) Give the use of ImageIcon class with example 4

(Explanation ndash 2 Marks Example- 2 Marks)

Ans In Swing icons are encapsulated by the ImageIconclass which paints an icon from an

image Two of its constructors are shown here

ImageIcon(String filename)

ImageIcon(URL url)

The first form uses the image in the file named filename The second form uses the

image in the resource identified by url

The ImageIconclass implements the Icon interface that declares the methods

As follows

Method Description

intgetIconHeight( ) Returns the height of the iconin pixels

intgetIconWidth( ) Returns the width of the iconin pixels

voidpaintIcon(Component comp Graphics gintx inty)Paints the icon at position x y onthe

graphics context g Additionalinformation about the paintoperation can be provided in comp

Example

import javaawt

import javaxswing

ltapplet code=JLabelDemo width=250 height=150gt

ltappletgt

public class JLabelDemo extends JApplet

public void init()

Get content pane

Container contentPane = getContentPane()

Create an icon

ImageIcon ii = new ImageIcon(francegif)

Create a label

JLabeljl = new JLabel(France ii JLabelCENTER)

Add label to the content pane

contentPaneadd(jl)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 16 of 38

e) Give the use of URL class along with syntax of constructors of URL class 4

(Use - 2 Marks Any two Constructor - 1 Mark each)

Ans The URL provides a reasonably intelligible form to uniquely identify or address information on the

Internet URLs are ubiquitous every browser uses them to identify information on the Web In

fact the Web is really just that same old Internet with all of its resources addressed as URLs plus

HTML

Javas URL class has several constructors One commonly used form specifies the URL with a

string that is identical to what you see displayed in a browser

1 URL(String urlSpecifier)

The next two forms of the constructor allow you to break up the URL into its componentparts

2 URL(String protocolName String hostName intport String path)

3 URL(String protocolName String hostName String path)

Another frequently used constructor allows you to use an existing URL as a referencecontext and

then create a new URL from that context Although this sounds a littlecontorted its really quite

easy and useful

4 URL(URL urlObj String urlSpecifier)

4 A) Attempt any three of the following Marks 12

a) Give the use of following methods of statement interface 4

i) executeQuery( ) ii) execute Update ( )

(Each method ndash 2 Marks)

Ans i) executeQuery()

The executeQuery() method of the statement object enables you to send SQL select statement to

the database and to receive result from the database Executing a query in effect sends a SQL

select statement to the database and returns the appropriate results back in the Resultset object

The executeQuery() method takes a SQL select statement as a parameter and returns a ResultSet

object that contains all the records that match the select statements criteria

ii) executeUpdate()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 17 of 38

The executeUpdate() method of the Statement object enables you to execute SQL update

statements such as delete insert and update The method takes a String containing the SQL update

statement and returns an integers that determines how many records were affected by the SQL

statement

b) Define Layout Manager Describe the use of GridLayout Manager 4

(Layout manager- 2 Marks Use-2 Marks)

Ans Each Container object has a layout manager associated with it A layout manager

is an instance of any class that implements the LayoutManagerinterface The layout

manager is set by the setLayout( ) method If no call to setLayout( ) is made then the

default layout manager is used Whenever a container is resized (or sized for the first

time) the layout manager is used to position each of the components within it

The setLayout( ) method has the following general form

voidsetLayout(LayoutManagerlayoutObj)

GridLayoutManager

GridLayout lays out components in a two-dimensional grid When you instantiate

a GridLayout you define the number of rows and columns The constructors

supported by GridLayoutare shown here

GridLayout( )

GridLayout(intnumRows intnumColumns)

GridLayout(intnumRows intnumColumns inthorz intvert)

c) Explain the use of cookies with example 4

(Explanation - 2 Marks Example - 2 Marks any one)

Ans Cookie is a small piece of information that is passed back and forth in the HTTP request and

response Even though a cookie can be created on the client side using some scripting language

such as JavaScript it is usually created by the server resource such as a Servlet The Cookies sent

by the server when the client requests another page from the same application In Servlet

programming a cookie is represented by a Cookie class in the javaxservlethttp package You can

create a cookie by calling the Cookie class constructor and passing two string objects the name

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 18 of 38

and value of the cookie For instance the following code creates a cookie object called c1The

cookie has the name ldquomyCookierdquo and value of rdquosecretrdquo

Cookie c1=new Cookie(ldquomyCookierdquordquosecretrdquo)

You then can add the cookie to the http response using addCookie method of the

HTTPServletResponse interfaceResponseaddCookie(c1)

Program for Add cookies

import javaio

importjavaxservlet

importjavaxservlethttp

public class AddCookieServlet extends HttpServlet

public void doPost(HttpServletRequest requestHttpServletResponse response)

throwsServletException IOException

Get parameter from HTTP request

String data = requestgetParameter(data)

Create cookie

Cookie cookie = new Cookie(MyCookie data)

Add cookie to HTTP response

responseaddCookie(cookie)

Write output to browser

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgtMyCookie has been set to)

pwprintln(data)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 19 of 38

pwclose()

OR

Program for Get Cookies

import javaio

importjavaxservlet

importjavaxservlethttp

public class GetCookiesServlet extends HttpServlet

public void doGet(HttpServletRequest requestHttpServletResponse response)

throwsServletException IOException

Get cookies from header of HTTP request

Cookie[] cookies = requestgetCookies()

Display these cookies

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgt)

for(inti = 0 iltcookieslength i++)

String name = cookies[i]getName()

String value = cookies[i]getValue()

pwprintln(name = + name +

value = + value)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 20 of 38

pwclose()

d) Give steps to create simple servlet with example 4

(Steps- 2 Marks Any one Example ndash 2 Marks)

Ans Steps 1) Write a java servet code

Steps 2) Compile Servet by setting classpath with servlet-api library

Step 3) Copy the class servlet file in web apps classpath directory

Steps 4) Open the webxml open it and add servlet tag and sevlet mapping tag

Steps 5) Start web server(apche tomcat)

Steps 6) Browse servlet using java compatible browser like IE

Example shows to start create a file named WelcomeServletjava that contains the following

program

import javaio

importjavaxservlet

public class WelcomeServletDemo extends GenericServlet

public void service(ServletRequestrequestServletResponse response) throws

ServletExceptionIOException

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgtWelcome to Servlet)

pwclose()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 21 of 38

B) Attempt any one of the following Marks 6

a) Describe the two ndashtier and three ndashtier database design of JDBC API with neat diagram

(Explanation of Two-tier-2 Marks and Three-tier-2 Marks Diagram ndash 1 Mark each)

Ans Two Tier Architecture

In a two tier model a java application is designed to interact directly with the database

Application functionality is divided into these two layers

1) Application Layer Including the JDBC driver business logic and user interface

2) Database Layer including RDBMS

The interface to the database is handled by the Java Database Connectivity(JDBC) Driver

appropriate to the particularly database management system being accessed The JDBC Driver

passes SQL statements to the database and returns the results of those statements to the

application

A clientserver configuration is the special case of the two tier model where the database is

located on another machine referred to as the server The application runs on the client machine

which is connected to the server over a network Commonly the network is an Intranet using

dedicated database servers to support multiple clients but it can just as easily be the internet

Three Tier Architecture-

In the three tier model the client typically sends requests to an application server forming the

middle tier The application server interprets these requests and formats the necessary SQL

statement to fulfill

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 22 of 38

These requests and sends them to the database The database process the SQL statements and

sends result back to the application server which then sends them to the client

Following are some advantages of Three-tier architecture

1 Performance can be improved by separating the application server and database server

2 Business logic is clearly separated from the database

3 Client application can use a simple protocol such as CGI to access services

The three-tier model show in following fig is a common in web application In this scenario the

client tier is frequently implemented in a browse on a client machine the middle tier is

implemented in a web server with a Servlet engine and the database management system runs on

a dedicated database server

Following are the main components of three tier architecture

1 Client Tier - Typically this is thin presentation layer that may be implemented using a web

browser

2 Middle Tier - This tier handles the business or application logic This may be implemented

using a Servlet engine such as Tomcat or an application server such as JBOSS The JDBC

driver also resides in this layer

3 Data source layer This component includes the RDBMS

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 23 of 38

b) Write servlet which shows how many times user has visited the page in session

(Any Correct Logic ndash4 Marks Syntax ndash 2 Marks)

Ans import javaio

import javaxservlet

import javaxservlethttp

public class Session Travker extends HttpServlet

public void doGet(HttpServletRequest req HttpServletResponse res) throws ServletException

IOException

ressetContentType(ldquotexthtmlrdquo)

PrintWriter out = resgetWriter()

HttpSession session = reqgetSession(true)

Integer count= (Integer)sessiongetValue(ldquotrackercountrdquo)

if(count== null) count=new Interger(1)

else count = new Interger(count intValue() +1)

sessionputValue(ldquotrackercountrdquocount)

outprintln(ldquoltHTMLgtltHEADgtltTITLEgtSession TrackerltTITLEgtltHEADgtrdquo)

outprintln(ldquoltBODYgtltH1gtSession Tracking DemoltH1gtrdquo)

outprintln(ldquoYou have visited this pagerdquo +count +((countintValue() == 1)rdquotimerdquo

ldquotimesrdquo))outprinln(ltPgtrdquo)

outprintln(ldquoltH2gtSesssion dataltH2gtrdquo)

String[] names = sessiongetValueNames()

for(int i=0 ilt nameslength i++)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 24 of 38

outprintln(names[i] + ldquo rdquo + sessiongetvalue(names[i])+ ldquoltBRgtrdquo)

outprintln(ldquoltBODYgtltHTMLgtrdquo)

5 Attempt any two of the following Marks 16

a) Write a program to display all records from Employee table from database using

JDBC

(Assume suitable data for table- Load driver create connection execute Query - 1 Mark

each Display data- 3 Marks Syntax ndash 2 Marks)

Ans import javasql

import javasqlStatement

import javaapplet

import javaawt

public class DisplayTable

public static void main( String args[])

RsultSet rs

Connection conn

try

String s1

ClassforName(sun jdbcodbcJdbcOdbcDriver)

Systemoutprintln(Connecting to a selected database)

String url=rdquojdbcodbcabcrdquo

conn = DriverManagergetConnection(DB_URL USER PASS)

Systemoutprintln(Connected database successfully)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 25 of 38

Systemoutprintln(Creating statement)

stmt = conncreateStatement()

sql = SELECT FROM Employee

ResultSet rs = stmtexecuteQuery(sql)

Tables fields assumed are id first last age

while(rsnext())

int id = rsgetInt(id)

int age = rsgetInt(age)

String first = rsgetString(first)

String last = rsgetString(last)

Systemoutprint(ID + id)

Systemoutprint( Age + age)

Systemoutprint( First + first)

Systemoutprintln( Last + last)

rsclose()

catch(SQLException se)

Handle errors for JDBC

seprintStackTrace()

catch(Exception e)

Handle errors for ClassforName

eprintStackTrace()

finally

finally block used to close resources

try

if(stmt=null)

connclose()

catch(SQLException se)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 26 of 38

b) Define the term

i) Reserved socket ii) proxy server

iii) Datagram iv) URL connection 4

(Each term- 2 Marks)

Ans i) Reserved socket

A socket is one end-point of a two-way communication link between two programs running on

the network Socket classes are used to represent the connection between a client program and a

server program

Reserved socket The socket which are reserved for specific protocols for communication

purpose are known as reseved sockets

TCPIP uses or reserves the lower 1024 ports for specific protocols

Example port number 23 is for Telnet 25 is for smtp 21 is for ftp 13 for daytime 110 for pop3

and so on Protocol decides how a client should interact with the port

ii) Proxy server

A proxy server is a computer that offers a computer network service to allow clients to make

indirect network connections to other network services A client connects to the proxy server

then requests a connection file or other resource available on a different server The proxy

provides the resource either by connecting to the specified server or by serving it from a cache In

some cases the proxy may alter the clients request or the servers response for various purposes

Purposes of the proxy servers

To keep machines behind it anonymous mainly for security

To speed up access to resources (using caching) Web proxies are commonly used to

cache web pages from a web server

To prevent downloading the same content multiple times (and save bandwidth)

To log audit usage eg to provide company employee Internet usage reporting

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 27 of 38

To scan transmitted content for malware before delivery

To scan outbound content eg for data loss prevention

iii) Datagram

Datagrams are bundles of information passed between machines They are somewhat like a hard

throw from a well-trained but blindfolded catcher to the third baseman Once the datagram has

been released to its intended target there is no assurance that it will arrive or even that

someone will be there to catch it Likewise when the datagram is received there is no

assurance that it hasnrsquot been damaged in transit or that whoever sent it is still there to receive a

response

Java implements datagrams on top of the UDP protocol by using two classes

The DatagramPacket object is the data container while the DatagramSocket is the mechanism

used to send or receive the DatagramPackets

iv) URL connection

URLConnection is a general-purpose class for accessing the attributes of a remote resource

Once you make a connection to a remote server you can use URLConnection to inspect the

Properties of the remote object before actually transporting it locally These attributes are

exposed by the HTTP protocol specification and as such only make sense for URL objects

that are using the HTTP protocol

URLConnection defines several methods

int getContentLength( )

String getContentType( )

long getDate( )

long getExpiration( )

String getHeaderField(int idx)

long getLastModified( )

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 28 of 38

c) Write a program to display three text fields and a button below to all an Applet Insert

the integer valuer from three text fields After pressing the button the background colour

of applet will be changed as per the RGB combination of the values given in the text field

(Correct logic - 6 Marks Syntax - 2 Marks)

4

Ans import javaawt

import javaawtevent

import javaapplet

ltapplet code=rdquoClrclassrdquo width=250 heigth=250gtltappletgt

public class Clrextends Applet implements ActionListener

int r g b

TextField t1t2t3

Button b1

Color c1

public void init()

t1= new TextField(5)

t2= new TextField(8)

t3= new TextField(11)

b1 = new Button(ldquo Set Colorrdquo)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 29 of 38

add(t1)

add(t2)

add(t3)

add(b1)

b1addActionListener(this)

public void void paint( )

setBackground(c1)

public void actionPerformed(ActionEvent ae)

r=IntegerparseInt(t1getText())

g=IntegerparseInt(t2getText())

b=IntegerparseInt(t3getText())

c1= new Color(rgb)

repaint()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 30 of 38

6) Attempt any four of the following Marks 16

a) How to check how many fonts are available in the computer system 4

Explain with example

(Explanation -2 Marks Example-2 Marks)

Ans When working with fonts often you need to know which fonts are available on your machine To

ontain this information you can use the getAvailableFontFamilyNames() method defined by the

GraphicsEnvironment classIt is shown here

String[ ] getAvailableFontFamilyNames( )

This method returns an array of string that contains the names of the available font families

Since this methods is members of GraphicsEnvironment you need a GraphicsEnvironment

reference to call itYou can obtain this reference by using the getlocalGrahicsEnvironmet() static

method which is derfined by GraphicsEnvironmentIt is shown here

static GraphicsEnvironment getLocalGraphicsEnvironment( )

Here is an applet that shown how to obtain the names of the available font families

ltapplet code=rdquoAllFontsrdquo width=500 height=100gt

ltappletgt

import javaapplet

import javaawt

public class AllFonts extends Applet

public void paint(Graphics g)

string fonts= ldquo rdquo

stirng allFontsList[]

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 31 of 38

GraphicsEnvironment t = GraphicsEnvironmentgetLocalGraphicsEnvironment()

allFontList = tgetAvailableFontFamilyNames()

for(int i= 0 ilt allFontsListlength i++)

fonts= fonts + allFontList[i] + ldquo rdquo

gdrawString(msg416)

b) Explain following check box class methods with appropriate example 4

i) Void setLable (String str) ii) Boolean getState ( )

(Explanation of each method-1 Marks Example-2 Marks)

Ans

i) void setLable(String str)

This method is used to set the label of check box

ii) Boolean getState()

This method is used to retrieve the current state of a check box It returns the value either true or

false depends on check box is selected or not

Example

Demonstrate check boxes

import javaawt

import javaawtevent

import javaapplet

ltapplet code=CheckboxDemo width=250 height=200gt

ltappletgt

public class CheckboxDemo extends Applet implements ItemListener

String msg =

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 32 of 38

Checkbox winXP winVista solaris mac

public void init()

winXP = new Checkbox(Windows XP null true)

mac = new Checkbox()

macsetLable(ldquoMac OSrdquo)

add(winXP)

add(mac)

winXPaddItemListener(this)

macaddItemListener(this)

public void itemStateChanged(ItemEvent ie)

repaint()

Display current state of the check boxes

public void paint(Graphics g)

msg = Current state

gdrawString(msg 6 80)

msg = Windows XP + winXPgetState()

gdrawString(msg 6 100)

msg = Mac OS + macgetState()

gdrawString(msg 6 120)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 33 of 38

c) Explain the techniques of session tracking management

(Any four techniques with explanation- 1 Mark each)

Ans Session tracking Techniques

1 User Authorization

Users can be authorized to use the web application in different ways Basic concept is that the

user will provide username and password to login to the application Based on that the user can

be identified and the session can be maintained

2 Hidden Fields

ltINPUT TYPE=rdquohiddenrdquo NAME=rdquotechnologyrdquo VALUE=rdquoservletrdquogt

Hidden fields like the above can be inserted in the webpages and information can be sent to the

server for session tracking These fields are not visible directly to the user but can be viewed

using view source option from the browsers This type doesnrsquot need any special configuration

from the browser of server and by default available to use for session tracking This cannot be

used for session tracking when the conversation included static resources lik html pages

3 URL Rewriting

Original URL httpserverportservletServletName

ewritten URL httpserverportservletServletNamesessionid=7456

When a request is made additional parameter is appended with the url In general added

additional parameter will be sessionid or sometimes the userid It will suffice to track the

session This type of session tracking doesnrsquot need any special support from the browser

Disadvantage is implementing this type of session tracking is tedious We need to keep track of

the parameter as a chain link until the conversation completes and also should make sure that

the parameter doesnrsquot clash with other application parameters

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 34 of 38

4 Cookies

Cookies are the mostly used technology for session tracking Cookie is a key value pair of

information sent by the server to the browser This should be saved by the browser in its space

in the client computer Whenever the browser sends a request to that server it sends the cookie

along with it Then the server can identify the client using the cookie

In java following is the source code snippet to create a cookie

Cookie cookie = new Cookie (ldquouserIDrdquo ldquo7456Prime)

resaddCookie(cookie)

5 Session tracking API

Session tracking API is built on top of the first four methods This is inorder to help the

developer to minimize the overhead of session tracking This type of session tracking is

provided by the underlying technology Lets take the java servlet example Then the servlet

container manages the session tracking task and the user need not do it explicitly using the java

servlets This is the best of all methods because all the management and errors related to

session tracking will be taken care of by the container itself

d) Give sequential steps for JTree in swing with example

(Steps- 2 Marks any small Example- 2 Marks)

Ans Steps for JTree

Atree is a component that presents a hierarchical view of data The user has the ability to

expand or collapse individual subtrees in this display Trees are implemented in Swing by

the JTree class

Here are the steps to follow to use a tree

1 Create an instance of JTree

2 Create a JScrollPane and specify the tree as the object to be scrolled

3 Add the tree to the scroll pane

4 Add the scroll pane to the content pane

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 35 of 38

Example

Demonstrate JTree

import javaawt

import javaxswingevent

import javaxswing

import javaxswingtree

ltapplet code=JTreeDemo width=400 height=200gt

ltappletgt

public class JTreeDemo extends JApplet

JTree tree

JLabel jlab

public void init()

try

SwingUtilitiesinvokeAndWait(

new Runnable()

public void run()

makeGUI()

)

catch (Exception exc)

Systemoutprintln(Cant create because of + exc)

private void makeGUI()

Create top node of tree

DefaultMutableTreeNode top = new DefaultMutableTreeNode(Options)

Create subtree of A

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 36 of 38

DefaultMutableTreeNode a = new DefaultMutableTreeNode(A)

topadd(a)

DefaultMutableTreeNode a1 = new DefaultMutableTreeNode(A1)

aadd(a1)

DefaultMutableTreeNode a2 = new DefaultMutableTreeNode(A2)

aadd(a2)

Create subtree of B

DefaultMutableTreeNode b = new DefaultMutableTreeNode(B)

topadd(b)

DefaultMutableTreeNode b1 = new DefaultMutableTreeNode(B1)

badd(b1)

DefaultMutableTreeNode b2 = new DefaultMutableTreeNode(B2)

badd(b2)

DefaultMutableTreeNode b3 = new DefaultMutableTreeNode(B3)

badd(b3)

Create the tree

tree = new JTree(top)

Add the tree to a scroll pane

JScrollPane jsp = new JScrollPane(tree)

Add the scroll pane to the content pane

add(jsp)

Add the label to the content pane

jlab = new JLabel()

add(jlab BorderLayoutSOUTH)

Handle tree selection events

treeaddTreeSelectionListener(new TreeSelectionListener()

public void valueChanged(TreeSelectionEvent tse)

jlabsetText(Selection is + tsegetPath())

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 37 of 38

e) Draw and explain the life cycle of servlet

(Explanation ndash 3 Marks Diagram -1 Marks)

Ans Three methods are central to the life cycle of a servlet

These are init( ) service( ) and destroy( )

They are implemented by every servlet and are invoked at specific times by the server Let

us consider a typical user scenario to understand when these methods are called

First assume that a user enters a Uniform Resource Locator (URL) to a web browser

The browser then generates an HTTP request for this URL This request is then sent to the

appropriate server

Second this HTTP request is received by the web server The server maps this request to

a particular servlet The servlet is dynamically retrieved and loaded into the address space

of the server

Third the server invokes the init( ) method of the servlet This method is invoked only

when the servlet is first loaded into memory It is possible to pass initialization parameters

to the servlet so it may configure itself

Fourth the server invokes the service( ) method of the servlet This method is called to

process the HTTP request You will see that it is possible for the servlet to read data that has

been provided in the HTTP request It may also formulate an HTTP response for the client

The servlet remains in the serverrsquos address space and is available to process any other

HTTP requests received from clients The service( ) method is called for each HTTP request

Finally the server may decide to unload the servlet from its memory The algorithms by

which this determination is made are specific to each server The server calls the destroy( )

method to relinquish any resources such as file handles that are allocated for the servlet

Important data may be saved to a persistent store The memory allocated for the servlet and

its objects can then be garbage collected

A servlet life cycle can be defined as the entire process from its creation till the destruction The

following are the paths followed by a servlet

The servlet is initialized by calling the init () method

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 38 of 38

The servlet calls service() method to process a clients request

The servlet is terminated by calling the destroy() method

Finally servlet is garbage collected by the garbage collector of the JVM

Initialization

(Load Resources)

Services

(Accept Requests)

Destruction

(Unload Resources)

Servlet

Request

Response

Page 6: AJP

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 6 of 38

++b

int v=ScrollPaneConstantsVERTICAL_SCROLLBAR_AS_NEEDED

int h= ScrollPaneConstantsHORIZONTAL_SCROLLBAR_AS_NEEDED

JScrollPane jsp= new JScrollPane(jpvh)

contentPaneadd(jspBorderLayoutCENTER)

2 Attempt any two of the following Marks 16

a) Write an application program making use of menu and menu bar class 8

(Applet tag ndash 1Mark correct logic to add menu and menubar - 5 Marks Synatax-2 Marks)

Ans import javaawt

import javaawtevent

import javaapplet

ltapplet code=rdquo MenuFramerdquo width=350

Height=250gt

ltappletgt

class MenuFrame extends Frame implements ActionListener

String msg=rdquordquo

MenuFrame(String title)

super(title)

MenuBar mbar= new menuBar()

setMentBar(mbar)

Menu file=new Menu(ldquoFilerdquo)

MenuItem item1item2item3item4item5

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 7 of 38

item1= new MenuItem (ldquoNewrdquo)

item2= new MenuItem (ldquoopenrdquo)

item3= new MenuItem (ldquocloserdquo)

item4= new MenuItem (ldquo-rdquo)

item5= new MenuItem (ldquoQuitrdquo)

fileadd(item1)

fileadd(item2)

fileadd(item3)

fileadd(item4)

fileadd(item5)

mbaradd(file)

MenuItem item6item7item8item9

item6= new MenuItem (ldquocutrdquo)

item7= new MenuItem (ldquocopyrdquo)

item8= new MenuItem (ldquopasterdquo)

item9= new MenuItem (ldquo-rdquo)

editadd(item6)

editadd(item7)

editadd(item8)

editadd(item9)

mbaradd(edit)

item1addActionListener(this)

item2addActionListener(this)

item3addActionListener(this)

item4addActionListener(this)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 8 of 38

item5addActionListener(this)

item6addActionListener(this)

item7addActionListener(this)

item8addActionListener(this)

item9addActionListener(this)

Public void paint(Graphics g)

gdrawString(msg10200)

public void actionPerformed(ActionEvent e)

msg= ldquoYou have selected rdquo+ egetActionCommand()

repaint()

public static void main(String args[])

MenuFrame m=new MenuFrame(ldquoMyMenurdquo)

msetVisible(true)

msetSize(100200)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 9 of 38

b) Give the use of Server Socket and Socket class Describe the steps that are 8

required to establish communication between client and server sockets

(Use-2 Marks each class Steps-4 Marks)

Ans Server socket

A Server Socket handles the requests and sends back an appropriate reply The actual tasks that a

server socket must accomplish are implemented by an internal SocketImpl instance A server

socket waits for requests to come in over the network It performs some operation based on that

request and then possibly returns a result to the requester The actual work of the server socket is

performed by an instance of the SocketImpl class An application can change the socket factory

that creates the socket implementation to configure itself to create sockets appropriate to the local

firewall

Client socket

we have used the class named ClientSocketInformationjava that implement the constructor of

the Socket class passing two arguments as hostName and TIME_PORT This program throws an

IOException for the exception handling This exception is thrown to indicate an IO problem of

some sort occurred Here we are going to explore a method to retrieve the host name of the local

system in a very simple way In this way we find out the Local address Local host information

reuseAddress and address of the local system in a very simple manner

Steps to connect

Using TCP socket provides the communication mechanism between two computers A client

program creates a socket at its end of the communication and attempts to connect that socket to a

server

The following is the lists of sequential steps which occur when establishing a TCP connection

between client socket and server socket

1 The server initiates a Server Socket object and mentions which port number communication is

to occur on

2 The server invokes the accept () method of the ServerSocket class This method does the wait

till a client gets connected to the server on the given port

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 10 of 38

After the waiting stages of server a client instantiates a Socket object It also specifies the

server name and port number to which it gets connected

3 The constructor of the Socket class tries to connect the client to the specified server and port

number If the communication is established the client has a Socket object which is capable

of communicating with the server

4 On server side the accept () method returns a reference to a new socket on the server that is

connected to the clientrsquos socket

Once the connection are established communication occur using IO streams Each socket has

both an Outputstream and InputStreams

As we know that the TCP is a two way communication protocol So data can be sent across

both streams at the same time

Two constructors used to create client socket

Socket (String hostnameint port)

Creates a socket connection the localhost to name host and port

Socket(InetAddress ipAddressint port)

Creates a socket using pre existing InetAddress object and a port

A socket can be examined at any time for the address and port information associated with it

InetAddress getInetAddress()

Int getPort()

Int getLocalPort()

Once the socket object has been created it can be examined to gain access to ip and op streams

associated with it

Example (optional)

import javanet

import javaio

class abc

public static void main(String args[])throws Exception

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 11 of 38

int c

Socket s=new socket(ldquointericnetrdquo43)

InputStream in=sgetInputStream()

OutputStream out=sgetOutputStream()

String str=(argslength==0rdquoOsbornecomrdquo)

byte buf[]=strgetBytes()outwrite(buf)

while((c=inread())=-1)

Systemoutprintln(char)c)

sclose()

c) Give sequential steps to use JTabbedPane in an Applet with example

(Steps- 4Marks any one Example- 4Marks)

Ans The general procedure to use a tabbed pane in an applet is

1) Create a JtabbedPane object

2) Call addTab() to add to the pane

3) Repeat step 2 for each tab

4) Add the tabbed pane to the content pane of the applet

Example

import javaxswing

ltapplet code=rdquoJTabbedPaneDemordquo width=350

Height=250gt

ltappletgt

public class JTabbedPaneDemo extends JApplet

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 12 of 38

public void init()

JTabbedPane jtp= new JTabbedPane()

jtpaddTab(ldquocitiesrdquonew citiesPanel())

jtpaddTab(ldquocolorsrdquonew colorsPanel())

jtpaddTab(ldquoFlavourrdquonew flavourPanel())

getContentPane()add(jtp)

class citiespanel extends JPanel

Public citiesPanel()

JButton b1=new Button(ldquoNew Yorkrdquo)

add(b1)

JButton b2=new Button(ldquolondonrdquo)

add(b2)

class colorpanel extends JPanel

Public colorPanel()

JCheckBox cb1=new JCheckBox(ldquoredrdquo)

add(cb1)

JCheckBox cb2=new JCheckBox (ldquogreenrdquo)

add(cb2)

class flavourpanel extends JPanel

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 13 of 38

public flavourPanel()

JComboBox b=new JComboBox()

jcbaddItem(ldquovanillardquo)

jcbaddItem(ldquochocolaterdquo)

add(jcb)

3 Attempt any four of the following Marks 16

a) Example the use of prepared statement with example 4

(Explanation-2 Marks Example-2 Marks)

Ans PrepareStatement ()

The preparedStatement() method creates a PreparedStatement object and returns it as a return

value The Prepared statement object is used to execute dynamic SQL statement against the

databaseA dynamic SQL statement is a statement in which some of the parameters in the

statement are unknown when the statement is created The parameter is placed into the SQL

statement as they are determined by the application When all the parameters are specified for the

SQL statement the dynamic SQL statement will be executed just as a static statement is executed

To create a dynamic SQL statement that takes a first name and last name as parameters use the

following code

try

String sql=rdquoSelect from temployeerdquo + ldquowhere Firstname=rdquo + ldquoand Lastname=rdquo

PreparedStatement p=connectionpreparedStatement(sql)

Catch(SQLException e)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 14 of 38

b) List any four differences between AWT and swing 4

(Any four points ndash 1 Mark each)

Ans

Swing AWT

It uses javaxswing package It uses javaapplet package

It uses JApplet class It uses Applet class

Swing is light weight component AWT is heavy weight component

It does not have add() method to add

control

It has add() method to add control

AWT provides less features than

swing

Swing has variety of component amp

features which is not in AWT

Awt has huge collection of classes amp

interfaces

Swing has bigger collection of classes

amp interfaces than AWT

AWT has predefined formats of

appearance amp behavior of component

Swing provides a facility of different

appearance amp behavior of the same

component

c) List four interfaces in javaxservlet package 4

(Any four points ndash 1 Mark each)

Ans Following are the interfaces in javaxservlet package

1 Servlet All servlets must implement the Servlet interface It declares the init( ) service( )

and destroy( ) methods that are called by the server during the life cycle of a servlet

2 ServletConfig The ServletContextinterface is implemented by the server It enables servlets

to obtain information about their environment

3 ServletContext The ServletContextinterface is implemented by the server It enables

servlets to obtain information about their environment

4 ServletRequest The ServletRequestinterface is implemented by the server It enables a

servlet to obtain information about a client request

5 ServletResponse The ServletResponseinterface is implemented by the server It enables a

servlet to formulate a response for a client

6 SingleThreadModel This interface is used to indicate that only a single thread will execute

the service( ) method of a servlet at a given time It defines no constants and declares no

methods

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 15 of 38

d) Give the use of ImageIcon class with example 4

(Explanation ndash 2 Marks Example- 2 Marks)

Ans In Swing icons are encapsulated by the ImageIconclass which paints an icon from an

image Two of its constructors are shown here

ImageIcon(String filename)

ImageIcon(URL url)

The first form uses the image in the file named filename The second form uses the

image in the resource identified by url

The ImageIconclass implements the Icon interface that declares the methods

As follows

Method Description

intgetIconHeight( ) Returns the height of the iconin pixels

intgetIconWidth( ) Returns the width of the iconin pixels

voidpaintIcon(Component comp Graphics gintx inty)Paints the icon at position x y onthe

graphics context g Additionalinformation about the paintoperation can be provided in comp

Example

import javaawt

import javaxswing

ltapplet code=JLabelDemo width=250 height=150gt

ltappletgt

public class JLabelDemo extends JApplet

public void init()

Get content pane

Container contentPane = getContentPane()

Create an icon

ImageIcon ii = new ImageIcon(francegif)

Create a label

JLabeljl = new JLabel(France ii JLabelCENTER)

Add label to the content pane

contentPaneadd(jl)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 16 of 38

e) Give the use of URL class along with syntax of constructors of URL class 4

(Use - 2 Marks Any two Constructor - 1 Mark each)

Ans The URL provides a reasonably intelligible form to uniquely identify or address information on the

Internet URLs are ubiquitous every browser uses them to identify information on the Web In

fact the Web is really just that same old Internet with all of its resources addressed as URLs plus

HTML

Javas URL class has several constructors One commonly used form specifies the URL with a

string that is identical to what you see displayed in a browser

1 URL(String urlSpecifier)

The next two forms of the constructor allow you to break up the URL into its componentparts

2 URL(String protocolName String hostName intport String path)

3 URL(String protocolName String hostName String path)

Another frequently used constructor allows you to use an existing URL as a referencecontext and

then create a new URL from that context Although this sounds a littlecontorted its really quite

easy and useful

4 URL(URL urlObj String urlSpecifier)

4 A) Attempt any three of the following Marks 12

a) Give the use of following methods of statement interface 4

i) executeQuery( ) ii) execute Update ( )

(Each method ndash 2 Marks)

Ans i) executeQuery()

The executeQuery() method of the statement object enables you to send SQL select statement to

the database and to receive result from the database Executing a query in effect sends a SQL

select statement to the database and returns the appropriate results back in the Resultset object

The executeQuery() method takes a SQL select statement as a parameter and returns a ResultSet

object that contains all the records that match the select statements criteria

ii) executeUpdate()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 17 of 38

The executeUpdate() method of the Statement object enables you to execute SQL update

statements such as delete insert and update The method takes a String containing the SQL update

statement and returns an integers that determines how many records were affected by the SQL

statement

b) Define Layout Manager Describe the use of GridLayout Manager 4

(Layout manager- 2 Marks Use-2 Marks)

Ans Each Container object has a layout manager associated with it A layout manager

is an instance of any class that implements the LayoutManagerinterface The layout

manager is set by the setLayout( ) method If no call to setLayout( ) is made then the

default layout manager is used Whenever a container is resized (or sized for the first

time) the layout manager is used to position each of the components within it

The setLayout( ) method has the following general form

voidsetLayout(LayoutManagerlayoutObj)

GridLayoutManager

GridLayout lays out components in a two-dimensional grid When you instantiate

a GridLayout you define the number of rows and columns The constructors

supported by GridLayoutare shown here

GridLayout( )

GridLayout(intnumRows intnumColumns)

GridLayout(intnumRows intnumColumns inthorz intvert)

c) Explain the use of cookies with example 4

(Explanation - 2 Marks Example - 2 Marks any one)

Ans Cookie is a small piece of information that is passed back and forth in the HTTP request and

response Even though a cookie can be created on the client side using some scripting language

such as JavaScript it is usually created by the server resource such as a Servlet The Cookies sent

by the server when the client requests another page from the same application In Servlet

programming a cookie is represented by a Cookie class in the javaxservlethttp package You can

create a cookie by calling the Cookie class constructor and passing two string objects the name

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 18 of 38

and value of the cookie For instance the following code creates a cookie object called c1The

cookie has the name ldquomyCookierdquo and value of rdquosecretrdquo

Cookie c1=new Cookie(ldquomyCookierdquordquosecretrdquo)

You then can add the cookie to the http response using addCookie method of the

HTTPServletResponse interfaceResponseaddCookie(c1)

Program for Add cookies

import javaio

importjavaxservlet

importjavaxservlethttp

public class AddCookieServlet extends HttpServlet

public void doPost(HttpServletRequest requestHttpServletResponse response)

throwsServletException IOException

Get parameter from HTTP request

String data = requestgetParameter(data)

Create cookie

Cookie cookie = new Cookie(MyCookie data)

Add cookie to HTTP response

responseaddCookie(cookie)

Write output to browser

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgtMyCookie has been set to)

pwprintln(data)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 19 of 38

pwclose()

OR

Program for Get Cookies

import javaio

importjavaxservlet

importjavaxservlethttp

public class GetCookiesServlet extends HttpServlet

public void doGet(HttpServletRequest requestHttpServletResponse response)

throwsServletException IOException

Get cookies from header of HTTP request

Cookie[] cookies = requestgetCookies()

Display these cookies

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgt)

for(inti = 0 iltcookieslength i++)

String name = cookies[i]getName()

String value = cookies[i]getValue()

pwprintln(name = + name +

value = + value)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 20 of 38

pwclose()

d) Give steps to create simple servlet with example 4

(Steps- 2 Marks Any one Example ndash 2 Marks)

Ans Steps 1) Write a java servet code

Steps 2) Compile Servet by setting classpath with servlet-api library

Step 3) Copy the class servlet file in web apps classpath directory

Steps 4) Open the webxml open it and add servlet tag and sevlet mapping tag

Steps 5) Start web server(apche tomcat)

Steps 6) Browse servlet using java compatible browser like IE

Example shows to start create a file named WelcomeServletjava that contains the following

program

import javaio

importjavaxservlet

public class WelcomeServletDemo extends GenericServlet

public void service(ServletRequestrequestServletResponse response) throws

ServletExceptionIOException

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgtWelcome to Servlet)

pwclose()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 21 of 38

B) Attempt any one of the following Marks 6

a) Describe the two ndashtier and three ndashtier database design of JDBC API with neat diagram

(Explanation of Two-tier-2 Marks and Three-tier-2 Marks Diagram ndash 1 Mark each)

Ans Two Tier Architecture

In a two tier model a java application is designed to interact directly with the database

Application functionality is divided into these two layers

1) Application Layer Including the JDBC driver business logic and user interface

2) Database Layer including RDBMS

The interface to the database is handled by the Java Database Connectivity(JDBC) Driver

appropriate to the particularly database management system being accessed The JDBC Driver

passes SQL statements to the database and returns the results of those statements to the

application

A clientserver configuration is the special case of the two tier model where the database is

located on another machine referred to as the server The application runs on the client machine

which is connected to the server over a network Commonly the network is an Intranet using

dedicated database servers to support multiple clients but it can just as easily be the internet

Three Tier Architecture-

In the three tier model the client typically sends requests to an application server forming the

middle tier The application server interprets these requests and formats the necessary SQL

statement to fulfill

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 22 of 38

These requests and sends them to the database The database process the SQL statements and

sends result back to the application server which then sends them to the client

Following are some advantages of Three-tier architecture

1 Performance can be improved by separating the application server and database server

2 Business logic is clearly separated from the database

3 Client application can use a simple protocol such as CGI to access services

The three-tier model show in following fig is a common in web application In this scenario the

client tier is frequently implemented in a browse on a client machine the middle tier is

implemented in a web server with a Servlet engine and the database management system runs on

a dedicated database server

Following are the main components of three tier architecture

1 Client Tier - Typically this is thin presentation layer that may be implemented using a web

browser

2 Middle Tier - This tier handles the business or application logic This may be implemented

using a Servlet engine such as Tomcat or an application server such as JBOSS The JDBC

driver also resides in this layer

3 Data source layer This component includes the RDBMS

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 23 of 38

b) Write servlet which shows how many times user has visited the page in session

(Any Correct Logic ndash4 Marks Syntax ndash 2 Marks)

Ans import javaio

import javaxservlet

import javaxservlethttp

public class Session Travker extends HttpServlet

public void doGet(HttpServletRequest req HttpServletResponse res) throws ServletException

IOException

ressetContentType(ldquotexthtmlrdquo)

PrintWriter out = resgetWriter()

HttpSession session = reqgetSession(true)

Integer count= (Integer)sessiongetValue(ldquotrackercountrdquo)

if(count== null) count=new Interger(1)

else count = new Interger(count intValue() +1)

sessionputValue(ldquotrackercountrdquocount)

outprintln(ldquoltHTMLgtltHEADgtltTITLEgtSession TrackerltTITLEgtltHEADgtrdquo)

outprintln(ldquoltBODYgtltH1gtSession Tracking DemoltH1gtrdquo)

outprintln(ldquoYou have visited this pagerdquo +count +((countintValue() == 1)rdquotimerdquo

ldquotimesrdquo))outprinln(ltPgtrdquo)

outprintln(ldquoltH2gtSesssion dataltH2gtrdquo)

String[] names = sessiongetValueNames()

for(int i=0 ilt nameslength i++)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 24 of 38

outprintln(names[i] + ldquo rdquo + sessiongetvalue(names[i])+ ldquoltBRgtrdquo)

outprintln(ldquoltBODYgtltHTMLgtrdquo)

5 Attempt any two of the following Marks 16

a) Write a program to display all records from Employee table from database using

JDBC

(Assume suitable data for table- Load driver create connection execute Query - 1 Mark

each Display data- 3 Marks Syntax ndash 2 Marks)

Ans import javasql

import javasqlStatement

import javaapplet

import javaawt

public class DisplayTable

public static void main( String args[])

RsultSet rs

Connection conn

try

String s1

ClassforName(sun jdbcodbcJdbcOdbcDriver)

Systemoutprintln(Connecting to a selected database)

String url=rdquojdbcodbcabcrdquo

conn = DriverManagergetConnection(DB_URL USER PASS)

Systemoutprintln(Connected database successfully)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 25 of 38

Systemoutprintln(Creating statement)

stmt = conncreateStatement()

sql = SELECT FROM Employee

ResultSet rs = stmtexecuteQuery(sql)

Tables fields assumed are id first last age

while(rsnext())

int id = rsgetInt(id)

int age = rsgetInt(age)

String first = rsgetString(first)

String last = rsgetString(last)

Systemoutprint(ID + id)

Systemoutprint( Age + age)

Systemoutprint( First + first)

Systemoutprintln( Last + last)

rsclose()

catch(SQLException se)

Handle errors for JDBC

seprintStackTrace()

catch(Exception e)

Handle errors for ClassforName

eprintStackTrace()

finally

finally block used to close resources

try

if(stmt=null)

connclose()

catch(SQLException se)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 26 of 38

b) Define the term

i) Reserved socket ii) proxy server

iii) Datagram iv) URL connection 4

(Each term- 2 Marks)

Ans i) Reserved socket

A socket is one end-point of a two-way communication link between two programs running on

the network Socket classes are used to represent the connection between a client program and a

server program

Reserved socket The socket which are reserved for specific protocols for communication

purpose are known as reseved sockets

TCPIP uses or reserves the lower 1024 ports for specific protocols

Example port number 23 is for Telnet 25 is for smtp 21 is for ftp 13 for daytime 110 for pop3

and so on Protocol decides how a client should interact with the port

ii) Proxy server

A proxy server is a computer that offers a computer network service to allow clients to make

indirect network connections to other network services A client connects to the proxy server

then requests a connection file or other resource available on a different server The proxy

provides the resource either by connecting to the specified server or by serving it from a cache In

some cases the proxy may alter the clients request or the servers response for various purposes

Purposes of the proxy servers

To keep machines behind it anonymous mainly for security

To speed up access to resources (using caching) Web proxies are commonly used to

cache web pages from a web server

To prevent downloading the same content multiple times (and save bandwidth)

To log audit usage eg to provide company employee Internet usage reporting

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 27 of 38

To scan transmitted content for malware before delivery

To scan outbound content eg for data loss prevention

iii) Datagram

Datagrams are bundles of information passed between machines They are somewhat like a hard

throw from a well-trained but blindfolded catcher to the third baseman Once the datagram has

been released to its intended target there is no assurance that it will arrive or even that

someone will be there to catch it Likewise when the datagram is received there is no

assurance that it hasnrsquot been damaged in transit or that whoever sent it is still there to receive a

response

Java implements datagrams on top of the UDP protocol by using two classes

The DatagramPacket object is the data container while the DatagramSocket is the mechanism

used to send or receive the DatagramPackets

iv) URL connection

URLConnection is a general-purpose class for accessing the attributes of a remote resource

Once you make a connection to a remote server you can use URLConnection to inspect the

Properties of the remote object before actually transporting it locally These attributes are

exposed by the HTTP protocol specification and as such only make sense for URL objects

that are using the HTTP protocol

URLConnection defines several methods

int getContentLength( )

String getContentType( )

long getDate( )

long getExpiration( )

String getHeaderField(int idx)

long getLastModified( )

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 28 of 38

c) Write a program to display three text fields and a button below to all an Applet Insert

the integer valuer from three text fields After pressing the button the background colour

of applet will be changed as per the RGB combination of the values given in the text field

(Correct logic - 6 Marks Syntax - 2 Marks)

4

Ans import javaawt

import javaawtevent

import javaapplet

ltapplet code=rdquoClrclassrdquo width=250 heigth=250gtltappletgt

public class Clrextends Applet implements ActionListener

int r g b

TextField t1t2t3

Button b1

Color c1

public void init()

t1= new TextField(5)

t2= new TextField(8)

t3= new TextField(11)

b1 = new Button(ldquo Set Colorrdquo)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 29 of 38

add(t1)

add(t2)

add(t3)

add(b1)

b1addActionListener(this)

public void void paint( )

setBackground(c1)

public void actionPerformed(ActionEvent ae)

r=IntegerparseInt(t1getText())

g=IntegerparseInt(t2getText())

b=IntegerparseInt(t3getText())

c1= new Color(rgb)

repaint()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 30 of 38

6) Attempt any four of the following Marks 16

a) How to check how many fonts are available in the computer system 4

Explain with example

(Explanation -2 Marks Example-2 Marks)

Ans When working with fonts often you need to know which fonts are available on your machine To

ontain this information you can use the getAvailableFontFamilyNames() method defined by the

GraphicsEnvironment classIt is shown here

String[ ] getAvailableFontFamilyNames( )

This method returns an array of string that contains the names of the available font families

Since this methods is members of GraphicsEnvironment you need a GraphicsEnvironment

reference to call itYou can obtain this reference by using the getlocalGrahicsEnvironmet() static

method which is derfined by GraphicsEnvironmentIt is shown here

static GraphicsEnvironment getLocalGraphicsEnvironment( )

Here is an applet that shown how to obtain the names of the available font families

ltapplet code=rdquoAllFontsrdquo width=500 height=100gt

ltappletgt

import javaapplet

import javaawt

public class AllFonts extends Applet

public void paint(Graphics g)

string fonts= ldquo rdquo

stirng allFontsList[]

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 31 of 38

GraphicsEnvironment t = GraphicsEnvironmentgetLocalGraphicsEnvironment()

allFontList = tgetAvailableFontFamilyNames()

for(int i= 0 ilt allFontsListlength i++)

fonts= fonts + allFontList[i] + ldquo rdquo

gdrawString(msg416)

b) Explain following check box class methods with appropriate example 4

i) Void setLable (String str) ii) Boolean getState ( )

(Explanation of each method-1 Marks Example-2 Marks)

Ans

i) void setLable(String str)

This method is used to set the label of check box

ii) Boolean getState()

This method is used to retrieve the current state of a check box It returns the value either true or

false depends on check box is selected or not

Example

Demonstrate check boxes

import javaawt

import javaawtevent

import javaapplet

ltapplet code=CheckboxDemo width=250 height=200gt

ltappletgt

public class CheckboxDemo extends Applet implements ItemListener

String msg =

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 32 of 38

Checkbox winXP winVista solaris mac

public void init()

winXP = new Checkbox(Windows XP null true)

mac = new Checkbox()

macsetLable(ldquoMac OSrdquo)

add(winXP)

add(mac)

winXPaddItemListener(this)

macaddItemListener(this)

public void itemStateChanged(ItemEvent ie)

repaint()

Display current state of the check boxes

public void paint(Graphics g)

msg = Current state

gdrawString(msg 6 80)

msg = Windows XP + winXPgetState()

gdrawString(msg 6 100)

msg = Mac OS + macgetState()

gdrawString(msg 6 120)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 33 of 38

c) Explain the techniques of session tracking management

(Any four techniques with explanation- 1 Mark each)

Ans Session tracking Techniques

1 User Authorization

Users can be authorized to use the web application in different ways Basic concept is that the

user will provide username and password to login to the application Based on that the user can

be identified and the session can be maintained

2 Hidden Fields

ltINPUT TYPE=rdquohiddenrdquo NAME=rdquotechnologyrdquo VALUE=rdquoservletrdquogt

Hidden fields like the above can be inserted in the webpages and information can be sent to the

server for session tracking These fields are not visible directly to the user but can be viewed

using view source option from the browsers This type doesnrsquot need any special configuration

from the browser of server and by default available to use for session tracking This cannot be

used for session tracking when the conversation included static resources lik html pages

3 URL Rewriting

Original URL httpserverportservletServletName

ewritten URL httpserverportservletServletNamesessionid=7456

When a request is made additional parameter is appended with the url In general added

additional parameter will be sessionid or sometimes the userid It will suffice to track the

session This type of session tracking doesnrsquot need any special support from the browser

Disadvantage is implementing this type of session tracking is tedious We need to keep track of

the parameter as a chain link until the conversation completes and also should make sure that

the parameter doesnrsquot clash with other application parameters

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 34 of 38

4 Cookies

Cookies are the mostly used technology for session tracking Cookie is a key value pair of

information sent by the server to the browser This should be saved by the browser in its space

in the client computer Whenever the browser sends a request to that server it sends the cookie

along with it Then the server can identify the client using the cookie

In java following is the source code snippet to create a cookie

Cookie cookie = new Cookie (ldquouserIDrdquo ldquo7456Prime)

resaddCookie(cookie)

5 Session tracking API

Session tracking API is built on top of the first four methods This is inorder to help the

developer to minimize the overhead of session tracking This type of session tracking is

provided by the underlying technology Lets take the java servlet example Then the servlet

container manages the session tracking task and the user need not do it explicitly using the java

servlets This is the best of all methods because all the management and errors related to

session tracking will be taken care of by the container itself

d) Give sequential steps for JTree in swing with example

(Steps- 2 Marks any small Example- 2 Marks)

Ans Steps for JTree

Atree is a component that presents a hierarchical view of data The user has the ability to

expand or collapse individual subtrees in this display Trees are implemented in Swing by

the JTree class

Here are the steps to follow to use a tree

1 Create an instance of JTree

2 Create a JScrollPane and specify the tree as the object to be scrolled

3 Add the tree to the scroll pane

4 Add the scroll pane to the content pane

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 35 of 38

Example

Demonstrate JTree

import javaawt

import javaxswingevent

import javaxswing

import javaxswingtree

ltapplet code=JTreeDemo width=400 height=200gt

ltappletgt

public class JTreeDemo extends JApplet

JTree tree

JLabel jlab

public void init()

try

SwingUtilitiesinvokeAndWait(

new Runnable()

public void run()

makeGUI()

)

catch (Exception exc)

Systemoutprintln(Cant create because of + exc)

private void makeGUI()

Create top node of tree

DefaultMutableTreeNode top = new DefaultMutableTreeNode(Options)

Create subtree of A

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 36 of 38

DefaultMutableTreeNode a = new DefaultMutableTreeNode(A)

topadd(a)

DefaultMutableTreeNode a1 = new DefaultMutableTreeNode(A1)

aadd(a1)

DefaultMutableTreeNode a2 = new DefaultMutableTreeNode(A2)

aadd(a2)

Create subtree of B

DefaultMutableTreeNode b = new DefaultMutableTreeNode(B)

topadd(b)

DefaultMutableTreeNode b1 = new DefaultMutableTreeNode(B1)

badd(b1)

DefaultMutableTreeNode b2 = new DefaultMutableTreeNode(B2)

badd(b2)

DefaultMutableTreeNode b3 = new DefaultMutableTreeNode(B3)

badd(b3)

Create the tree

tree = new JTree(top)

Add the tree to a scroll pane

JScrollPane jsp = new JScrollPane(tree)

Add the scroll pane to the content pane

add(jsp)

Add the label to the content pane

jlab = new JLabel()

add(jlab BorderLayoutSOUTH)

Handle tree selection events

treeaddTreeSelectionListener(new TreeSelectionListener()

public void valueChanged(TreeSelectionEvent tse)

jlabsetText(Selection is + tsegetPath())

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 37 of 38

e) Draw and explain the life cycle of servlet

(Explanation ndash 3 Marks Diagram -1 Marks)

Ans Three methods are central to the life cycle of a servlet

These are init( ) service( ) and destroy( )

They are implemented by every servlet and are invoked at specific times by the server Let

us consider a typical user scenario to understand when these methods are called

First assume that a user enters a Uniform Resource Locator (URL) to a web browser

The browser then generates an HTTP request for this URL This request is then sent to the

appropriate server

Second this HTTP request is received by the web server The server maps this request to

a particular servlet The servlet is dynamically retrieved and loaded into the address space

of the server

Third the server invokes the init( ) method of the servlet This method is invoked only

when the servlet is first loaded into memory It is possible to pass initialization parameters

to the servlet so it may configure itself

Fourth the server invokes the service( ) method of the servlet This method is called to

process the HTTP request You will see that it is possible for the servlet to read data that has

been provided in the HTTP request It may also formulate an HTTP response for the client

The servlet remains in the serverrsquos address space and is available to process any other

HTTP requests received from clients The service( ) method is called for each HTTP request

Finally the server may decide to unload the servlet from its memory The algorithms by

which this determination is made are specific to each server The server calls the destroy( )

method to relinquish any resources such as file handles that are allocated for the servlet

Important data may be saved to a persistent store The memory allocated for the servlet and

its objects can then be garbage collected

A servlet life cycle can be defined as the entire process from its creation till the destruction The

following are the paths followed by a servlet

The servlet is initialized by calling the init () method

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 38 of 38

The servlet calls service() method to process a clients request

The servlet is terminated by calling the destroy() method

Finally servlet is garbage collected by the garbage collector of the JVM

Initialization

(Load Resources)

Services

(Accept Requests)

Destruction

(Unload Resources)

Servlet

Request

Response

Page 7: AJP

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 7 of 38

item1= new MenuItem (ldquoNewrdquo)

item2= new MenuItem (ldquoopenrdquo)

item3= new MenuItem (ldquocloserdquo)

item4= new MenuItem (ldquo-rdquo)

item5= new MenuItem (ldquoQuitrdquo)

fileadd(item1)

fileadd(item2)

fileadd(item3)

fileadd(item4)

fileadd(item5)

mbaradd(file)

MenuItem item6item7item8item9

item6= new MenuItem (ldquocutrdquo)

item7= new MenuItem (ldquocopyrdquo)

item8= new MenuItem (ldquopasterdquo)

item9= new MenuItem (ldquo-rdquo)

editadd(item6)

editadd(item7)

editadd(item8)

editadd(item9)

mbaradd(edit)

item1addActionListener(this)

item2addActionListener(this)

item3addActionListener(this)

item4addActionListener(this)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 8 of 38

item5addActionListener(this)

item6addActionListener(this)

item7addActionListener(this)

item8addActionListener(this)

item9addActionListener(this)

Public void paint(Graphics g)

gdrawString(msg10200)

public void actionPerformed(ActionEvent e)

msg= ldquoYou have selected rdquo+ egetActionCommand()

repaint()

public static void main(String args[])

MenuFrame m=new MenuFrame(ldquoMyMenurdquo)

msetVisible(true)

msetSize(100200)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 9 of 38

b) Give the use of Server Socket and Socket class Describe the steps that are 8

required to establish communication between client and server sockets

(Use-2 Marks each class Steps-4 Marks)

Ans Server socket

A Server Socket handles the requests and sends back an appropriate reply The actual tasks that a

server socket must accomplish are implemented by an internal SocketImpl instance A server

socket waits for requests to come in over the network It performs some operation based on that

request and then possibly returns a result to the requester The actual work of the server socket is

performed by an instance of the SocketImpl class An application can change the socket factory

that creates the socket implementation to configure itself to create sockets appropriate to the local

firewall

Client socket

we have used the class named ClientSocketInformationjava that implement the constructor of

the Socket class passing two arguments as hostName and TIME_PORT This program throws an

IOException for the exception handling This exception is thrown to indicate an IO problem of

some sort occurred Here we are going to explore a method to retrieve the host name of the local

system in a very simple way In this way we find out the Local address Local host information

reuseAddress and address of the local system in a very simple manner

Steps to connect

Using TCP socket provides the communication mechanism between two computers A client

program creates a socket at its end of the communication and attempts to connect that socket to a

server

The following is the lists of sequential steps which occur when establishing a TCP connection

between client socket and server socket

1 The server initiates a Server Socket object and mentions which port number communication is

to occur on

2 The server invokes the accept () method of the ServerSocket class This method does the wait

till a client gets connected to the server on the given port

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 10 of 38

After the waiting stages of server a client instantiates a Socket object It also specifies the

server name and port number to which it gets connected

3 The constructor of the Socket class tries to connect the client to the specified server and port

number If the communication is established the client has a Socket object which is capable

of communicating with the server

4 On server side the accept () method returns a reference to a new socket on the server that is

connected to the clientrsquos socket

Once the connection are established communication occur using IO streams Each socket has

both an Outputstream and InputStreams

As we know that the TCP is a two way communication protocol So data can be sent across

both streams at the same time

Two constructors used to create client socket

Socket (String hostnameint port)

Creates a socket connection the localhost to name host and port

Socket(InetAddress ipAddressint port)

Creates a socket using pre existing InetAddress object and a port

A socket can be examined at any time for the address and port information associated with it

InetAddress getInetAddress()

Int getPort()

Int getLocalPort()

Once the socket object has been created it can be examined to gain access to ip and op streams

associated with it

Example (optional)

import javanet

import javaio

class abc

public static void main(String args[])throws Exception

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 11 of 38

int c

Socket s=new socket(ldquointericnetrdquo43)

InputStream in=sgetInputStream()

OutputStream out=sgetOutputStream()

String str=(argslength==0rdquoOsbornecomrdquo)

byte buf[]=strgetBytes()outwrite(buf)

while((c=inread())=-1)

Systemoutprintln(char)c)

sclose()

c) Give sequential steps to use JTabbedPane in an Applet with example

(Steps- 4Marks any one Example- 4Marks)

Ans The general procedure to use a tabbed pane in an applet is

1) Create a JtabbedPane object

2) Call addTab() to add to the pane

3) Repeat step 2 for each tab

4) Add the tabbed pane to the content pane of the applet

Example

import javaxswing

ltapplet code=rdquoJTabbedPaneDemordquo width=350

Height=250gt

ltappletgt

public class JTabbedPaneDemo extends JApplet

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 12 of 38

public void init()

JTabbedPane jtp= new JTabbedPane()

jtpaddTab(ldquocitiesrdquonew citiesPanel())

jtpaddTab(ldquocolorsrdquonew colorsPanel())

jtpaddTab(ldquoFlavourrdquonew flavourPanel())

getContentPane()add(jtp)

class citiespanel extends JPanel

Public citiesPanel()

JButton b1=new Button(ldquoNew Yorkrdquo)

add(b1)

JButton b2=new Button(ldquolondonrdquo)

add(b2)

class colorpanel extends JPanel

Public colorPanel()

JCheckBox cb1=new JCheckBox(ldquoredrdquo)

add(cb1)

JCheckBox cb2=new JCheckBox (ldquogreenrdquo)

add(cb2)

class flavourpanel extends JPanel

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 13 of 38

public flavourPanel()

JComboBox b=new JComboBox()

jcbaddItem(ldquovanillardquo)

jcbaddItem(ldquochocolaterdquo)

add(jcb)

3 Attempt any four of the following Marks 16

a) Example the use of prepared statement with example 4

(Explanation-2 Marks Example-2 Marks)

Ans PrepareStatement ()

The preparedStatement() method creates a PreparedStatement object and returns it as a return

value The Prepared statement object is used to execute dynamic SQL statement against the

databaseA dynamic SQL statement is a statement in which some of the parameters in the

statement are unknown when the statement is created The parameter is placed into the SQL

statement as they are determined by the application When all the parameters are specified for the

SQL statement the dynamic SQL statement will be executed just as a static statement is executed

To create a dynamic SQL statement that takes a first name and last name as parameters use the

following code

try

String sql=rdquoSelect from temployeerdquo + ldquowhere Firstname=rdquo + ldquoand Lastname=rdquo

PreparedStatement p=connectionpreparedStatement(sql)

Catch(SQLException e)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 14 of 38

b) List any four differences between AWT and swing 4

(Any four points ndash 1 Mark each)

Ans

Swing AWT

It uses javaxswing package It uses javaapplet package

It uses JApplet class It uses Applet class

Swing is light weight component AWT is heavy weight component

It does not have add() method to add

control

It has add() method to add control

AWT provides less features than

swing

Swing has variety of component amp

features which is not in AWT

Awt has huge collection of classes amp

interfaces

Swing has bigger collection of classes

amp interfaces than AWT

AWT has predefined formats of

appearance amp behavior of component

Swing provides a facility of different

appearance amp behavior of the same

component

c) List four interfaces in javaxservlet package 4

(Any four points ndash 1 Mark each)

Ans Following are the interfaces in javaxservlet package

1 Servlet All servlets must implement the Servlet interface It declares the init( ) service( )

and destroy( ) methods that are called by the server during the life cycle of a servlet

2 ServletConfig The ServletContextinterface is implemented by the server It enables servlets

to obtain information about their environment

3 ServletContext The ServletContextinterface is implemented by the server It enables

servlets to obtain information about their environment

4 ServletRequest The ServletRequestinterface is implemented by the server It enables a

servlet to obtain information about a client request

5 ServletResponse The ServletResponseinterface is implemented by the server It enables a

servlet to formulate a response for a client

6 SingleThreadModel This interface is used to indicate that only a single thread will execute

the service( ) method of a servlet at a given time It defines no constants and declares no

methods

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 15 of 38

d) Give the use of ImageIcon class with example 4

(Explanation ndash 2 Marks Example- 2 Marks)

Ans In Swing icons are encapsulated by the ImageIconclass which paints an icon from an

image Two of its constructors are shown here

ImageIcon(String filename)

ImageIcon(URL url)

The first form uses the image in the file named filename The second form uses the

image in the resource identified by url

The ImageIconclass implements the Icon interface that declares the methods

As follows

Method Description

intgetIconHeight( ) Returns the height of the iconin pixels

intgetIconWidth( ) Returns the width of the iconin pixels

voidpaintIcon(Component comp Graphics gintx inty)Paints the icon at position x y onthe

graphics context g Additionalinformation about the paintoperation can be provided in comp

Example

import javaawt

import javaxswing

ltapplet code=JLabelDemo width=250 height=150gt

ltappletgt

public class JLabelDemo extends JApplet

public void init()

Get content pane

Container contentPane = getContentPane()

Create an icon

ImageIcon ii = new ImageIcon(francegif)

Create a label

JLabeljl = new JLabel(France ii JLabelCENTER)

Add label to the content pane

contentPaneadd(jl)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 16 of 38

e) Give the use of URL class along with syntax of constructors of URL class 4

(Use - 2 Marks Any two Constructor - 1 Mark each)

Ans The URL provides a reasonably intelligible form to uniquely identify or address information on the

Internet URLs are ubiquitous every browser uses them to identify information on the Web In

fact the Web is really just that same old Internet with all of its resources addressed as URLs plus

HTML

Javas URL class has several constructors One commonly used form specifies the URL with a

string that is identical to what you see displayed in a browser

1 URL(String urlSpecifier)

The next two forms of the constructor allow you to break up the URL into its componentparts

2 URL(String protocolName String hostName intport String path)

3 URL(String protocolName String hostName String path)

Another frequently used constructor allows you to use an existing URL as a referencecontext and

then create a new URL from that context Although this sounds a littlecontorted its really quite

easy and useful

4 URL(URL urlObj String urlSpecifier)

4 A) Attempt any three of the following Marks 12

a) Give the use of following methods of statement interface 4

i) executeQuery( ) ii) execute Update ( )

(Each method ndash 2 Marks)

Ans i) executeQuery()

The executeQuery() method of the statement object enables you to send SQL select statement to

the database and to receive result from the database Executing a query in effect sends a SQL

select statement to the database and returns the appropriate results back in the Resultset object

The executeQuery() method takes a SQL select statement as a parameter and returns a ResultSet

object that contains all the records that match the select statements criteria

ii) executeUpdate()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 17 of 38

The executeUpdate() method of the Statement object enables you to execute SQL update

statements such as delete insert and update The method takes a String containing the SQL update

statement and returns an integers that determines how many records were affected by the SQL

statement

b) Define Layout Manager Describe the use of GridLayout Manager 4

(Layout manager- 2 Marks Use-2 Marks)

Ans Each Container object has a layout manager associated with it A layout manager

is an instance of any class that implements the LayoutManagerinterface The layout

manager is set by the setLayout( ) method If no call to setLayout( ) is made then the

default layout manager is used Whenever a container is resized (or sized for the first

time) the layout manager is used to position each of the components within it

The setLayout( ) method has the following general form

voidsetLayout(LayoutManagerlayoutObj)

GridLayoutManager

GridLayout lays out components in a two-dimensional grid When you instantiate

a GridLayout you define the number of rows and columns The constructors

supported by GridLayoutare shown here

GridLayout( )

GridLayout(intnumRows intnumColumns)

GridLayout(intnumRows intnumColumns inthorz intvert)

c) Explain the use of cookies with example 4

(Explanation - 2 Marks Example - 2 Marks any one)

Ans Cookie is a small piece of information that is passed back and forth in the HTTP request and

response Even though a cookie can be created on the client side using some scripting language

such as JavaScript it is usually created by the server resource such as a Servlet The Cookies sent

by the server when the client requests another page from the same application In Servlet

programming a cookie is represented by a Cookie class in the javaxservlethttp package You can

create a cookie by calling the Cookie class constructor and passing two string objects the name

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 18 of 38

and value of the cookie For instance the following code creates a cookie object called c1The

cookie has the name ldquomyCookierdquo and value of rdquosecretrdquo

Cookie c1=new Cookie(ldquomyCookierdquordquosecretrdquo)

You then can add the cookie to the http response using addCookie method of the

HTTPServletResponse interfaceResponseaddCookie(c1)

Program for Add cookies

import javaio

importjavaxservlet

importjavaxservlethttp

public class AddCookieServlet extends HttpServlet

public void doPost(HttpServletRequest requestHttpServletResponse response)

throwsServletException IOException

Get parameter from HTTP request

String data = requestgetParameter(data)

Create cookie

Cookie cookie = new Cookie(MyCookie data)

Add cookie to HTTP response

responseaddCookie(cookie)

Write output to browser

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgtMyCookie has been set to)

pwprintln(data)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 19 of 38

pwclose()

OR

Program for Get Cookies

import javaio

importjavaxservlet

importjavaxservlethttp

public class GetCookiesServlet extends HttpServlet

public void doGet(HttpServletRequest requestHttpServletResponse response)

throwsServletException IOException

Get cookies from header of HTTP request

Cookie[] cookies = requestgetCookies()

Display these cookies

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgt)

for(inti = 0 iltcookieslength i++)

String name = cookies[i]getName()

String value = cookies[i]getValue()

pwprintln(name = + name +

value = + value)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 20 of 38

pwclose()

d) Give steps to create simple servlet with example 4

(Steps- 2 Marks Any one Example ndash 2 Marks)

Ans Steps 1) Write a java servet code

Steps 2) Compile Servet by setting classpath with servlet-api library

Step 3) Copy the class servlet file in web apps classpath directory

Steps 4) Open the webxml open it and add servlet tag and sevlet mapping tag

Steps 5) Start web server(apche tomcat)

Steps 6) Browse servlet using java compatible browser like IE

Example shows to start create a file named WelcomeServletjava that contains the following

program

import javaio

importjavaxservlet

public class WelcomeServletDemo extends GenericServlet

public void service(ServletRequestrequestServletResponse response) throws

ServletExceptionIOException

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgtWelcome to Servlet)

pwclose()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 21 of 38

B) Attempt any one of the following Marks 6

a) Describe the two ndashtier and three ndashtier database design of JDBC API with neat diagram

(Explanation of Two-tier-2 Marks and Three-tier-2 Marks Diagram ndash 1 Mark each)

Ans Two Tier Architecture

In a two tier model a java application is designed to interact directly with the database

Application functionality is divided into these two layers

1) Application Layer Including the JDBC driver business logic and user interface

2) Database Layer including RDBMS

The interface to the database is handled by the Java Database Connectivity(JDBC) Driver

appropriate to the particularly database management system being accessed The JDBC Driver

passes SQL statements to the database and returns the results of those statements to the

application

A clientserver configuration is the special case of the two tier model where the database is

located on another machine referred to as the server The application runs on the client machine

which is connected to the server over a network Commonly the network is an Intranet using

dedicated database servers to support multiple clients but it can just as easily be the internet

Three Tier Architecture-

In the three tier model the client typically sends requests to an application server forming the

middle tier The application server interprets these requests and formats the necessary SQL

statement to fulfill

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 22 of 38

These requests and sends them to the database The database process the SQL statements and

sends result back to the application server which then sends them to the client

Following are some advantages of Three-tier architecture

1 Performance can be improved by separating the application server and database server

2 Business logic is clearly separated from the database

3 Client application can use a simple protocol such as CGI to access services

The three-tier model show in following fig is a common in web application In this scenario the

client tier is frequently implemented in a browse on a client machine the middle tier is

implemented in a web server with a Servlet engine and the database management system runs on

a dedicated database server

Following are the main components of three tier architecture

1 Client Tier - Typically this is thin presentation layer that may be implemented using a web

browser

2 Middle Tier - This tier handles the business or application logic This may be implemented

using a Servlet engine such as Tomcat or an application server such as JBOSS The JDBC

driver also resides in this layer

3 Data source layer This component includes the RDBMS

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 23 of 38

b) Write servlet which shows how many times user has visited the page in session

(Any Correct Logic ndash4 Marks Syntax ndash 2 Marks)

Ans import javaio

import javaxservlet

import javaxservlethttp

public class Session Travker extends HttpServlet

public void doGet(HttpServletRequest req HttpServletResponse res) throws ServletException

IOException

ressetContentType(ldquotexthtmlrdquo)

PrintWriter out = resgetWriter()

HttpSession session = reqgetSession(true)

Integer count= (Integer)sessiongetValue(ldquotrackercountrdquo)

if(count== null) count=new Interger(1)

else count = new Interger(count intValue() +1)

sessionputValue(ldquotrackercountrdquocount)

outprintln(ldquoltHTMLgtltHEADgtltTITLEgtSession TrackerltTITLEgtltHEADgtrdquo)

outprintln(ldquoltBODYgtltH1gtSession Tracking DemoltH1gtrdquo)

outprintln(ldquoYou have visited this pagerdquo +count +((countintValue() == 1)rdquotimerdquo

ldquotimesrdquo))outprinln(ltPgtrdquo)

outprintln(ldquoltH2gtSesssion dataltH2gtrdquo)

String[] names = sessiongetValueNames()

for(int i=0 ilt nameslength i++)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 24 of 38

outprintln(names[i] + ldquo rdquo + sessiongetvalue(names[i])+ ldquoltBRgtrdquo)

outprintln(ldquoltBODYgtltHTMLgtrdquo)

5 Attempt any two of the following Marks 16

a) Write a program to display all records from Employee table from database using

JDBC

(Assume suitable data for table- Load driver create connection execute Query - 1 Mark

each Display data- 3 Marks Syntax ndash 2 Marks)

Ans import javasql

import javasqlStatement

import javaapplet

import javaawt

public class DisplayTable

public static void main( String args[])

RsultSet rs

Connection conn

try

String s1

ClassforName(sun jdbcodbcJdbcOdbcDriver)

Systemoutprintln(Connecting to a selected database)

String url=rdquojdbcodbcabcrdquo

conn = DriverManagergetConnection(DB_URL USER PASS)

Systemoutprintln(Connected database successfully)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 25 of 38

Systemoutprintln(Creating statement)

stmt = conncreateStatement()

sql = SELECT FROM Employee

ResultSet rs = stmtexecuteQuery(sql)

Tables fields assumed are id first last age

while(rsnext())

int id = rsgetInt(id)

int age = rsgetInt(age)

String first = rsgetString(first)

String last = rsgetString(last)

Systemoutprint(ID + id)

Systemoutprint( Age + age)

Systemoutprint( First + first)

Systemoutprintln( Last + last)

rsclose()

catch(SQLException se)

Handle errors for JDBC

seprintStackTrace()

catch(Exception e)

Handle errors for ClassforName

eprintStackTrace()

finally

finally block used to close resources

try

if(stmt=null)

connclose()

catch(SQLException se)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 26 of 38

b) Define the term

i) Reserved socket ii) proxy server

iii) Datagram iv) URL connection 4

(Each term- 2 Marks)

Ans i) Reserved socket

A socket is one end-point of a two-way communication link between two programs running on

the network Socket classes are used to represent the connection between a client program and a

server program

Reserved socket The socket which are reserved for specific protocols for communication

purpose are known as reseved sockets

TCPIP uses or reserves the lower 1024 ports for specific protocols

Example port number 23 is for Telnet 25 is for smtp 21 is for ftp 13 for daytime 110 for pop3

and so on Protocol decides how a client should interact with the port

ii) Proxy server

A proxy server is a computer that offers a computer network service to allow clients to make

indirect network connections to other network services A client connects to the proxy server

then requests a connection file or other resource available on a different server The proxy

provides the resource either by connecting to the specified server or by serving it from a cache In

some cases the proxy may alter the clients request or the servers response for various purposes

Purposes of the proxy servers

To keep machines behind it anonymous mainly for security

To speed up access to resources (using caching) Web proxies are commonly used to

cache web pages from a web server

To prevent downloading the same content multiple times (and save bandwidth)

To log audit usage eg to provide company employee Internet usage reporting

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 27 of 38

To scan transmitted content for malware before delivery

To scan outbound content eg for data loss prevention

iii) Datagram

Datagrams are bundles of information passed between machines They are somewhat like a hard

throw from a well-trained but blindfolded catcher to the third baseman Once the datagram has

been released to its intended target there is no assurance that it will arrive or even that

someone will be there to catch it Likewise when the datagram is received there is no

assurance that it hasnrsquot been damaged in transit or that whoever sent it is still there to receive a

response

Java implements datagrams on top of the UDP protocol by using two classes

The DatagramPacket object is the data container while the DatagramSocket is the mechanism

used to send or receive the DatagramPackets

iv) URL connection

URLConnection is a general-purpose class for accessing the attributes of a remote resource

Once you make a connection to a remote server you can use URLConnection to inspect the

Properties of the remote object before actually transporting it locally These attributes are

exposed by the HTTP protocol specification and as such only make sense for URL objects

that are using the HTTP protocol

URLConnection defines several methods

int getContentLength( )

String getContentType( )

long getDate( )

long getExpiration( )

String getHeaderField(int idx)

long getLastModified( )

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 28 of 38

c) Write a program to display three text fields and a button below to all an Applet Insert

the integer valuer from three text fields After pressing the button the background colour

of applet will be changed as per the RGB combination of the values given in the text field

(Correct logic - 6 Marks Syntax - 2 Marks)

4

Ans import javaawt

import javaawtevent

import javaapplet

ltapplet code=rdquoClrclassrdquo width=250 heigth=250gtltappletgt

public class Clrextends Applet implements ActionListener

int r g b

TextField t1t2t3

Button b1

Color c1

public void init()

t1= new TextField(5)

t2= new TextField(8)

t3= new TextField(11)

b1 = new Button(ldquo Set Colorrdquo)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 29 of 38

add(t1)

add(t2)

add(t3)

add(b1)

b1addActionListener(this)

public void void paint( )

setBackground(c1)

public void actionPerformed(ActionEvent ae)

r=IntegerparseInt(t1getText())

g=IntegerparseInt(t2getText())

b=IntegerparseInt(t3getText())

c1= new Color(rgb)

repaint()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 30 of 38

6) Attempt any four of the following Marks 16

a) How to check how many fonts are available in the computer system 4

Explain with example

(Explanation -2 Marks Example-2 Marks)

Ans When working with fonts often you need to know which fonts are available on your machine To

ontain this information you can use the getAvailableFontFamilyNames() method defined by the

GraphicsEnvironment classIt is shown here

String[ ] getAvailableFontFamilyNames( )

This method returns an array of string that contains the names of the available font families

Since this methods is members of GraphicsEnvironment you need a GraphicsEnvironment

reference to call itYou can obtain this reference by using the getlocalGrahicsEnvironmet() static

method which is derfined by GraphicsEnvironmentIt is shown here

static GraphicsEnvironment getLocalGraphicsEnvironment( )

Here is an applet that shown how to obtain the names of the available font families

ltapplet code=rdquoAllFontsrdquo width=500 height=100gt

ltappletgt

import javaapplet

import javaawt

public class AllFonts extends Applet

public void paint(Graphics g)

string fonts= ldquo rdquo

stirng allFontsList[]

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 31 of 38

GraphicsEnvironment t = GraphicsEnvironmentgetLocalGraphicsEnvironment()

allFontList = tgetAvailableFontFamilyNames()

for(int i= 0 ilt allFontsListlength i++)

fonts= fonts + allFontList[i] + ldquo rdquo

gdrawString(msg416)

b) Explain following check box class methods with appropriate example 4

i) Void setLable (String str) ii) Boolean getState ( )

(Explanation of each method-1 Marks Example-2 Marks)

Ans

i) void setLable(String str)

This method is used to set the label of check box

ii) Boolean getState()

This method is used to retrieve the current state of a check box It returns the value either true or

false depends on check box is selected or not

Example

Demonstrate check boxes

import javaawt

import javaawtevent

import javaapplet

ltapplet code=CheckboxDemo width=250 height=200gt

ltappletgt

public class CheckboxDemo extends Applet implements ItemListener

String msg =

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 32 of 38

Checkbox winXP winVista solaris mac

public void init()

winXP = new Checkbox(Windows XP null true)

mac = new Checkbox()

macsetLable(ldquoMac OSrdquo)

add(winXP)

add(mac)

winXPaddItemListener(this)

macaddItemListener(this)

public void itemStateChanged(ItemEvent ie)

repaint()

Display current state of the check boxes

public void paint(Graphics g)

msg = Current state

gdrawString(msg 6 80)

msg = Windows XP + winXPgetState()

gdrawString(msg 6 100)

msg = Mac OS + macgetState()

gdrawString(msg 6 120)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 33 of 38

c) Explain the techniques of session tracking management

(Any four techniques with explanation- 1 Mark each)

Ans Session tracking Techniques

1 User Authorization

Users can be authorized to use the web application in different ways Basic concept is that the

user will provide username and password to login to the application Based on that the user can

be identified and the session can be maintained

2 Hidden Fields

ltINPUT TYPE=rdquohiddenrdquo NAME=rdquotechnologyrdquo VALUE=rdquoservletrdquogt

Hidden fields like the above can be inserted in the webpages and information can be sent to the

server for session tracking These fields are not visible directly to the user but can be viewed

using view source option from the browsers This type doesnrsquot need any special configuration

from the browser of server and by default available to use for session tracking This cannot be

used for session tracking when the conversation included static resources lik html pages

3 URL Rewriting

Original URL httpserverportservletServletName

ewritten URL httpserverportservletServletNamesessionid=7456

When a request is made additional parameter is appended with the url In general added

additional parameter will be sessionid or sometimes the userid It will suffice to track the

session This type of session tracking doesnrsquot need any special support from the browser

Disadvantage is implementing this type of session tracking is tedious We need to keep track of

the parameter as a chain link until the conversation completes and also should make sure that

the parameter doesnrsquot clash with other application parameters

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 34 of 38

4 Cookies

Cookies are the mostly used technology for session tracking Cookie is a key value pair of

information sent by the server to the browser This should be saved by the browser in its space

in the client computer Whenever the browser sends a request to that server it sends the cookie

along with it Then the server can identify the client using the cookie

In java following is the source code snippet to create a cookie

Cookie cookie = new Cookie (ldquouserIDrdquo ldquo7456Prime)

resaddCookie(cookie)

5 Session tracking API

Session tracking API is built on top of the first four methods This is inorder to help the

developer to minimize the overhead of session tracking This type of session tracking is

provided by the underlying technology Lets take the java servlet example Then the servlet

container manages the session tracking task and the user need not do it explicitly using the java

servlets This is the best of all methods because all the management and errors related to

session tracking will be taken care of by the container itself

d) Give sequential steps for JTree in swing with example

(Steps- 2 Marks any small Example- 2 Marks)

Ans Steps for JTree

Atree is a component that presents a hierarchical view of data The user has the ability to

expand or collapse individual subtrees in this display Trees are implemented in Swing by

the JTree class

Here are the steps to follow to use a tree

1 Create an instance of JTree

2 Create a JScrollPane and specify the tree as the object to be scrolled

3 Add the tree to the scroll pane

4 Add the scroll pane to the content pane

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 35 of 38

Example

Demonstrate JTree

import javaawt

import javaxswingevent

import javaxswing

import javaxswingtree

ltapplet code=JTreeDemo width=400 height=200gt

ltappletgt

public class JTreeDemo extends JApplet

JTree tree

JLabel jlab

public void init()

try

SwingUtilitiesinvokeAndWait(

new Runnable()

public void run()

makeGUI()

)

catch (Exception exc)

Systemoutprintln(Cant create because of + exc)

private void makeGUI()

Create top node of tree

DefaultMutableTreeNode top = new DefaultMutableTreeNode(Options)

Create subtree of A

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 36 of 38

DefaultMutableTreeNode a = new DefaultMutableTreeNode(A)

topadd(a)

DefaultMutableTreeNode a1 = new DefaultMutableTreeNode(A1)

aadd(a1)

DefaultMutableTreeNode a2 = new DefaultMutableTreeNode(A2)

aadd(a2)

Create subtree of B

DefaultMutableTreeNode b = new DefaultMutableTreeNode(B)

topadd(b)

DefaultMutableTreeNode b1 = new DefaultMutableTreeNode(B1)

badd(b1)

DefaultMutableTreeNode b2 = new DefaultMutableTreeNode(B2)

badd(b2)

DefaultMutableTreeNode b3 = new DefaultMutableTreeNode(B3)

badd(b3)

Create the tree

tree = new JTree(top)

Add the tree to a scroll pane

JScrollPane jsp = new JScrollPane(tree)

Add the scroll pane to the content pane

add(jsp)

Add the label to the content pane

jlab = new JLabel()

add(jlab BorderLayoutSOUTH)

Handle tree selection events

treeaddTreeSelectionListener(new TreeSelectionListener()

public void valueChanged(TreeSelectionEvent tse)

jlabsetText(Selection is + tsegetPath())

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 37 of 38

e) Draw and explain the life cycle of servlet

(Explanation ndash 3 Marks Diagram -1 Marks)

Ans Three methods are central to the life cycle of a servlet

These are init( ) service( ) and destroy( )

They are implemented by every servlet and are invoked at specific times by the server Let

us consider a typical user scenario to understand when these methods are called

First assume that a user enters a Uniform Resource Locator (URL) to a web browser

The browser then generates an HTTP request for this URL This request is then sent to the

appropriate server

Second this HTTP request is received by the web server The server maps this request to

a particular servlet The servlet is dynamically retrieved and loaded into the address space

of the server

Third the server invokes the init( ) method of the servlet This method is invoked only

when the servlet is first loaded into memory It is possible to pass initialization parameters

to the servlet so it may configure itself

Fourth the server invokes the service( ) method of the servlet This method is called to

process the HTTP request You will see that it is possible for the servlet to read data that has

been provided in the HTTP request It may also formulate an HTTP response for the client

The servlet remains in the serverrsquos address space and is available to process any other

HTTP requests received from clients The service( ) method is called for each HTTP request

Finally the server may decide to unload the servlet from its memory The algorithms by

which this determination is made are specific to each server The server calls the destroy( )

method to relinquish any resources such as file handles that are allocated for the servlet

Important data may be saved to a persistent store The memory allocated for the servlet and

its objects can then be garbage collected

A servlet life cycle can be defined as the entire process from its creation till the destruction The

following are the paths followed by a servlet

The servlet is initialized by calling the init () method

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 38 of 38

The servlet calls service() method to process a clients request

The servlet is terminated by calling the destroy() method

Finally servlet is garbage collected by the garbage collector of the JVM

Initialization

(Load Resources)

Services

(Accept Requests)

Destruction

(Unload Resources)

Servlet

Request

Response

Page 8: AJP

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 8 of 38

item5addActionListener(this)

item6addActionListener(this)

item7addActionListener(this)

item8addActionListener(this)

item9addActionListener(this)

Public void paint(Graphics g)

gdrawString(msg10200)

public void actionPerformed(ActionEvent e)

msg= ldquoYou have selected rdquo+ egetActionCommand()

repaint()

public static void main(String args[])

MenuFrame m=new MenuFrame(ldquoMyMenurdquo)

msetVisible(true)

msetSize(100200)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 9 of 38

b) Give the use of Server Socket and Socket class Describe the steps that are 8

required to establish communication between client and server sockets

(Use-2 Marks each class Steps-4 Marks)

Ans Server socket

A Server Socket handles the requests and sends back an appropriate reply The actual tasks that a

server socket must accomplish are implemented by an internal SocketImpl instance A server

socket waits for requests to come in over the network It performs some operation based on that

request and then possibly returns a result to the requester The actual work of the server socket is

performed by an instance of the SocketImpl class An application can change the socket factory

that creates the socket implementation to configure itself to create sockets appropriate to the local

firewall

Client socket

we have used the class named ClientSocketInformationjava that implement the constructor of

the Socket class passing two arguments as hostName and TIME_PORT This program throws an

IOException for the exception handling This exception is thrown to indicate an IO problem of

some sort occurred Here we are going to explore a method to retrieve the host name of the local

system in a very simple way In this way we find out the Local address Local host information

reuseAddress and address of the local system in a very simple manner

Steps to connect

Using TCP socket provides the communication mechanism between two computers A client

program creates a socket at its end of the communication and attempts to connect that socket to a

server

The following is the lists of sequential steps which occur when establishing a TCP connection

between client socket and server socket

1 The server initiates a Server Socket object and mentions which port number communication is

to occur on

2 The server invokes the accept () method of the ServerSocket class This method does the wait

till a client gets connected to the server on the given port

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 10 of 38

After the waiting stages of server a client instantiates a Socket object It also specifies the

server name and port number to which it gets connected

3 The constructor of the Socket class tries to connect the client to the specified server and port

number If the communication is established the client has a Socket object which is capable

of communicating with the server

4 On server side the accept () method returns a reference to a new socket on the server that is

connected to the clientrsquos socket

Once the connection are established communication occur using IO streams Each socket has

both an Outputstream and InputStreams

As we know that the TCP is a two way communication protocol So data can be sent across

both streams at the same time

Two constructors used to create client socket

Socket (String hostnameint port)

Creates a socket connection the localhost to name host and port

Socket(InetAddress ipAddressint port)

Creates a socket using pre existing InetAddress object and a port

A socket can be examined at any time for the address and port information associated with it

InetAddress getInetAddress()

Int getPort()

Int getLocalPort()

Once the socket object has been created it can be examined to gain access to ip and op streams

associated with it

Example (optional)

import javanet

import javaio

class abc

public static void main(String args[])throws Exception

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 11 of 38

int c

Socket s=new socket(ldquointericnetrdquo43)

InputStream in=sgetInputStream()

OutputStream out=sgetOutputStream()

String str=(argslength==0rdquoOsbornecomrdquo)

byte buf[]=strgetBytes()outwrite(buf)

while((c=inread())=-1)

Systemoutprintln(char)c)

sclose()

c) Give sequential steps to use JTabbedPane in an Applet with example

(Steps- 4Marks any one Example- 4Marks)

Ans The general procedure to use a tabbed pane in an applet is

1) Create a JtabbedPane object

2) Call addTab() to add to the pane

3) Repeat step 2 for each tab

4) Add the tabbed pane to the content pane of the applet

Example

import javaxswing

ltapplet code=rdquoJTabbedPaneDemordquo width=350

Height=250gt

ltappletgt

public class JTabbedPaneDemo extends JApplet

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 12 of 38

public void init()

JTabbedPane jtp= new JTabbedPane()

jtpaddTab(ldquocitiesrdquonew citiesPanel())

jtpaddTab(ldquocolorsrdquonew colorsPanel())

jtpaddTab(ldquoFlavourrdquonew flavourPanel())

getContentPane()add(jtp)

class citiespanel extends JPanel

Public citiesPanel()

JButton b1=new Button(ldquoNew Yorkrdquo)

add(b1)

JButton b2=new Button(ldquolondonrdquo)

add(b2)

class colorpanel extends JPanel

Public colorPanel()

JCheckBox cb1=new JCheckBox(ldquoredrdquo)

add(cb1)

JCheckBox cb2=new JCheckBox (ldquogreenrdquo)

add(cb2)

class flavourpanel extends JPanel

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 13 of 38

public flavourPanel()

JComboBox b=new JComboBox()

jcbaddItem(ldquovanillardquo)

jcbaddItem(ldquochocolaterdquo)

add(jcb)

3 Attempt any four of the following Marks 16

a) Example the use of prepared statement with example 4

(Explanation-2 Marks Example-2 Marks)

Ans PrepareStatement ()

The preparedStatement() method creates a PreparedStatement object and returns it as a return

value The Prepared statement object is used to execute dynamic SQL statement against the

databaseA dynamic SQL statement is a statement in which some of the parameters in the

statement are unknown when the statement is created The parameter is placed into the SQL

statement as they are determined by the application When all the parameters are specified for the

SQL statement the dynamic SQL statement will be executed just as a static statement is executed

To create a dynamic SQL statement that takes a first name and last name as parameters use the

following code

try

String sql=rdquoSelect from temployeerdquo + ldquowhere Firstname=rdquo + ldquoand Lastname=rdquo

PreparedStatement p=connectionpreparedStatement(sql)

Catch(SQLException e)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 14 of 38

b) List any four differences between AWT and swing 4

(Any four points ndash 1 Mark each)

Ans

Swing AWT

It uses javaxswing package It uses javaapplet package

It uses JApplet class It uses Applet class

Swing is light weight component AWT is heavy weight component

It does not have add() method to add

control

It has add() method to add control

AWT provides less features than

swing

Swing has variety of component amp

features which is not in AWT

Awt has huge collection of classes amp

interfaces

Swing has bigger collection of classes

amp interfaces than AWT

AWT has predefined formats of

appearance amp behavior of component

Swing provides a facility of different

appearance amp behavior of the same

component

c) List four interfaces in javaxservlet package 4

(Any four points ndash 1 Mark each)

Ans Following are the interfaces in javaxservlet package

1 Servlet All servlets must implement the Servlet interface It declares the init( ) service( )

and destroy( ) methods that are called by the server during the life cycle of a servlet

2 ServletConfig The ServletContextinterface is implemented by the server It enables servlets

to obtain information about their environment

3 ServletContext The ServletContextinterface is implemented by the server It enables

servlets to obtain information about their environment

4 ServletRequest The ServletRequestinterface is implemented by the server It enables a

servlet to obtain information about a client request

5 ServletResponse The ServletResponseinterface is implemented by the server It enables a

servlet to formulate a response for a client

6 SingleThreadModel This interface is used to indicate that only a single thread will execute

the service( ) method of a servlet at a given time It defines no constants and declares no

methods

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 15 of 38

d) Give the use of ImageIcon class with example 4

(Explanation ndash 2 Marks Example- 2 Marks)

Ans In Swing icons are encapsulated by the ImageIconclass which paints an icon from an

image Two of its constructors are shown here

ImageIcon(String filename)

ImageIcon(URL url)

The first form uses the image in the file named filename The second form uses the

image in the resource identified by url

The ImageIconclass implements the Icon interface that declares the methods

As follows

Method Description

intgetIconHeight( ) Returns the height of the iconin pixels

intgetIconWidth( ) Returns the width of the iconin pixels

voidpaintIcon(Component comp Graphics gintx inty)Paints the icon at position x y onthe

graphics context g Additionalinformation about the paintoperation can be provided in comp

Example

import javaawt

import javaxswing

ltapplet code=JLabelDemo width=250 height=150gt

ltappletgt

public class JLabelDemo extends JApplet

public void init()

Get content pane

Container contentPane = getContentPane()

Create an icon

ImageIcon ii = new ImageIcon(francegif)

Create a label

JLabeljl = new JLabel(France ii JLabelCENTER)

Add label to the content pane

contentPaneadd(jl)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 16 of 38

e) Give the use of URL class along with syntax of constructors of URL class 4

(Use - 2 Marks Any two Constructor - 1 Mark each)

Ans The URL provides a reasonably intelligible form to uniquely identify or address information on the

Internet URLs are ubiquitous every browser uses them to identify information on the Web In

fact the Web is really just that same old Internet with all of its resources addressed as URLs plus

HTML

Javas URL class has several constructors One commonly used form specifies the URL with a

string that is identical to what you see displayed in a browser

1 URL(String urlSpecifier)

The next two forms of the constructor allow you to break up the URL into its componentparts

2 URL(String protocolName String hostName intport String path)

3 URL(String protocolName String hostName String path)

Another frequently used constructor allows you to use an existing URL as a referencecontext and

then create a new URL from that context Although this sounds a littlecontorted its really quite

easy and useful

4 URL(URL urlObj String urlSpecifier)

4 A) Attempt any three of the following Marks 12

a) Give the use of following methods of statement interface 4

i) executeQuery( ) ii) execute Update ( )

(Each method ndash 2 Marks)

Ans i) executeQuery()

The executeQuery() method of the statement object enables you to send SQL select statement to

the database and to receive result from the database Executing a query in effect sends a SQL

select statement to the database and returns the appropriate results back in the Resultset object

The executeQuery() method takes a SQL select statement as a parameter and returns a ResultSet

object that contains all the records that match the select statements criteria

ii) executeUpdate()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 17 of 38

The executeUpdate() method of the Statement object enables you to execute SQL update

statements such as delete insert and update The method takes a String containing the SQL update

statement and returns an integers that determines how many records were affected by the SQL

statement

b) Define Layout Manager Describe the use of GridLayout Manager 4

(Layout manager- 2 Marks Use-2 Marks)

Ans Each Container object has a layout manager associated with it A layout manager

is an instance of any class that implements the LayoutManagerinterface The layout

manager is set by the setLayout( ) method If no call to setLayout( ) is made then the

default layout manager is used Whenever a container is resized (or sized for the first

time) the layout manager is used to position each of the components within it

The setLayout( ) method has the following general form

voidsetLayout(LayoutManagerlayoutObj)

GridLayoutManager

GridLayout lays out components in a two-dimensional grid When you instantiate

a GridLayout you define the number of rows and columns The constructors

supported by GridLayoutare shown here

GridLayout( )

GridLayout(intnumRows intnumColumns)

GridLayout(intnumRows intnumColumns inthorz intvert)

c) Explain the use of cookies with example 4

(Explanation - 2 Marks Example - 2 Marks any one)

Ans Cookie is a small piece of information that is passed back and forth in the HTTP request and

response Even though a cookie can be created on the client side using some scripting language

such as JavaScript it is usually created by the server resource such as a Servlet The Cookies sent

by the server when the client requests another page from the same application In Servlet

programming a cookie is represented by a Cookie class in the javaxservlethttp package You can

create a cookie by calling the Cookie class constructor and passing two string objects the name

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 18 of 38

and value of the cookie For instance the following code creates a cookie object called c1The

cookie has the name ldquomyCookierdquo and value of rdquosecretrdquo

Cookie c1=new Cookie(ldquomyCookierdquordquosecretrdquo)

You then can add the cookie to the http response using addCookie method of the

HTTPServletResponse interfaceResponseaddCookie(c1)

Program for Add cookies

import javaio

importjavaxservlet

importjavaxservlethttp

public class AddCookieServlet extends HttpServlet

public void doPost(HttpServletRequest requestHttpServletResponse response)

throwsServletException IOException

Get parameter from HTTP request

String data = requestgetParameter(data)

Create cookie

Cookie cookie = new Cookie(MyCookie data)

Add cookie to HTTP response

responseaddCookie(cookie)

Write output to browser

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgtMyCookie has been set to)

pwprintln(data)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 19 of 38

pwclose()

OR

Program for Get Cookies

import javaio

importjavaxservlet

importjavaxservlethttp

public class GetCookiesServlet extends HttpServlet

public void doGet(HttpServletRequest requestHttpServletResponse response)

throwsServletException IOException

Get cookies from header of HTTP request

Cookie[] cookies = requestgetCookies()

Display these cookies

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgt)

for(inti = 0 iltcookieslength i++)

String name = cookies[i]getName()

String value = cookies[i]getValue()

pwprintln(name = + name +

value = + value)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 20 of 38

pwclose()

d) Give steps to create simple servlet with example 4

(Steps- 2 Marks Any one Example ndash 2 Marks)

Ans Steps 1) Write a java servet code

Steps 2) Compile Servet by setting classpath with servlet-api library

Step 3) Copy the class servlet file in web apps classpath directory

Steps 4) Open the webxml open it and add servlet tag and sevlet mapping tag

Steps 5) Start web server(apche tomcat)

Steps 6) Browse servlet using java compatible browser like IE

Example shows to start create a file named WelcomeServletjava that contains the following

program

import javaio

importjavaxservlet

public class WelcomeServletDemo extends GenericServlet

public void service(ServletRequestrequestServletResponse response) throws

ServletExceptionIOException

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgtWelcome to Servlet)

pwclose()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 21 of 38

B) Attempt any one of the following Marks 6

a) Describe the two ndashtier and three ndashtier database design of JDBC API with neat diagram

(Explanation of Two-tier-2 Marks and Three-tier-2 Marks Diagram ndash 1 Mark each)

Ans Two Tier Architecture

In a two tier model a java application is designed to interact directly with the database

Application functionality is divided into these two layers

1) Application Layer Including the JDBC driver business logic and user interface

2) Database Layer including RDBMS

The interface to the database is handled by the Java Database Connectivity(JDBC) Driver

appropriate to the particularly database management system being accessed The JDBC Driver

passes SQL statements to the database and returns the results of those statements to the

application

A clientserver configuration is the special case of the two tier model where the database is

located on another machine referred to as the server The application runs on the client machine

which is connected to the server over a network Commonly the network is an Intranet using

dedicated database servers to support multiple clients but it can just as easily be the internet

Three Tier Architecture-

In the three tier model the client typically sends requests to an application server forming the

middle tier The application server interprets these requests and formats the necessary SQL

statement to fulfill

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 22 of 38

These requests and sends them to the database The database process the SQL statements and

sends result back to the application server which then sends them to the client

Following are some advantages of Three-tier architecture

1 Performance can be improved by separating the application server and database server

2 Business logic is clearly separated from the database

3 Client application can use a simple protocol such as CGI to access services

The three-tier model show in following fig is a common in web application In this scenario the

client tier is frequently implemented in a browse on a client machine the middle tier is

implemented in a web server with a Servlet engine and the database management system runs on

a dedicated database server

Following are the main components of three tier architecture

1 Client Tier - Typically this is thin presentation layer that may be implemented using a web

browser

2 Middle Tier - This tier handles the business or application logic This may be implemented

using a Servlet engine such as Tomcat or an application server such as JBOSS The JDBC

driver also resides in this layer

3 Data source layer This component includes the RDBMS

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 23 of 38

b) Write servlet which shows how many times user has visited the page in session

(Any Correct Logic ndash4 Marks Syntax ndash 2 Marks)

Ans import javaio

import javaxservlet

import javaxservlethttp

public class Session Travker extends HttpServlet

public void doGet(HttpServletRequest req HttpServletResponse res) throws ServletException

IOException

ressetContentType(ldquotexthtmlrdquo)

PrintWriter out = resgetWriter()

HttpSession session = reqgetSession(true)

Integer count= (Integer)sessiongetValue(ldquotrackercountrdquo)

if(count== null) count=new Interger(1)

else count = new Interger(count intValue() +1)

sessionputValue(ldquotrackercountrdquocount)

outprintln(ldquoltHTMLgtltHEADgtltTITLEgtSession TrackerltTITLEgtltHEADgtrdquo)

outprintln(ldquoltBODYgtltH1gtSession Tracking DemoltH1gtrdquo)

outprintln(ldquoYou have visited this pagerdquo +count +((countintValue() == 1)rdquotimerdquo

ldquotimesrdquo))outprinln(ltPgtrdquo)

outprintln(ldquoltH2gtSesssion dataltH2gtrdquo)

String[] names = sessiongetValueNames()

for(int i=0 ilt nameslength i++)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 24 of 38

outprintln(names[i] + ldquo rdquo + sessiongetvalue(names[i])+ ldquoltBRgtrdquo)

outprintln(ldquoltBODYgtltHTMLgtrdquo)

5 Attempt any two of the following Marks 16

a) Write a program to display all records from Employee table from database using

JDBC

(Assume suitable data for table- Load driver create connection execute Query - 1 Mark

each Display data- 3 Marks Syntax ndash 2 Marks)

Ans import javasql

import javasqlStatement

import javaapplet

import javaawt

public class DisplayTable

public static void main( String args[])

RsultSet rs

Connection conn

try

String s1

ClassforName(sun jdbcodbcJdbcOdbcDriver)

Systemoutprintln(Connecting to a selected database)

String url=rdquojdbcodbcabcrdquo

conn = DriverManagergetConnection(DB_URL USER PASS)

Systemoutprintln(Connected database successfully)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 25 of 38

Systemoutprintln(Creating statement)

stmt = conncreateStatement()

sql = SELECT FROM Employee

ResultSet rs = stmtexecuteQuery(sql)

Tables fields assumed are id first last age

while(rsnext())

int id = rsgetInt(id)

int age = rsgetInt(age)

String first = rsgetString(first)

String last = rsgetString(last)

Systemoutprint(ID + id)

Systemoutprint( Age + age)

Systemoutprint( First + first)

Systemoutprintln( Last + last)

rsclose()

catch(SQLException se)

Handle errors for JDBC

seprintStackTrace()

catch(Exception e)

Handle errors for ClassforName

eprintStackTrace()

finally

finally block used to close resources

try

if(stmt=null)

connclose()

catch(SQLException se)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 26 of 38

b) Define the term

i) Reserved socket ii) proxy server

iii) Datagram iv) URL connection 4

(Each term- 2 Marks)

Ans i) Reserved socket

A socket is one end-point of a two-way communication link between two programs running on

the network Socket classes are used to represent the connection between a client program and a

server program

Reserved socket The socket which are reserved for specific protocols for communication

purpose are known as reseved sockets

TCPIP uses or reserves the lower 1024 ports for specific protocols

Example port number 23 is for Telnet 25 is for smtp 21 is for ftp 13 for daytime 110 for pop3

and so on Protocol decides how a client should interact with the port

ii) Proxy server

A proxy server is a computer that offers a computer network service to allow clients to make

indirect network connections to other network services A client connects to the proxy server

then requests a connection file or other resource available on a different server The proxy

provides the resource either by connecting to the specified server or by serving it from a cache In

some cases the proxy may alter the clients request or the servers response for various purposes

Purposes of the proxy servers

To keep machines behind it anonymous mainly for security

To speed up access to resources (using caching) Web proxies are commonly used to

cache web pages from a web server

To prevent downloading the same content multiple times (and save bandwidth)

To log audit usage eg to provide company employee Internet usage reporting

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 27 of 38

To scan transmitted content for malware before delivery

To scan outbound content eg for data loss prevention

iii) Datagram

Datagrams are bundles of information passed between machines They are somewhat like a hard

throw from a well-trained but blindfolded catcher to the third baseman Once the datagram has

been released to its intended target there is no assurance that it will arrive or even that

someone will be there to catch it Likewise when the datagram is received there is no

assurance that it hasnrsquot been damaged in transit or that whoever sent it is still there to receive a

response

Java implements datagrams on top of the UDP protocol by using two classes

The DatagramPacket object is the data container while the DatagramSocket is the mechanism

used to send or receive the DatagramPackets

iv) URL connection

URLConnection is a general-purpose class for accessing the attributes of a remote resource

Once you make a connection to a remote server you can use URLConnection to inspect the

Properties of the remote object before actually transporting it locally These attributes are

exposed by the HTTP protocol specification and as such only make sense for URL objects

that are using the HTTP protocol

URLConnection defines several methods

int getContentLength( )

String getContentType( )

long getDate( )

long getExpiration( )

String getHeaderField(int idx)

long getLastModified( )

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 28 of 38

c) Write a program to display three text fields and a button below to all an Applet Insert

the integer valuer from three text fields After pressing the button the background colour

of applet will be changed as per the RGB combination of the values given in the text field

(Correct logic - 6 Marks Syntax - 2 Marks)

4

Ans import javaawt

import javaawtevent

import javaapplet

ltapplet code=rdquoClrclassrdquo width=250 heigth=250gtltappletgt

public class Clrextends Applet implements ActionListener

int r g b

TextField t1t2t3

Button b1

Color c1

public void init()

t1= new TextField(5)

t2= new TextField(8)

t3= new TextField(11)

b1 = new Button(ldquo Set Colorrdquo)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 29 of 38

add(t1)

add(t2)

add(t3)

add(b1)

b1addActionListener(this)

public void void paint( )

setBackground(c1)

public void actionPerformed(ActionEvent ae)

r=IntegerparseInt(t1getText())

g=IntegerparseInt(t2getText())

b=IntegerparseInt(t3getText())

c1= new Color(rgb)

repaint()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 30 of 38

6) Attempt any four of the following Marks 16

a) How to check how many fonts are available in the computer system 4

Explain with example

(Explanation -2 Marks Example-2 Marks)

Ans When working with fonts often you need to know which fonts are available on your machine To

ontain this information you can use the getAvailableFontFamilyNames() method defined by the

GraphicsEnvironment classIt is shown here

String[ ] getAvailableFontFamilyNames( )

This method returns an array of string that contains the names of the available font families

Since this methods is members of GraphicsEnvironment you need a GraphicsEnvironment

reference to call itYou can obtain this reference by using the getlocalGrahicsEnvironmet() static

method which is derfined by GraphicsEnvironmentIt is shown here

static GraphicsEnvironment getLocalGraphicsEnvironment( )

Here is an applet that shown how to obtain the names of the available font families

ltapplet code=rdquoAllFontsrdquo width=500 height=100gt

ltappletgt

import javaapplet

import javaawt

public class AllFonts extends Applet

public void paint(Graphics g)

string fonts= ldquo rdquo

stirng allFontsList[]

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 31 of 38

GraphicsEnvironment t = GraphicsEnvironmentgetLocalGraphicsEnvironment()

allFontList = tgetAvailableFontFamilyNames()

for(int i= 0 ilt allFontsListlength i++)

fonts= fonts + allFontList[i] + ldquo rdquo

gdrawString(msg416)

b) Explain following check box class methods with appropriate example 4

i) Void setLable (String str) ii) Boolean getState ( )

(Explanation of each method-1 Marks Example-2 Marks)

Ans

i) void setLable(String str)

This method is used to set the label of check box

ii) Boolean getState()

This method is used to retrieve the current state of a check box It returns the value either true or

false depends on check box is selected or not

Example

Demonstrate check boxes

import javaawt

import javaawtevent

import javaapplet

ltapplet code=CheckboxDemo width=250 height=200gt

ltappletgt

public class CheckboxDemo extends Applet implements ItemListener

String msg =

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 32 of 38

Checkbox winXP winVista solaris mac

public void init()

winXP = new Checkbox(Windows XP null true)

mac = new Checkbox()

macsetLable(ldquoMac OSrdquo)

add(winXP)

add(mac)

winXPaddItemListener(this)

macaddItemListener(this)

public void itemStateChanged(ItemEvent ie)

repaint()

Display current state of the check boxes

public void paint(Graphics g)

msg = Current state

gdrawString(msg 6 80)

msg = Windows XP + winXPgetState()

gdrawString(msg 6 100)

msg = Mac OS + macgetState()

gdrawString(msg 6 120)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 33 of 38

c) Explain the techniques of session tracking management

(Any four techniques with explanation- 1 Mark each)

Ans Session tracking Techniques

1 User Authorization

Users can be authorized to use the web application in different ways Basic concept is that the

user will provide username and password to login to the application Based on that the user can

be identified and the session can be maintained

2 Hidden Fields

ltINPUT TYPE=rdquohiddenrdquo NAME=rdquotechnologyrdquo VALUE=rdquoservletrdquogt

Hidden fields like the above can be inserted in the webpages and information can be sent to the

server for session tracking These fields are not visible directly to the user but can be viewed

using view source option from the browsers This type doesnrsquot need any special configuration

from the browser of server and by default available to use for session tracking This cannot be

used for session tracking when the conversation included static resources lik html pages

3 URL Rewriting

Original URL httpserverportservletServletName

ewritten URL httpserverportservletServletNamesessionid=7456

When a request is made additional parameter is appended with the url In general added

additional parameter will be sessionid or sometimes the userid It will suffice to track the

session This type of session tracking doesnrsquot need any special support from the browser

Disadvantage is implementing this type of session tracking is tedious We need to keep track of

the parameter as a chain link until the conversation completes and also should make sure that

the parameter doesnrsquot clash with other application parameters

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 34 of 38

4 Cookies

Cookies are the mostly used technology for session tracking Cookie is a key value pair of

information sent by the server to the browser This should be saved by the browser in its space

in the client computer Whenever the browser sends a request to that server it sends the cookie

along with it Then the server can identify the client using the cookie

In java following is the source code snippet to create a cookie

Cookie cookie = new Cookie (ldquouserIDrdquo ldquo7456Prime)

resaddCookie(cookie)

5 Session tracking API

Session tracking API is built on top of the first four methods This is inorder to help the

developer to minimize the overhead of session tracking This type of session tracking is

provided by the underlying technology Lets take the java servlet example Then the servlet

container manages the session tracking task and the user need not do it explicitly using the java

servlets This is the best of all methods because all the management and errors related to

session tracking will be taken care of by the container itself

d) Give sequential steps for JTree in swing with example

(Steps- 2 Marks any small Example- 2 Marks)

Ans Steps for JTree

Atree is a component that presents a hierarchical view of data The user has the ability to

expand or collapse individual subtrees in this display Trees are implemented in Swing by

the JTree class

Here are the steps to follow to use a tree

1 Create an instance of JTree

2 Create a JScrollPane and specify the tree as the object to be scrolled

3 Add the tree to the scroll pane

4 Add the scroll pane to the content pane

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 35 of 38

Example

Demonstrate JTree

import javaawt

import javaxswingevent

import javaxswing

import javaxswingtree

ltapplet code=JTreeDemo width=400 height=200gt

ltappletgt

public class JTreeDemo extends JApplet

JTree tree

JLabel jlab

public void init()

try

SwingUtilitiesinvokeAndWait(

new Runnable()

public void run()

makeGUI()

)

catch (Exception exc)

Systemoutprintln(Cant create because of + exc)

private void makeGUI()

Create top node of tree

DefaultMutableTreeNode top = new DefaultMutableTreeNode(Options)

Create subtree of A

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 36 of 38

DefaultMutableTreeNode a = new DefaultMutableTreeNode(A)

topadd(a)

DefaultMutableTreeNode a1 = new DefaultMutableTreeNode(A1)

aadd(a1)

DefaultMutableTreeNode a2 = new DefaultMutableTreeNode(A2)

aadd(a2)

Create subtree of B

DefaultMutableTreeNode b = new DefaultMutableTreeNode(B)

topadd(b)

DefaultMutableTreeNode b1 = new DefaultMutableTreeNode(B1)

badd(b1)

DefaultMutableTreeNode b2 = new DefaultMutableTreeNode(B2)

badd(b2)

DefaultMutableTreeNode b3 = new DefaultMutableTreeNode(B3)

badd(b3)

Create the tree

tree = new JTree(top)

Add the tree to a scroll pane

JScrollPane jsp = new JScrollPane(tree)

Add the scroll pane to the content pane

add(jsp)

Add the label to the content pane

jlab = new JLabel()

add(jlab BorderLayoutSOUTH)

Handle tree selection events

treeaddTreeSelectionListener(new TreeSelectionListener()

public void valueChanged(TreeSelectionEvent tse)

jlabsetText(Selection is + tsegetPath())

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 37 of 38

e) Draw and explain the life cycle of servlet

(Explanation ndash 3 Marks Diagram -1 Marks)

Ans Three methods are central to the life cycle of a servlet

These are init( ) service( ) and destroy( )

They are implemented by every servlet and are invoked at specific times by the server Let

us consider a typical user scenario to understand when these methods are called

First assume that a user enters a Uniform Resource Locator (URL) to a web browser

The browser then generates an HTTP request for this URL This request is then sent to the

appropriate server

Second this HTTP request is received by the web server The server maps this request to

a particular servlet The servlet is dynamically retrieved and loaded into the address space

of the server

Third the server invokes the init( ) method of the servlet This method is invoked only

when the servlet is first loaded into memory It is possible to pass initialization parameters

to the servlet so it may configure itself

Fourth the server invokes the service( ) method of the servlet This method is called to

process the HTTP request You will see that it is possible for the servlet to read data that has

been provided in the HTTP request It may also formulate an HTTP response for the client

The servlet remains in the serverrsquos address space and is available to process any other

HTTP requests received from clients The service( ) method is called for each HTTP request

Finally the server may decide to unload the servlet from its memory The algorithms by

which this determination is made are specific to each server The server calls the destroy( )

method to relinquish any resources such as file handles that are allocated for the servlet

Important data may be saved to a persistent store The memory allocated for the servlet and

its objects can then be garbage collected

A servlet life cycle can be defined as the entire process from its creation till the destruction The

following are the paths followed by a servlet

The servlet is initialized by calling the init () method

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 38 of 38

The servlet calls service() method to process a clients request

The servlet is terminated by calling the destroy() method

Finally servlet is garbage collected by the garbage collector of the JVM

Initialization

(Load Resources)

Services

(Accept Requests)

Destruction

(Unload Resources)

Servlet

Request

Response

Page 9: AJP

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 9 of 38

b) Give the use of Server Socket and Socket class Describe the steps that are 8

required to establish communication between client and server sockets

(Use-2 Marks each class Steps-4 Marks)

Ans Server socket

A Server Socket handles the requests and sends back an appropriate reply The actual tasks that a

server socket must accomplish are implemented by an internal SocketImpl instance A server

socket waits for requests to come in over the network It performs some operation based on that

request and then possibly returns a result to the requester The actual work of the server socket is

performed by an instance of the SocketImpl class An application can change the socket factory

that creates the socket implementation to configure itself to create sockets appropriate to the local

firewall

Client socket

we have used the class named ClientSocketInformationjava that implement the constructor of

the Socket class passing two arguments as hostName and TIME_PORT This program throws an

IOException for the exception handling This exception is thrown to indicate an IO problem of

some sort occurred Here we are going to explore a method to retrieve the host name of the local

system in a very simple way In this way we find out the Local address Local host information

reuseAddress and address of the local system in a very simple manner

Steps to connect

Using TCP socket provides the communication mechanism between two computers A client

program creates a socket at its end of the communication and attempts to connect that socket to a

server

The following is the lists of sequential steps which occur when establishing a TCP connection

between client socket and server socket

1 The server initiates a Server Socket object and mentions which port number communication is

to occur on

2 The server invokes the accept () method of the ServerSocket class This method does the wait

till a client gets connected to the server on the given port

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 10 of 38

After the waiting stages of server a client instantiates a Socket object It also specifies the

server name and port number to which it gets connected

3 The constructor of the Socket class tries to connect the client to the specified server and port

number If the communication is established the client has a Socket object which is capable

of communicating with the server

4 On server side the accept () method returns a reference to a new socket on the server that is

connected to the clientrsquos socket

Once the connection are established communication occur using IO streams Each socket has

both an Outputstream and InputStreams

As we know that the TCP is a two way communication protocol So data can be sent across

both streams at the same time

Two constructors used to create client socket

Socket (String hostnameint port)

Creates a socket connection the localhost to name host and port

Socket(InetAddress ipAddressint port)

Creates a socket using pre existing InetAddress object and a port

A socket can be examined at any time for the address and port information associated with it

InetAddress getInetAddress()

Int getPort()

Int getLocalPort()

Once the socket object has been created it can be examined to gain access to ip and op streams

associated with it

Example (optional)

import javanet

import javaio

class abc

public static void main(String args[])throws Exception

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 11 of 38

int c

Socket s=new socket(ldquointericnetrdquo43)

InputStream in=sgetInputStream()

OutputStream out=sgetOutputStream()

String str=(argslength==0rdquoOsbornecomrdquo)

byte buf[]=strgetBytes()outwrite(buf)

while((c=inread())=-1)

Systemoutprintln(char)c)

sclose()

c) Give sequential steps to use JTabbedPane in an Applet with example

(Steps- 4Marks any one Example- 4Marks)

Ans The general procedure to use a tabbed pane in an applet is

1) Create a JtabbedPane object

2) Call addTab() to add to the pane

3) Repeat step 2 for each tab

4) Add the tabbed pane to the content pane of the applet

Example

import javaxswing

ltapplet code=rdquoJTabbedPaneDemordquo width=350

Height=250gt

ltappletgt

public class JTabbedPaneDemo extends JApplet

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 12 of 38

public void init()

JTabbedPane jtp= new JTabbedPane()

jtpaddTab(ldquocitiesrdquonew citiesPanel())

jtpaddTab(ldquocolorsrdquonew colorsPanel())

jtpaddTab(ldquoFlavourrdquonew flavourPanel())

getContentPane()add(jtp)

class citiespanel extends JPanel

Public citiesPanel()

JButton b1=new Button(ldquoNew Yorkrdquo)

add(b1)

JButton b2=new Button(ldquolondonrdquo)

add(b2)

class colorpanel extends JPanel

Public colorPanel()

JCheckBox cb1=new JCheckBox(ldquoredrdquo)

add(cb1)

JCheckBox cb2=new JCheckBox (ldquogreenrdquo)

add(cb2)

class flavourpanel extends JPanel

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 13 of 38

public flavourPanel()

JComboBox b=new JComboBox()

jcbaddItem(ldquovanillardquo)

jcbaddItem(ldquochocolaterdquo)

add(jcb)

3 Attempt any four of the following Marks 16

a) Example the use of prepared statement with example 4

(Explanation-2 Marks Example-2 Marks)

Ans PrepareStatement ()

The preparedStatement() method creates a PreparedStatement object and returns it as a return

value The Prepared statement object is used to execute dynamic SQL statement against the

databaseA dynamic SQL statement is a statement in which some of the parameters in the

statement are unknown when the statement is created The parameter is placed into the SQL

statement as they are determined by the application When all the parameters are specified for the

SQL statement the dynamic SQL statement will be executed just as a static statement is executed

To create a dynamic SQL statement that takes a first name and last name as parameters use the

following code

try

String sql=rdquoSelect from temployeerdquo + ldquowhere Firstname=rdquo + ldquoand Lastname=rdquo

PreparedStatement p=connectionpreparedStatement(sql)

Catch(SQLException e)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 14 of 38

b) List any four differences between AWT and swing 4

(Any four points ndash 1 Mark each)

Ans

Swing AWT

It uses javaxswing package It uses javaapplet package

It uses JApplet class It uses Applet class

Swing is light weight component AWT is heavy weight component

It does not have add() method to add

control

It has add() method to add control

AWT provides less features than

swing

Swing has variety of component amp

features which is not in AWT

Awt has huge collection of classes amp

interfaces

Swing has bigger collection of classes

amp interfaces than AWT

AWT has predefined formats of

appearance amp behavior of component

Swing provides a facility of different

appearance amp behavior of the same

component

c) List four interfaces in javaxservlet package 4

(Any four points ndash 1 Mark each)

Ans Following are the interfaces in javaxservlet package

1 Servlet All servlets must implement the Servlet interface It declares the init( ) service( )

and destroy( ) methods that are called by the server during the life cycle of a servlet

2 ServletConfig The ServletContextinterface is implemented by the server It enables servlets

to obtain information about their environment

3 ServletContext The ServletContextinterface is implemented by the server It enables

servlets to obtain information about their environment

4 ServletRequest The ServletRequestinterface is implemented by the server It enables a

servlet to obtain information about a client request

5 ServletResponse The ServletResponseinterface is implemented by the server It enables a

servlet to formulate a response for a client

6 SingleThreadModel This interface is used to indicate that only a single thread will execute

the service( ) method of a servlet at a given time It defines no constants and declares no

methods

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 15 of 38

d) Give the use of ImageIcon class with example 4

(Explanation ndash 2 Marks Example- 2 Marks)

Ans In Swing icons are encapsulated by the ImageIconclass which paints an icon from an

image Two of its constructors are shown here

ImageIcon(String filename)

ImageIcon(URL url)

The first form uses the image in the file named filename The second form uses the

image in the resource identified by url

The ImageIconclass implements the Icon interface that declares the methods

As follows

Method Description

intgetIconHeight( ) Returns the height of the iconin pixels

intgetIconWidth( ) Returns the width of the iconin pixels

voidpaintIcon(Component comp Graphics gintx inty)Paints the icon at position x y onthe

graphics context g Additionalinformation about the paintoperation can be provided in comp

Example

import javaawt

import javaxswing

ltapplet code=JLabelDemo width=250 height=150gt

ltappletgt

public class JLabelDemo extends JApplet

public void init()

Get content pane

Container contentPane = getContentPane()

Create an icon

ImageIcon ii = new ImageIcon(francegif)

Create a label

JLabeljl = new JLabel(France ii JLabelCENTER)

Add label to the content pane

contentPaneadd(jl)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 16 of 38

e) Give the use of URL class along with syntax of constructors of URL class 4

(Use - 2 Marks Any two Constructor - 1 Mark each)

Ans The URL provides a reasonably intelligible form to uniquely identify or address information on the

Internet URLs are ubiquitous every browser uses them to identify information on the Web In

fact the Web is really just that same old Internet with all of its resources addressed as URLs plus

HTML

Javas URL class has several constructors One commonly used form specifies the URL with a

string that is identical to what you see displayed in a browser

1 URL(String urlSpecifier)

The next two forms of the constructor allow you to break up the URL into its componentparts

2 URL(String protocolName String hostName intport String path)

3 URL(String protocolName String hostName String path)

Another frequently used constructor allows you to use an existing URL as a referencecontext and

then create a new URL from that context Although this sounds a littlecontorted its really quite

easy and useful

4 URL(URL urlObj String urlSpecifier)

4 A) Attempt any three of the following Marks 12

a) Give the use of following methods of statement interface 4

i) executeQuery( ) ii) execute Update ( )

(Each method ndash 2 Marks)

Ans i) executeQuery()

The executeQuery() method of the statement object enables you to send SQL select statement to

the database and to receive result from the database Executing a query in effect sends a SQL

select statement to the database and returns the appropriate results back in the Resultset object

The executeQuery() method takes a SQL select statement as a parameter and returns a ResultSet

object that contains all the records that match the select statements criteria

ii) executeUpdate()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 17 of 38

The executeUpdate() method of the Statement object enables you to execute SQL update

statements such as delete insert and update The method takes a String containing the SQL update

statement and returns an integers that determines how many records were affected by the SQL

statement

b) Define Layout Manager Describe the use of GridLayout Manager 4

(Layout manager- 2 Marks Use-2 Marks)

Ans Each Container object has a layout manager associated with it A layout manager

is an instance of any class that implements the LayoutManagerinterface The layout

manager is set by the setLayout( ) method If no call to setLayout( ) is made then the

default layout manager is used Whenever a container is resized (or sized for the first

time) the layout manager is used to position each of the components within it

The setLayout( ) method has the following general form

voidsetLayout(LayoutManagerlayoutObj)

GridLayoutManager

GridLayout lays out components in a two-dimensional grid When you instantiate

a GridLayout you define the number of rows and columns The constructors

supported by GridLayoutare shown here

GridLayout( )

GridLayout(intnumRows intnumColumns)

GridLayout(intnumRows intnumColumns inthorz intvert)

c) Explain the use of cookies with example 4

(Explanation - 2 Marks Example - 2 Marks any one)

Ans Cookie is a small piece of information that is passed back and forth in the HTTP request and

response Even though a cookie can be created on the client side using some scripting language

such as JavaScript it is usually created by the server resource such as a Servlet The Cookies sent

by the server when the client requests another page from the same application In Servlet

programming a cookie is represented by a Cookie class in the javaxservlethttp package You can

create a cookie by calling the Cookie class constructor and passing two string objects the name

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 18 of 38

and value of the cookie For instance the following code creates a cookie object called c1The

cookie has the name ldquomyCookierdquo and value of rdquosecretrdquo

Cookie c1=new Cookie(ldquomyCookierdquordquosecretrdquo)

You then can add the cookie to the http response using addCookie method of the

HTTPServletResponse interfaceResponseaddCookie(c1)

Program for Add cookies

import javaio

importjavaxservlet

importjavaxservlethttp

public class AddCookieServlet extends HttpServlet

public void doPost(HttpServletRequest requestHttpServletResponse response)

throwsServletException IOException

Get parameter from HTTP request

String data = requestgetParameter(data)

Create cookie

Cookie cookie = new Cookie(MyCookie data)

Add cookie to HTTP response

responseaddCookie(cookie)

Write output to browser

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgtMyCookie has been set to)

pwprintln(data)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 19 of 38

pwclose()

OR

Program for Get Cookies

import javaio

importjavaxservlet

importjavaxservlethttp

public class GetCookiesServlet extends HttpServlet

public void doGet(HttpServletRequest requestHttpServletResponse response)

throwsServletException IOException

Get cookies from header of HTTP request

Cookie[] cookies = requestgetCookies()

Display these cookies

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgt)

for(inti = 0 iltcookieslength i++)

String name = cookies[i]getName()

String value = cookies[i]getValue()

pwprintln(name = + name +

value = + value)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 20 of 38

pwclose()

d) Give steps to create simple servlet with example 4

(Steps- 2 Marks Any one Example ndash 2 Marks)

Ans Steps 1) Write a java servet code

Steps 2) Compile Servet by setting classpath with servlet-api library

Step 3) Copy the class servlet file in web apps classpath directory

Steps 4) Open the webxml open it and add servlet tag and sevlet mapping tag

Steps 5) Start web server(apche tomcat)

Steps 6) Browse servlet using java compatible browser like IE

Example shows to start create a file named WelcomeServletjava that contains the following

program

import javaio

importjavaxservlet

public class WelcomeServletDemo extends GenericServlet

public void service(ServletRequestrequestServletResponse response) throws

ServletExceptionIOException

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgtWelcome to Servlet)

pwclose()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 21 of 38

B) Attempt any one of the following Marks 6

a) Describe the two ndashtier and three ndashtier database design of JDBC API with neat diagram

(Explanation of Two-tier-2 Marks and Three-tier-2 Marks Diagram ndash 1 Mark each)

Ans Two Tier Architecture

In a two tier model a java application is designed to interact directly with the database

Application functionality is divided into these two layers

1) Application Layer Including the JDBC driver business logic and user interface

2) Database Layer including RDBMS

The interface to the database is handled by the Java Database Connectivity(JDBC) Driver

appropriate to the particularly database management system being accessed The JDBC Driver

passes SQL statements to the database and returns the results of those statements to the

application

A clientserver configuration is the special case of the two tier model where the database is

located on another machine referred to as the server The application runs on the client machine

which is connected to the server over a network Commonly the network is an Intranet using

dedicated database servers to support multiple clients but it can just as easily be the internet

Three Tier Architecture-

In the three tier model the client typically sends requests to an application server forming the

middle tier The application server interprets these requests and formats the necessary SQL

statement to fulfill

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 22 of 38

These requests and sends them to the database The database process the SQL statements and

sends result back to the application server which then sends them to the client

Following are some advantages of Three-tier architecture

1 Performance can be improved by separating the application server and database server

2 Business logic is clearly separated from the database

3 Client application can use a simple protocol such as CGI to access services

The three-tier model show in following fig is a common in web application In this scenario the

client tier is frequently implemented in a browse on a client machine the middle tier is

implemented in a web server with a Servlet engine and the database management system runs on

a dedicated database server

Following are the main components of three tier architecture

1 Client Tier - Typically this is thin presentation layer that may be implemented using a web

browser

2 Middle Tier - This tier handles the business or application logic This may be implemented

using a Servlet engine such as Tomcat or an application server such as JBOSS The JDBC

driver also resides in this layer

3 Data source layer This component includes the RDBMS

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 23 of 38

b) Write servlet which shows how many times user has visited the page in session

(Any Correct Logic ndash4 Marks Syntax ndash 2 Marks)

Ans import javaio

import javaxservlet

import javaxservlethttp

public class Session Travker extends HttpServlet

public void doGet(HttpServletRequest req HttpServletResponse res) throws ServletException

IOException

ressetContentType(ldquotexthtmlrdquo)

PrintWriter out = resgetWriter()

HttpSession session = reqgetSession(true)

Integer count= (Integer)sessiongetValue(ldquotrackercountrdquo)

if(count== null) count=new Interger(1)

else count = new Interger(count intValue() +1)

sessionputValue(ldquotrackercountrdquocount)

outprintln(ldquoltHTMLgtltHEADgtltTITLEgtSession TrackerltTITLEgtltHEADgtrdquo)

outprintln(ldquoltBODYgtltH1gtSession Tracking DemoltH1gtrdquo)

outprintln(ldquoYou have visited this pagerdquo +count +((countintValue() == 1)rdquotimerdquo

ldquotimesrdquo))outprinln(ltPgtrdquo)

outprintln(ldquoltH2gtSesssion dataltH2gtrdquo)

String[] names = sessiongetValueNames()

for(int i=0 ilt nameslength i++)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 24 of 38

outprintln(names[i] + ldquo rdquo + sessiongetvalue(names[i])+ ldquoltBRgtrdquo)

outprintln(ldquoltBODYgtltHTMLgtrdquo)

5 Attempt any two of the following Marks 16

a) Write a program to display all records from Employee table from database using

JDBC

(Assume suitable data for table- Load driver create connection execute Query - 1 Mark

each Display data- 3 Marks Syntax ndash 2 Marks)

Ans import javasql

import javasqlStatement

import javaapplet

import javaawt

public class DisplayTable

public static void main( String args[])

RsultSet rs

Connection conn

try

String s1

ClassforName(sun jdbcodbcJdbcOdbcDriver)

Systemoutprintln(Connecting to a selected database)

String url=rdquojdbcodbcabcrdquo

conn = DriverManagergetConnection(DB_URL USER PASS)

Systemoutprintln(Connected database successfully)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 25 of 38

Systemoutprintln(Creating statement)

stmt = conncreateStatement()

sql = SELECT FROM Employee

ResultSet rs = stmtexecuteQuery(sql)

Tables fields assumed are id first last age

while(rsnext())

int id = rsgetInt(id)

int age = rsgetInt(age)

String first = rsgetString(first)

String last = rsgetString(last)

Systemoutprint(ID + id)

Systemoutprint( Age + age)

Systemoutprint( First + first)

Systemoutprintln( Last + last)

rsclose()

catch(SQLException se)

Handle errors for JDBC

seprintStackTrace()

catch(Exception e)

Handle errors for ClassforName

eprintStackTrace()

finally

finally block used to close resources

try

if(stmt=null)

connclose()

catch(SQLException se)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 26 of 38

b) Define the term

i) Reserved socket ii) proxy server

iii) Datagram iv) URL connection 4

(Each term- 2 Marks)

Ans i) Reserved socket

A socket is one end-point of a two-way communication link between two programs running on

the network Socket classes are used to represent the connection between a client program and a

server program

Reserved socket The socket which are reserved for specific protocols for communication

purpose are known as reseved sockets

TCPIP uses or reserves the lower 1024 ports for specific protocols

Example port number 23 is for Telnet 25 is for smtp 21 is for ftp 13 for daytime 110 for pop3

and so on Protocol decides how a client should interact with the port

ii) Proxy server

A proxy server is a computer that offers a computer network service to allow clients to make

indirect network connections to other network services A client connects to the proxy server

then requests a connection file or other resource available on a different server The proxy

provides the resource either by connecting to the specified server or by serving it from a cache In

some cases the proxy may alter the clients request or the servers response for various purposes

Purposes of the proxy servers

To keep machines behind it anonymous mainly for security

To speed up access to resources (using caching) Web proxies are commonly used to

cache web pages from a web server

To prevent downloading the same content multiple times (and save bandwidth)

To log audit usage eg to provide company employee Internet usage reporting

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 27 of 38

To scan transmitted content for malware before delivery

To scan outbound content eg for data loss prevention

iii) Datagram

Datagrams are bundles of information passed between machines They are somewhat like a hard

throw from a well-trained but blindfolded catcher to the third baseman Once the datagram has

been released to its intended target there is no assurance that it will arrive or even that

someone will be there to catch it Likewise when the datagram is received there is no

assurance that it hasnrsquot been damaged in transit or that whoever sent it is still there to receive a

response

Java implements datagrams on top of the UDP protocol by using two classes

The DatagramPacket object is the data container while the DatagramSocket is the mechanism

used to send or receive the DatagramPackets

iv) URL connection

URLConnection is a general-purpose class for accessing the attributes of a remote resource

Once you make a connection to a remote server you can use URLConnection to inspect the

Properties of the remote object before actually transporting it locally These attributes are

exposed by the HTTP protocol specification and as such only make sense for URL objects

that are using the HTTP protocol

URLConnection defines several methods

int getContentLength( )

String getContentType( )

long getDate( )

long getExpiration( )

String getHeaderField(int idx)

long getLastModified( )

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 28 of 38

c) Write a program to display three text fields and a button below to all an Applet Insert

the integer valuer from three text fields After pressing the button the background colour

of applet will be changed as per the RGB combination of the values given in the text field

(Correct logic - 6 Marks Syntax - 2 Marks)

4

Ans import javaawt

import javaawtevent

import javaapplet

ltapplet code=rdquoClrclassrdquo width=250 heigth=250gtltappletgt

public class Clrextends Applet implements ActionListener

int r g b

TextField t1t2t3

Button b1

Color c1

public void init()

t1= new TextField(5)

t2= new TextField(8)

t3= new TextField(11)

b1 = new Button(ldquo Set Colorrdquo)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 29 of 38

add(t1)

add(t2)

add(t3)

add(b1)

b1addActionListener(this)

public void void paint( )

setBackground(c1)

public void actionPerformed(ActionEvent ae)

r=IntegerparseInt(t1getText())

g=IntegerparseInt(t2getText())

b=IntegerparseInt(t3getText())

c1= new Color(rgb)

repaint()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 30 of 38

6) Attempt any four of the following Marks 16

a) How to check how many fonts are available in the computer system 4

Explain with example

(Explanation -2 Marks Example-2 Marks)

Ans When working with fonts often you need to know which fonts are available on your machine To

ontain this information you can use the getAvailableFontFamilyNames() method defined by the

GraphicsEnvironment classIt is shown here

String[ ] getAvailableFontFamilyNames( )

This method returns an array of string that contains the names of the available font families

Since this methods is members of GraphicsEnvironment you need a GraphicsEnvironment

reference to call itYou can obtain this reference by using the getlocalGrahicsEnvironmet() static

method which is derfined by GraphicsEnvironmentIt is shown here

static GraphicsEnvironment getLocalGraphicsEnvironment( )

Here is an applet that shown how to obtain the names of the available font families

ltapplet code=rdquoAllFontsrdquo width=500 height=100gt

ltappletgt

import javaapplet

import javaawt

public class AllFonts extends Applet

public void paint(Graphics g)

string fonts= ldquo rdquo

stirng allFontsList[]

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 31 of 38

GraphicsEnvironment t = GraphicsEnvironmentgetLocalGraphicsEnvironment()

allFontList = tgetAvailableFontFamilyNames()

for(int i= 0 ilt allFontsListlength i++)

fonts= fonts + allFontList[i] + ldquo rdquo

gdrawString(msg416)

b) Explain following check box class methods with appropriate example 4

i) Void setLable (String str) ii) Boolean getState ( )

(Explanation of each method-1 Marks Example-2 Marks)

Ans

i) void setLable(String str)

This method is used to set the label of check box

ii) Boolean getState()

This method is used to retrieve the current state of a check box It returns the value either true or

false depends on check box is selected or not

Example

Demonstrate check boxes

import javaawt

import javaawtevent

import javaapplet

ltapplet code=CheckboxDemo width=250 height=200gt

ltappletgt

public class CheckboxDemo extends Applet implements ItemListener

String msg =

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 32 of 38

Checkbox winXP winVista solaris mac

public void init()

winXP = new Checkbox(Windows XP null true)

mac = new Checkbox()

macsetLable(ldquoMac OSrdquo)

add(winXP)

add(mac)

winXPaddItemListener(this)

macaddItemListener(this)

public void itemStateChanged(ItemEvent ie)

repaint()

Display current state of the check boxes

public void paint(Graphics g)

msg = Current state

gdrawString(msg 6 80)

msg = Windows XP + winXPgetState()

gdrawString(msg 6 100)

msg = Mac OS + macgetState()

gdrawString(msg 6 120)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 33 of 38

c) Explain the techniques of session tracking management

(Any four techniques with explanation- 1 Mark each)

Ans Session tracking Techniques

1 User Authorization

Users can be authorized to use the web application in different ways Basic concept is that the

user will provide username and password to login to the application Based on that the user can

be identified and the session can be maintained

2 Hidden Fields

ltINPUT TYPE=rdquohiddenrdquo NAME=rdquotechnologyrdquo VALUE=rdquoservletrdquogt

Hidden fields like the above can be inserted in the webpages and information can be sent to the

server for session tracking These fields are not visible directly to the user but can be viewed

using view source option from the browsers This type doesnrsquot need any special configuration

from the browser of server and by default available to use for session tracking This cannot be

used for session tracking when the conversation included static resources lik html pages

3 URL Rewriting

Original URL httpserverportservletServletName

ewritten URL httpserverportservletServletNamesessionid=7456

When a request is made additional parameter is appended with the url In general added

additional parameter will be sessionid or sometimes the userid It will suffice to track the

session This type of session tracking doesnrsquot need any special support from the browser

Disadvantage is implementing this type of session tracking is tedious We need to keep track of

the parameter as a chain link until the conversation completes and also should make sure that

the parameter doesnrsquot clash with other application parameters

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 34 of 38

4 Cookies

Cookies are the mostly used technology for session tracking Cookie is a key value pair of

information sent by the server to the browser This should be saved by the browser in its space

in the client computer Whenever the browser sends a request to that server it sends the cookie

along with it Then the server can identify the client using the cookie

In java following is the source code snippet to create a cookie

Cookie cookie = new Cookie (ldquouserIDrdquo ldquo7456Prime)

resaddCookie(cookie)

5 Session tracking API

Session tracking API is built on top of the first four methods This is inorder to help the

developer to minimize the overhead of session tracking This type of session tracking is

provided by the underlying technology Lets take the java servlet example Then the servlet

container manages the session tracking task and the user need not do it explicitly using the java

servlets This is the best of all methods because all the management and errors related to

session tracking will be taken care of by the container itself

d) Give sequential steps for JTree in swing with example

(Steps- 2 Marks any small Example- 2 Marks)

Ans Steps for JTree

Atree is a component that presents a hierarchical view of data The user has the ability to

expand or collapse individual subtrees in this display Trees are implemented in Swing by

the JTree class

Here are the steps to follow to use a tree

1 Create an instance of JTree

2 Create a JScrollPane and specify the tree as the object to be scrolled

3 Add the tree to the scroll pane

4 Add the scroll pane to the content pane

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 35 of 38

Example

Demonstrate JTree

import javaawt

import javaxswingevent

import javaxswing

import javaxswingtree

ltapplet code=JTreeDemo width=400 height=200gt

ltappletgt

public class JTreeDemo extends JApplet

JTree tree

JLabel jlab

public void init()

try

SwingUtilitiesinvokeAndWait(

new Runnable()

public void run()

makeGUI()

)

catch (Exception exc)

Systemoutprintln(Cant create because of + exc)

private void makeGUI()

Create top node of tree

DefaultMutableTreeNode top = new DefaultMutableTreeNode(Options)

Create subtree of A

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 36 of 38

DefaultMutableTreeNode a = new DefaultMutableTreeNode(A)

topadd(a)

DefaultMutableTreeNode a1 = new DefaultMutableTreeNode(A1)

aadd(a1)

DefaultMutableTreeNode a2 = new DefaultMutableTreeNode(A2)

aadd(a2)

Create subtree of B

DefaultMutableTreeNode b = new DefaultMutableTreeNode(B)

topadd(b)

DefaultMutableTreeNode b1 = new DefaultMutableTreeNode(B1)

badd(b1)

DefaultMutableTreeNode b2 = new DefaultMutableTreeNode(B2)

badd(b2)

DefaultMutableTreeNode b3 = new DefaultMutableTreeNode(B3)

badd(b3)

Create the tree

tree = new JTree(top)

Add the tree to a scroll pane

JScrollPane jsp = new JScrollPane(tree)

Add the scroll pane to the content pane

add(jsp)

Add the label to the content pane

jlab = new JLabel()

add(jlab BorderLayoutSOUTH)

Handle tree selection events

treeaddTreeSelectionListener(new TreeSelectionListener()

public void valueChanged(TreeSelectionEvent tse)

jlabsetText(Selection is + tsegetPath())

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 37 of 38

e) Draw and explain the life cycle of servlet

(Explanation ndash 3 Marks Diagram -1 Marks)

Ans Three methods are central to the life cycle of a servlet

These are init( ) service( ) and destroy( )

They are implemented by every servlet and are invoked at specific times by the server Let

us consider a typical user scenario to understand when these methods are called

First assume that a user enters a Uniform Resource Locator (URL) to a web browser

The browser then generates an HTTP request for this URL This request is then sent to the

appropriate server

Second this HTTP request is received by the web server The server maps this request to

a particular servlet The servlet is dynamically retrieved and loaded into the address space

of the server

Third the server invokes the init( ) method of the servlet This method is invoked only

when the servlet is first loaded into memory It is possible to pass initialization parameters

to the servlet so it may configure itself

Fourth the server invokes the service( ) method of the servlet This method is called to

process the HTTP request You will see that it is possible for the servlet to read data that has

been provided in the HTTP request It may also formulate an HTTP response for the client

The servlet remains in the serverrsquos address space and is available to process any other

HTTP requests received from clients The service( ) method is called for each HTTP request

Finally the server may decide to unload the servlet from its memory The algorithms by

which this determination is made are specific to each server The server calls the destroy( )

method to relinquish any resources such as file handles that are allocated for the servlet

Important data may be saved to a persistent store The memory allocated for the servlet and

its objects can then be garbage collected

A servlet life cycle can be defined as the entire process from its creation till the destruction The

following are the paths followed by a servlet

The servlet is initialized by calling the init () method

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 38 of 38

The servlet calls service() method to process a clients request

The servlet is terminated by calling the destroy() method

Finally servlet is garbage collected by the garbage collector of the JVM

Initialization

(Load Resources)

Services

(Accept Requests)

Destruction

(Unload Resources)

Servlet

Request

Response

Page 10: AJP

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 10 of 38

After the waiting stages of server a client instantiates a Socket object It also specifies the

server name and port number to which it gets connected

3 The constructor of the Socket class tries to connect the client to the specified server and port

number If the communication is established the client has a Socket object which is capable

of communicating with the server

4 On server side the accept () method returns a reference to a new socket on the server that is

connected to the clientrsquos socket

Once the connection are established communication occur using IO streams Each socket has

both an Outputstream and InputStreams

As we know that the TCP is a two way communication protocol So data can be sent across

both streams at the same time

Two constructors used to create client socket

Socket (String hostnameint port)

Creates a socket connection the localhost to name host and port

Socket(InetAddress ipAddressint port)

Creates a socket using pre existing InetAddress object and a port

A socket can be examined at any time for the address and port information associated with it

InetAddress getInetAddress()

Int getPort()

Int getLocalPort()

Once the socket object has been created it can be examined to gain access to ip and op streams

associated with it

Example (optional)

import javanet

import javaio

class abc

public static void main(String args[])throws Exception

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 11 of 38

int c

Socket s=new socket(ldquointericnetrdquo43)

InputStream in=sgetInputStream()

OutputStream out=sgetOutputStream()

String str=(argslength==0rdquoOsbornecomrdquo)

byte buf[]=strgetBytes()outwrite(buf)

while((c=inread())=-1)

Systemoutprintln(char)c)

sclose()

c) Give sequential steps to use JTabbedPane in an Applet with example

(Steps- 4Marks any one Example- 4Marks)

Ans The general procedure to use a tabbed pane in an applet is

1) Create a JtabbedPane object

2) Call addTab() to add to the pane

3) Repeat step 2 for each tab

4) Add the tabbed pane to the content pane of the applet

Example

import javaxswing

ltapplet code=rdquoJTabbedPaneDemordquo width=350

Height=250gt

ltappletgt

public class JTabbedPaneDemo extends JApplet

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 12 of 38

public void init()

JTabbedPane jtp= new JTabbedPane()

jtpaddTab(ldquocitiesrdquonew citiesPanel())

jtpaddTab(ldquocolorsrdquonew colorsPanel())

jtpaddTab(ldquoFlavourrdquonew flavourPanel())

getContentPane()add(jtp)

class citiespanel extends JPanel

Public citiesPanel()

JButton b1=new Button(ldquoNew Yorkrdquo)

add(b1)

JButton b2=new Button(ldquolondonrdquo)

add(b2)

class colorpanel extends JPanel

Public colorPanel()

JCheckBox cb1=new JCheckBox(ldquoredrdquo)

add(cb1)

JCheckBox cb2=new JCheckBox (ldquogreenrdquo)

add(cb2)

class flavourpanel extends JPanel

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 13 of 38

public flavourPanel()

JComboBox b=new JComboBox()

jcbaddItem(ldquovanillardquo)

jcbaddItem(ldquochocolaterdquo)

add(jcb)

3 Attempt any four of the following Marks 16

a) Example the use of prepared statement with example 4

(Explanation-2 Marks Example-2 Marks)

Ans PrepareStatement ()

The preparedStatement() method creates a PreparedStatement object and returns it as a return

value The Prepared statement object is used to execute dynamic SQL statement against the

databaseA dynamic SQL statement is a statement in which some of the parameters in the

statement are unknown when the statement is created The parameter is placed into the SQL

statement as they are determined by the application When all the parameters are specified for the

SQL statement the dynamic SQL statement will be executed just as a static statement is executed

To create a dynamic SQL statement that takes a first name and last name as parameters use the

following code

try

String sql=rdquoSelect from temployeerdquo + ldquowhere Firstname=rdquo + ldquoand Lastname=rdquo

PreparedStatement p=connectionpreparedStatement(sql)

Catch(SQLException e)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 14 of 38

b) List any four differences between AWT and swing 4

(Any four points ndash 1 Mark each)

Ans

Swing AWT

It uses javaxswing package It uses javaapplet package

It uses JApplet class It uses Applet class

Swing is light weight component AWT is heavy weight component

It does not have add() method to add

control

It has add() method to add control

AWT provides less features than

swing

Swing has variety of component amp

features which is not in AWT

Awt has huge collection of classes amp

interfaces

Swing has bigger collection of classes

amp interfaces than AWT

AWT has predefined formats of

appearance amp behavior of component

Swing provides a facility of different

appearance amp behavior of the same

component

c) List four interfaces in javaxservlet package 4

(Any four points ndash 1 Mark each)

Ans Following are the interfaces in javaxservlet package

1 Servlet All servlets must implement the Servlet interface It declares the init( ) service( )

and destroy( ) methods that are called by the server during the life cycle of a servlet

2 ServletConfig The ServletContextinterface is implemented by the server It enables servlets

to obtain information about their environment

3 ServletContext The ServletContextinterface is implemented by the server It enables

servlets to obtain information about their environment

4 ServletRequest The ServletRequestinterface is implemented by the server It enables a

servlet to obtain information about a client request

5 ServletResponse The ServletResponseinterface is implemented by the server It enables a

servlet to formulate a response for a client

6 SingleThreadModel This interface is used to indicate that only a single thread will execute

the service( ) method of a servlet at a given time It defines no constants and declares no

methods

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 15 of 38

d) Give the use of ImageIcon class with example 4

(Explanation ndash 2 Marks Example- 2 Marks)

Ans In Swing icons are encapsulated by the ImageIconclass which paints an icon from an

image Two of its constructors are shown here

ImageIcon(String filename)

ImageIcon(URL url)

The first form uses the image in the file named filename The second form uses the

image in the resource identified by url

The ImageIconclass implements the Icon interface that declares the methods

As follows

Method Description

intgetIconHeight( ) Returns the height of the iconin pixels

intgetIconWidth( ) Returns the width of the iconin pixels

voidpaintIcon(Component comp Graphics gintx inty)Paints the icon at position x y onthe

graphics context g Additionalinformation about the paintoperation can be provided in comp

Example

import javaawt

import javaxswing

ltapplet code=JLabelDemo width=250 height=150gt

ltappletgt

public class JLabelDemo extends JApplet

public void init()

Get content pane

Container contentPane = getContentPane()

Create an icon

ImageIcon ii = new ImageIcon(francegif)

Create a label

JLabeljl = new JLabel(France ii JLabelCENTER)

Add label to the content pane

contentPaneadd(jl)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 16 of 38

e) Give the use of URL class along with syntax of constructors of URL class 4

(Use - 2 Marks Any two Constructor - 1 Mark each)

Ans The URL provides a reasonably intelligible form to uniquely identify or address information on the

Internet URLs are ubiquitous every browser uses them to identify information on the Web In

fact the Web is really just that same old Internet with all of its resources addressed as URLs plus

HTML

Javas URL class has several constructors One commonly used form specifies the URL with a

string that is identical to what you see displayed in a browser

1 URL(String urlSpecifier)

The next two forms of the constructor allow you to break up the URL into its componentparts

2 URL(String protocolName String hostName intport String path)

3 URL(String protocolName String hostName String path)

Another frequently used constructor allows you to use an existing URL as a referencecontext and

then create a new URL from that context Although this sounds a littlecontorted its really quite

easy and useful

4 URL(URL urlObj String urlSpecifier)

4 A) Attempt any three of the following Marks 12

a) Give the use of following methods of statement interface 4

i) executeQuery( ) ii) execute Update ( )

(Each method ndash 2 Marks)

Ans i) executeQuery()

The executeQuery() method of the statement object enables you to send SQL select statement to

the database and to receive result from the database Executing a query in effect sends a SQL

select statement to the database and returns the appropriate results back in the Resultset object

The executeQuery() method takes a SQL select statement as a parameter and returns a ResultSet

object that contains all the records that match the select statements criteria

ii) executeUpdate()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 17 of 38

The executeUpdate() method of the Statement object enables you to execute SQL update

statements such as delete insert and update The method takes a String containing the SQL update

statement and returns an integers that determines how many records were affected by the SQL

statement

b) Define Layout Manager Describe the use of GridLayout Manager 4

(Layout manager- 2 Marks Use-2 Marks)

Ans Each Container object has a layout manager associated with it A layout manager

is an instance of any class that implements the LayoutManagerinterface The layout

manager is set by the setLayout( ) method If no call to setLayout( ) is made then the

default layout manager is used Whenever a container is resized (or sized for the first

time) the layout manager is used to position each of the components within it

The setLayout( ) method has the following general form

voidsetLayout(LayoutManagerlayoutObj)

GridLayoutManager

GridLayout lays out components in a two-dimensional grid When you instantiate

a GridLayout you define the number of rows and columns The constructors

supported by GridLayoutare shown here

GridLayout( )

GridLayout(intnumRows intnumColumns)

GridLayout(intnumRows intnumColumns inthorz intvert)

c) Explain the use of cookies with example 4

(Explanation - 2 Marks Example - 2 Marks any one)

Ans Cookie is a small piece of information that is passed back and forth in the HTTP request and

response Even though a cookie can be created on the client side using some scripting language

such as JavaScript it is usually created by the server resource such as a Servlet The Cookies sent

by the server when the client requests another page from the same application In Servlet

programming a cookie is represented by a Cookie class in the javaxservlethttp package You can

create a cookie by calling the Cookie class constructor and passing two string objects the name

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 18 of 38

and value of the cookie For instance the following code creates a cookie object called c1The

cookie has the name ldquomyCookierdquo and value of rdquosecretrdquo

Cookie c1=new Cookie(ldquomyCookierdquordquosecretrdquo)

You then can add the cookie to the http response using addCookie method of the

HTTPServletResponse interfaceResponseaddCookie(c1)

Program for Add cookies

import javaio

importjavaxservlet

importjavaxservlethttp

public class AddCookieServlet extends HttpServlet

public void doPost(HttpServletRequest requestHttpServletResponse response)

throwsServletException IOException

Get parameter from HTTP request

String data = requestgetParameter(data)

Create cookie

Cookie cookie = new Cookie(MyCookie data)

Add cookie to HTTP response

responseaddCookie(cookie)

Write output to browser

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgtMyCookie has been set to)

pwprintln(data)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 19 of 38

pwclose()

OR

Program for Get Cookies

import javaio

importjavaxservlet

importjavaxservlethttp

public class GetCookiesServlet extends HttpServlet

public void doGet(HttpServletRequest requestHttpServletResponse response)

throwsServletException IOException

Get cookies from header of HTTP request

Cookie[] cookies = requestgetCookies()

Display these cookies

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgt)

for(inti = 0 iltcookieslength i++)

String name = cookies[i]getName()

String value = cookies[i]getValue()

pwprintln(name = + name +

value = + value)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 20 of 38

pwclose()

d) Give steps to create simple servlet with example 4

(Steps- 2 Marks Any one Example ndash 2 Marks)

Ans Steps 1) Write a java servet code

Steps 2) Compile Servet by setting classpath with servlet-api library

Step 3) Copy the class servlet file in web apps classpath directory

Steps 4) Open the webxml open it and add servlet tag and sevlet mapping tag

Steps 5) Start web server(apche tomcat)

Steps 6) Browse servlet using java compatible browser like IE

Example shows to start create a file named WelcomeServletjava that contains the following

program

import javaio

importjavaxservlet

public class WelcomeServletDemo extends GenericServlet

public void service(ServletRequestrequestServletResponse response) throws

ServletExceptionIOException

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgtWelcome to Servlet)

pwclose()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 21 of 38

B) Attempt any one of the following Marks 6

a) Describe the two ndashtier and three ndashtier database design of JDBC API with neat diagram

(Explanation of Two-tier-2 Marks and Three-tier-2 Marks Diagram ndash 1 Mark each)

Ans Two Tier Architecture

In a two tier model a java application is designed to interact directly with the database

Application functionality is divided into these two layers

1) Application Layer Including the JDBC driver business logic and user interface

2) Database Layer including RDBMS

The interface to the database is handled by the Java Database Connectivity(JDBC) Driver

appropriate to the particularly database management system being accessed The JDBC Driver

passes SQL statements to the database and returns the results of those statements to the

application

A clientserver configuration is the special case of the two tier model where the database is

located on another machine referred to as the server The application runs on the client machine

which is connected to the server over a network Commonly the network is an Intranet using

dedicated database servers to support multiple clients but it can just as easily be the internet

Three Tier Architecture-

In the three tier model the client typically sends requests to an application server forming the

middle tier The application server interprets these requests and formats the necessary SQL

statement to fulfill

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 22 of 38

These requests and sends them to the database The database process the SQL statements and

sends result back to the application server which then sends them to the client

Following are some advantages of Three-tier architecture

1 Performance can be improved by separating the application server and database server

2 Business logic is clearly separated from the database

3 Client application can use a simple protocol such as CGI to access services

The three-tier model show in following fig is a common in web application In this scenario the

client tier is frequently implemented in a browse on a client machine the middle tier is

implemented in a web server with a Servlet engine and the database management system runs on

a dedicated database server

Following are the main components of three tier architecture

1 Client Tier - Typically this is thin presentation layer that may be implemented using a web

browser

2 Middle Tier - This tier handles the business or application logic This may be implemented

using a Servlet engine such as Tomcat or an application server such as JBOSS The JDBC

driver also resides in this layer

3 Data source layer This component includes the RDBMS

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 23 of 38

b) Write servlet which shows how many times user has visited the page in session

(Any Correct Logic ndash4 Marks Syntax ndash 2 Marks)

Ans import javaio

import javaxservlet

import javaxservlethttp

public class Session Travker extends HttpServlet

public void doGet(HttpServletRequest req HttpServletResponse res) throws ServletException

IOException

ressetContentType(ldquotexthtmlrdquo)

PrintWriter out = resgetWriter()

HttpSession session = reqgetSession(true)

Integer count= (Integer)sessiongetValue(ldquotrackercountrdquo)

if(count== null) count=new Interger(1)

else count = new Interger(count intValue() +1)

sessionputValue(ldquotrackercountrdquocount)

outprintln(ldquoltHTMLgtltHEADgtltTITLEgtSession TrackerltTITLEgtltHEADgtrdquo)

outprintln(ldquoltBODYgtltH1gtSession Tracking DemoltH1gtrdquo)

outprintln(ldquoYou have visited this pagerdquo +count +((countintValue() == 1)rdquotimerdquo

ldquotimesrdquo))outprinln(ltPgtrdquo)

outprintln(ldquoltH2gtSesssion dataltH2gtrdquo)

String[] names = sessiongetValueNames()

for(int i=0 ilt nameslength i++)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 24 of 38

outprintln(names[i] + ldquo rdquo + sessiongetvalue(names[i])+ ldquoltBRgtrdquo)

outprintln(ldquoltBODYgtltHTMLgtrdquo)

5 Attempt any two of the following Marks 16

a) Write a program to display all records from Employee table from database using

JDBC

(Assume suitable data for table- Load driver create connection execute Query - 1 Mark

each Display data- 3 Marks Syntax ndash 2 Marks)

Ans import javasql

import javasqlStatement

import javaapplet

import javaawt

public class DisplayTable

public static void main( String args[])

RsultSet rs

Connection conn

try

String s1

ClassforName(sun jdbcodbcJdbcOdbcDriver)

Systemoutprintln(Connecting to a selected database)

String url=rdquojdbcodbcabcrdquo

conn = DriverManagergetConnection(DB_URL USER PASS)

Systemoutprintln(Connected database successfully)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 25 of 38

Systemoutprintln(Creating statement)

stmt = conncreateStatement()

sql = SELECT FROM Employee

ResultSet rs = stmtexecuteQuery(sql)

Tables fields assumed are id first last age

while(rsnext())

int id = rsgetInt(id)

int age = rsgetInt(age)

String first = rsgetString(first)

String last = rsgetString(last)

Systemoutprint(ID + id)

Systemoutprint( Age + age)

Systemoutprint( First + first)

Systemoutprintln( Last + last)

rsclose()

catch(SQLException se)

Handle errors for JDBC

seprintStackTrace()

catch(Exception e)

Handle errors for ClassforName

eprintStackTrace()

finally

finally block used to close resources

try

if(stmt=null)

connclose()

catch(SQLException se)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 26 of 38

b) Define the term

i) Reserved socket ii) proxy server

iii) Datagram iv) URL connection 4

(Each term- 2 Marks)

Ans i) Reserved socket

A socket is one end-point of a two-way communication link between two programs running on

the network Socket classes are used to represent the connection between a client program and a

server program

Reserved socket The socket which are reserved for specific protocols for communication

purpose are known as reseved sockets

TCPIP uses or reserves the lower 1024 ports for specific protocols

Example port number 23 is for Telnet 25 is for smtp 21 is for ftp 13 for daytime 110 for pop3

and so on Protocol decides how a client should interact with the port

ii) Proxy server

A proxy server is a computer that offers a computer network service to allow clients to make

indirect network connections to other network services A client connects to the proxy server

then requests a connection file or other resource available on a different server The proxy

provides the resource either by connecting to the specified server or by serving it from a cache In

some cases the proxy may alter the clients request or the servers response for various purposes

Purposes of the proxy servers

To keep machines behind it anonymous mainly for security

To speed up access to resources (using caching) Web proxies are commonly used to

cache web pages from a web server

To prevent downloading the same content multiple times (and save bandwidth)

To log audit usage eg to provide company employee Internet usage reporting

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 27 of 38

To scan transmitted content for malware before delivery

To scan outbound content eg for data loss prevention

iii) Datagram

Datagrams are bundles of information passed between machines They are somewhat like a hard

throw from a well-trained but blindfolded catcher to the third baseman Once the datagram has

been released to its intended target there is no assurance that it will arrive or even that

someone will be there to catch it Likewise when the datagram is received there is no

assurance that it hasnrsquot been damaged in transit or that whoever sent it is still there to receive a

response

Java implements datagrams on top of the UDP protocol by using two classes

The DatagramPacket object is the data container while the DatagramSocket is the mechanism

used to send or receive the DatagramPackets

iv) URL connection

URLConnection is a general-purpose class for accessing the attributes of a remote resource

Once you make a connection to a remote server you can use URLConnection to inspect the

Properties of the remote object before actually transporting it locally These attributes are

exposed by the HTTP protocol specification and as such only make sense for URL objects

that are using the HTTP protocol

URLConnection defines several methods

int getContentLength( )

String getContentType( )

long getDate( )

long getExpiration( )

String getHeaderField(int idx)

long getLastModified( )

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 28 of 38

c) Write a program to display three text fields and a button below to all an Applet Insert

the integer valuer from three text fields After pressing the button the background colour

of applet will be changed as per the RGB combination of the values given in the text field

(Correct logic - 6 Marks Syntax - 2 Marks)

4

Ans import javaawt

import javaawtevent

import javaapplet

ltapplet code=rdquoClrclassrdquo width=250 heigth=250gtltappletgt

public class Clrextends Applet implements ActionListener

int r g b

TextField t1t2t3

Button b1

Color c1

public void init()

t1= new TextField(5)

t2= new TextField(8)

t3= new TextField(11)

b1 = new Button(ldquo Set Colorrdquo)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 29 of 38

add(t1)

add(t2)

add(t3)

add(b1)

b1addActionListener(this)

public void void paint( )

setBackground(c1)

public void actionPerformed(ActionEvent ae)

r=IntegerparseInt(t1getText())

g=IntegerparseInt(t2getText())

b=IntegerparseInt(t3getText())

c1= new Color(rgb)

repaint()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 30 of 38

6) Attempt any four of the following Marks 16

a) How to check how many fonts are available in the computer system 4

Explain with example

(Explanation -2 Marks Example-2 Marks)

Ans When working with fonts often you need to know which fonts are available on your machine To

ontain this information you can use the getAvailableFontFamilyNames() method defined by the

GraphicsEnvironment classIt is shown here

String[ ] getAvailableFontFamilyNames( )

This method returns an array of string that contains the names of the available font families

Since this methods is members of GraphicsEnvironment you need a GraphicsEnvironment

reference to call itYou can obtain this reference by using the getlocalGrahicsEnvironmet() static

method which is derfined by GraphicsEnvironmentIt is shown here

static GraphicsEnvironment getLocalGraphicsEnvironment( )

Here is an applet that shown how to obtain the names of the available font families

ltapplet code=rdquoAllFontsrdquo width=500 height=100gt

ltappletgt

import javaapplet

import javaawt

public class AllFonts extends Applet

public void paint(Graphics g)

string fonts= ldquo rdquo

stirng allFontsList[]

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 31 of 38

GraphicsEnvironment t = GraphicsEnvironmentgetLocalGraphicsEnvironment()

allFontList = tgetAvailableFontFamilyNames()

for(int i= 0 ilt allFontsListlength i++)

fonts= fonts + allFontList[i] + ldquo rdquo

gdrawString(msg416)

b) Explain following check box class methods with appropriate example 4

i) Void setLable (String str) ii) Boolean getState ( )

(Explanation of each method-1 Marks Example-2 Marks)

Ans

i) void setLable(String str)

This method is used to set the label of check box

ii) Boolean getState()

This method is used to retrieve the current state of a check box It returns the value either true or

false depends on check box is selected or not

Example

Demonstrate check boxes

import javaawt

import javaawtevent

import javaapplet

ltapplet code=CheckboxDemo width=250 height=200gt

ltappletgt

public class CheckboxDemo extends Applet implements ItemListener

String msg =

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 32 of 38

Checkbox winXP winVista solaris mac

public void init()

winXP = new Checkbox(Windows XP null true)

mac = new Checkbox()

macsetLable(ldquoMac OSrdquo)

add(winXP)

add(mac)

winXPaddItemListener(this)

macaddItemListener(this)

public void itemStateChanged(ItemEvent ie)

repaint()

Display current state of the check boxes

public void paint(Graphics g)

msg = Current state

gdrawString(msg 6 80)

msg = Windows XP + winXPgetState()

gdrawString(msg 6 100)

msg = Mac OS + macgetState()

gdrawString(msg 6 120)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 33 of 38

c) Explain the techniques of session tracking management

(Any four techniques with explanation- 1 Mark each)

Ans Session tracking Techniques

1 User Authorization

Users can be authorized to use the web application in different ways Basic concept is that the

user will provide username and password to login to the application Based on that the user can

be identified and the session can be maintained

2 Hidden Fields

ltINPUT TYPE=rdquohiddenrdquo NAME=rdquotechnologyrdquo VALUE=rdquoservletrdquogt

Hidden fields like the above can be inserted in the webpages and information can be sent to the

server for session tracking These fields are not visible directly to the user but can be viewed

using view source option from the browsers This type doesnrsquot need any special configuration

from the browser of server and by default available to use for session tracking This cannot be

used for session tracking when the conversation included static resources lik html pages

3 URL Rewriting

Original URL httpserverportservletServletName

ewritten URL httpserverportservletServletNamesessionid=7456

When a request is made additional parameter is appended with the url In general added

additional parameter will be sessionid or sometimes the userid It will suffice to track the

session This type of session tracking doesnrsquot need any special support from the browser

Disadvantage is implementing this type of session tracking is tedious We need to keep track of

the parameter as a chain link until the conversation completes and also should make sure that

the parameter doesnrsquot clash with other application parameters

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 34 of 38

4 Cookies

Cookies are the mostly used technology for session tracking Cookie is a key value pair of

information sent by the server to the browser This should be saved by the browser in its space

in the client computer Whenever the browser sends a request to that server it sends the cookie

along with it Then the server can identify the client using the cookie

In java following is the source code snippet to create a cookie

Cookie cookie = new Cookie (ldquouserIDrdquo ldquo7456Prime)

resaddCookie(cookie)

5 Session tracking API

Session tracking API is built on top of the first four methods This is inorder to help the

developer to minimize the overhead of session tracking This type of session tracking is

provided by the underlying technology Lets take the java servlet example Then the servlet

container manages the session tracking task and the user need not do it explicitly using the java

servlets This is the best of all methods because all the management and errors related to

session tracking will be taken care of by the container itself

d) Give sequential steps for JTree in swing with example

(Steps- 2 Marks any small Example- 2 Marks)

Ans Steps for JTree

Atree is a component that presents a hierarchical view of data The user has the ability to

expand or collapse individual subtrees in this display Trees are implemented in Swing by

the JTree class

Here are the steps to follow to use a tree

1 Create an instance of JTree

2 Create a JScrollPane and specify the tree as the object to be scrolled

3 Add the tree to the scroll pane

4 Add the scroll pane to the content pane

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 35 of 38

Example

Demonstrate JTree

import javaawt

import javaxswingevent

import javaxswing

import javaxswingtree

ltapplet code=JTreeDemo width=400 height=200gt

ltappletgt

public class JTreeDemo extends JApplet

JTree tree

JLabel jlab

public void init()

try

SwingUtilitiesinvokeAndWait(

new Runnable()

public void run()

makeGUI()

)

catch (Exception exc)

Systemoutprintln(Cant create because of + exc)

private void makeGUI()

Create top node of tree

DefaultMutableTreeNode top = new DefaultMutableTreeNode(Options)

Create subtree of A

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 36 of 38

DefaultMutableTreeNode a = new DefaultMutableTreeNode(A)

topadd(a)

DefaultMutableTreeNode a1 = new DefaultMutableTreeNode(A1)

aadd(a1)

DefaultMutableTreeNode a2 = new DefaultMutableTreeNode(A2)

aadd(a2)

Create subtree of B

DefaultMutableTreeNode b = new DefaultMutableTreeNode(B)

topadd(b)

DefaultMutableTreeNode b1 = new DefaultMutableTreeNode(B1)

badd(b1)

DefaultMutableTreeNode b2 = new DefaultMutableTreeNode(B2)

badd(b2)

DefaultMutableTreeNode b3 = new DefaultMutableTreeNode(B3)

badd(b3)

Create the tree

tree = new JTree(top)

Add the tree to a scroll pane

JScrollPane jsp = new JScrollPane(tree)

Add the scroll pane to the content pane

add(jsp)

Add the label to the content pane

jlab = new JLabel()

add(jlab BorderLayoutSOUTH)

Handle tree selection events

treeaddTreeSelectionListener(new TreeSelectionListener()

public void valueChanged(TreeSelectionEvent tse)

jlabsetText(Selection is + tsegetPath())

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 37 of 38

e) Draw and explain the life cycle of servlet

(Explanation ndash 3 Marks Diagram -1 Marks)

Ans Three methods are central to the life cycle of a servlet

These are init( ) service( ) and destroy( )

They are implemented by every servlet and are invoked at specific times by the server Let

us consider a typical user scenario to understand when these methods are called

First assume that a user enters a Uniform Resource Locator (URL) to a web browser

The browser then generates an HTTP request for this URL This request is then sent to the

appropriate server

Second this HTTP request is received by the web server The server maps this request to

a particular servlet The servlet is dynamically retrieved and loaded into the address space

of the server

Third the server invokes the init( ) method of the servlet This method is invoked only

when the servlet is first loaded into memory It is possible to pass initialization parameters

to the servlet so it may configure itself

Fourth the server invokes the service( ) method of the servlet This method is called to

process the HTTP request You will see that it is possible for the servlet to read data that has

been provided in the HTTP request It may also formulate an HTTP response for the client

The servlet remains in the serverrsquos address space and is available to process any other

HTTP requests received from clients The service( ) method is called for each HTTP request

Finally the server may decide to unload the servlet from its memory The algorithms by

which this determination is made are specific to each server The server calls the destroy( )

method to relinquish any resources such as file handles that are allocated for the servlet

Important data may be saved to a persistent store The memory allocated for the servlet and

its objects can then be garbage collected

A servlet life cycle can be defined as the entire process from its creation till the destruction The

following are the paths followed by a servlet

The servlet is initialized by calling the init () method

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 38 of 38

The servlet calls service() method to process a clients request

The servlet is terminated by calling the destroy() method

Finally servlet is garbage collected by the garbage collector of the JVM

Initialization

(Load Resources)

Services

(Accept Requests)

Destruction

(Unload Resources)

Servlet

Request

Response

Page 11: AJP

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 11 of 38

int c

Socket s=new socket(ldquointericnetrdquo43)

InputStream in=sgetInputStream()

OutputStream out=sgetOutputStream()

String str=(argslength==0rdquoOsbornecomrdquo)

byte buf[]=strgetBytes()outwrite(buf)

while((c=inread())=-1)

Systemoutprintln(char)c)

sclose()

c) Give sequential steps to use JTabbedPane in an Applet with example

(Steps- 4Marks any one Example- 4Marks)

Ans The general procedure to use a tabbed pane in an applet is

1) Create a JtabbedPane object

2) Call addTab() to add to the pane

3) Repeat step 2 for each tab

4) Add the tabbed pane to the content pane of the applet

Example

import javaxswing

ltapplet code=rdquoJTabbedPaneDemordquo width=350

Height=250gt

ltappletgt

public class JTabbedPaneDemo extends JApplet

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 12 of 38

public void init()

JTabbedPane jtp= new JTabbedPane()

jtpaddTab(ldquocitiesrdquonew citiesPanel())

jtpaddTab(ldquocolorsrdquonew colorsPanel())

jtpaddTab(ldquoFlavourrdquonew flavourPanel())

getContentPane()add(jtp)

class citiespanel extends JPanel

Public citiesPanel()

JButton b1=new Button(ldquoNew Yorkrdquo)

add(b1)

JButton b2=new Button(ldquolondonrdquo)

add(b2)

class colorpanel extends JPanel

Public colorPanel()

JCheckBox cb1=new JCheckBox(ldquoredrdquo)

add(cb1)

JCheckBox cb2=new JCheckBox (ldquogreenrdquo)

add(cb2)

class flavourpanel extends JPanel

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 13 of 38

public flavourPanel()

JComboBox b=new JComboBox()

jcbaddItem(ldquovanillardquo)

jcbaddItem(ldquochocolaterdquo)

add(jcb)

3 Attempt any four of the following Marks 16

a) Example the use of prepared statement with example 4

(Explanation-2 Marks Example-2 Marks)

Ans PrepareStatement ()

The preparedStatement() method creates a PreparedStatement object and returns it as a return

value The Prepared statement object is used to execute dynamic SQL statement against the

databaseA dynamic SQL statement is a statement in which some of the parameters in the

statement are unknown when the statement is created The parameter is placed into the SQL

statement as they are determined by the application When all the parameters are specified for the

SQL statement the dynamic SQL statement will be executed just as a static statement is executed

To create a dynamic SQL statement that takes a first name and last name as parameters use the

following code

try

String sql=rdquoSelect from temployeerdquo + ldquowhere Firstname=rdquo + ldquoand Lastname=rdquo

PreparedStatement p=connectionpreparedStatement(sql)

Catch(SQLException e)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 14 of 38

b) List any four differences between AWT and swing 4

(Any four points ndash 1 Mark each)

Ans

Swing AWT

It uses javaxswing package It uses javaapplet package

It uses JApplet class It uses Applet class

Swing is light weight component AWT is heavy weight component

It does not have add() method to add

control

It has add() method to add control

AWT provides less features than

swing

Swing has variety of component amp

features which is not in AWT

Awt has huge collection of classes amp

interfaces

Swing has bigger collection of classes

amp interfaces than AWT

AWT has predefined formats of

appearance amp behavior of component

Swing provides a facility of different

appearance amp behavior of the same

component

c) List four interfaces in javaxservlet package 4

(Any four points ndash 1 Mark each)

Ans Following are the interfaces in javaxservlet package

1 Servlet All servlets must implement the Servlet interface It declares the init( ) service( )

and destroy( ) methods that are called by the server during the life cycle of a servlet

2 ServletConfig The ServletContextinterface is implemented by the server It enables servlets

to obtain information about their environment

3 ServletContext The ServletContextinterface is implemented by the server It enables

servlets to obtain information about their environment

4 ServletRequest The ServletRequestinterface is implemented by the server It enables a

servlet to obtain information about a client request

5 ServletResponse The ServletResponseinterface is implemented by the server It enables a

servlet to formulate a response for a client

6 SingleThreadModel This interface is used to indicate that only a single thread will execute

the service( ) method of a servlet at a given time It defines no constants and declares no

methods

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 15 of 38

d) Give the use of ImageIcon class with example 4

(Explanation ndash 2 Marks Example- 2 Marks)

Ans In Swing icons are encapsulated by the ImageIconclass which paints an icon from an

image Two of its constructors are shown here

ImageIcon(String filename)

ImageIcon(URL url)

The first form uses the image in the file named filename The second form uses the

image in the resource identified by url

The ImageIconclass implements the Icon interface that declares the methods

As follows

Method Description

intgetIconHeight( ) Returns the height of the iconin pixels

intgetIconWidth( ) Returns the width of the iconin pixels

voidpaintIcon(Component comp Graphics gintx inty)Paints the icon at position x y onthe

graphics context g Additionalinformation about the paintoperation can be provided in comp

Example

import javaawt

import javaxswing

ltapplet code=JLabelDemo width=250 height=150gt

ltappletgt

public class JLabelDemo extends JApplet

public void init()

Get content pane

Container contentPane = getContentPane()

Create an icon

ImageIcon ii = new ImageIcon(francegif)

Create a label

JLabeljl = new JLabel(France ii JLabelCENTER)

Add label to the content pane

contentPaneadd(jl)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 16 of 38

e) Give the use of URL class along with syntax of constructors of URL class 4

(Use - 2 Marks Any two Constructor - 1 Mark each)

Ans The URL provides a reasonably intelligible form to uniquely identify or address information on the

Internet URLs are ubiquitous every browser uses them to identify information on the Web In

fact the Web is really just that same old Internet with all of its resources addressed as URLs plus

HTML

Javas URL class has several constructors One commonly used form specifies the URL with a

string that is identical to what you see displayed in a browser

1 URL(String urlSpecifier)

The next two forms of the constructor allow you to break up the URL into its componentparts

2 URL(String protocolName String hostName intport String path)

3 URL(String protocolName String hostName String path)

Another frequently used constructor allows you to use an existing URL as a referencecontext and

then create a new URL from that context Although this sounds a littlecontorted its really quite

easy and useful

4 URL(URL urlObj String urlSpecifier)

4 A) Attempt any three of the following Marks 12

a) Give the use of following methods of statement interface 4

i) executeQuery( ) ii) execute Update ( )

(Each method ndash 2 Marks)

Ans i) executeQuery()

The executeQuery() method of the statement object enables you to send SQL select statement to

the database and to receive result from the database Executing a query in effect sends a SQL

select statement to the database and returns the appropriate results back in the Resultset object

The executeQuery() method takes a SQL select statement as a parameter and returns a ResultSet

object that contains all the records that match the select statements criteria

ii) executeUpdate()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 17 of 38

The executeUpdate() method of the Statement object enables you to execute SQL update

statements such as delete insert and update The method takes a String containing the SQL update

statement and returns an integers that determines how many records were affected by the SQL

statement

b) Define Layout Manager Describe the use of GridLayout Manager 4

(Layout manager- 2 Marks Use-2 Marks)

Ans Each Container object has a layout manager associated with it A layout manager

is an instance of any class that implements the LayoutManagerinterface The layout

manager is set by the setLayout( ) method If no call to setLayout( ) is made then the

default layout manager is used Whenever a container is resized (or sized for the first

time) the layout manager is used to position each of the components within it

The setLayout( ) method has the following general form

voidsetLayout(LayoutManagerlayoutObj)

GridLayoutManager

GridLayout lays out components in a two-dimensional grid When you instantiate

a GridLayout you define the number of rows and columns The constructors

supported by GridLayoutare shown here

GridLayout( )

GridLayout(intnumRows intnumColumns)

GridLayout(intnumRows intnumColumns inthorz intvert)

c) Explain the use of cookies with example 4

(Explanation - 2 Marks Example - 2 Marks any one)

Ans Cookie is a small piece of information that is passed back and forth in the HTTP request and

response Even though a cookie can be created on the client side using some scripting language

such as JavaScript it is usually created by the server resource such as a Servlet The Cookies sent

by the server when the client requests another page from the same application In Servlet

programming a cookie is represented by a Cookie class in the javaxservlethttp package You can

create a cookie by calling the Cookie class constructor and passing two string objects the name

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 18 of 38

and value of the cookie For instance the following code creates a cookie object called c1The

cookie has the name ldquomyCookierdquo and value of rdquosecretrdquo

Cookie c1=new Cookie(ldquomyCookierdquordquosecretrdquo)

You then can add the cookie to the http response using addCookie method of the

HTTPServletResponse interfaceResponseaddCookie(c1)

Program for Add cookies

import javaio

importjavaxservlet

importjavaxservlethttp

public class AddCookieServlet extends HttpServlet

public void doPost(HttpServletRequest requestHttpServletResponse response)

throwsServletException IOException

Get parameter from HTTP request

String data = requestgetParameter(data)

Create cookie

Cookie cookie = new Cookie(MyCookie data)

Add cookie to HTTP response

responseaddCookie(cookie)

Write output to browser

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgtMyCookie has been set to)

pwprintln(data)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 19 of 38

pwclose()

OR

Program for Get Cookies

import javaio

importjavaxservlet

importjavaxservlethttp

public class GetCookiesServlet extends HttpServlet

public void doGet(HttpServletRequest requestHttpServletResponse response)

throwsServletException IOException

Get cookies from header of HTTP request

Cookie[] cookies = requestgetCookies()

Display these cookies

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgt)

for(inti = 0 iltcookieslength i++)

String name = cookies[i]getName()

String value = cookies[i]getValue()

pwprintln(name = + name +

value = + value)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 20 of 38

pwclose()

d) Give steps to create simple servlet with example 4

(Steps- 2 Marks Any one Example ndash 2 Marks)

Ans Steps 1) Write a java servet code

Steps 2) Compile Servet by setting classpath with servlet-api library

Step 3) Copy the class servlet file in web apps classpath directory

Steps 4) Open the webxml open it and add servlet tag and sevlet mapping tag

Steps 5) Start web server(apche tomcat)

Steps 6) Browse servlet using java compatible browser like IE

Example shows to start create a file named WelcomeServletjava that contains the following

program

import javaio

importjavaxservlet

public class WelcomeServletDemo extends GenericServlet

public void service(ServletRequestrequestServletResponse response) throws

ServletExceptionIOException

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgtWelcome to Servlet)

pwclose()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 21 of 38

B) Attempt any one of the following Marks 6

a) Describe the two ndashtier and three ndashtier database design of JDBC API with neat diagram

(Explanation of Two-tier-2 Marks and Three-tier-2 Marks Diagram ndash 1 Mark each)

Ans Two Tier Architecture

In a two tier model a java application is designed to interact directly with the database

Application functionality is divided into these two layers

1) Application Layer Including the JDBC driver business logic and user interface

2) Database Layer including RDBMS

The interface to the database is handled by the Java Database Connectivity(JDBC) Driver

appropriate to the particularly database management system being accessed The JDBC Driver

passes SQL statements to the database and returns the results of those statements to the

application

A clientserver configuration is the special case of the two tier model where the database is

located on another machine referred to as the server The application runs on the client machine

which is connected to the server over a network Commonly the network is an Intranet using

dedicated database servers to support multiple clients but it can just as easily be the internet

Three Tier Architecture-

In the three tier model the client typically sends requests to an application server forming the

middle tier The application server interprets these requests and formats the necessary SQL

statement to fulfill

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 22 of 38

These requests and sends them to the database The database process the SQL statements and

sends result back to the application server which then sends them to the client

Following are some advantages of Three-tier architecture

1 Performance can be improved by separating the application server and database server

2 Business logic is clearly separated from the database

3 Client application can use a simple protocol such as CGI to access services

The three-tier model show in following fig is a common in web application In this scenario the

client tier is frequently implemented in a browse on a client machine the middle tier is

implemented in a web server with a Servlet engine and the database management system runs on

a dedicated database server

Following are the main components of three tier architecture

1 Client Tier - Typically this is thin presentation layer that may be implemented using a web

browser

2 Middle Tier - This tier handles the business or application logic This may be implemented

using a Servlet engine such as Tomcat or an application server such as JBOSS The JDBC

driver also resides in this layer

3 Data source layer This component includes the RDBMS

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 23 of 38

b) Write servlet which shows how many times user has visited the page in session

(Any Correct Logic ndash4 Marks Syntax ndash 2 Marks)

Ans import javaio

import javaxservlet

import javaxservlethttp

public class Session Travker extends HttpServlet

public void doGet(HttpServletRequest req HttpServletResponse res) throws ServletException

IOException

ressetContentType(ldquotexthtmlrdquo)

PrintWriter out = resgetWriter()

HttpSession session = reqgetSession(true)

Integer count= (Integer)sessiongetValue(ldquotrackercountrdquo)

if(count== null) count=new Interger(1)

else count = new Interger(count intValue() +1)

sessionputValue(ldquotrackercountrdquocount)

outprintln(ldquoltHTMLgtltHEADgtltTITLEgtSession TrackerltTITLEgtltHEADgtrdquo)

outprintln(ldquoltBODYgtltH1gtSession Tracking DemoltH1gtrdquo)

outprintln(ldquoYou have visited this pagerdquo +count +((countintValue() == 1)rdquotimerdquo

ldquotimesrdquo))outprinln(ltPgtrdquo)

outprintln(ldquoltH2gtSesssion dataltH2gtrdquo)

String[] names = sessiongetValueNames()

for(int i=0 ilt nameslength i++)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 24 of 38

outprintln(names[i] + ldquo rdquo + sessiongetvalue(names[i])+ ldquoltBRgtrdquo)

outprintln(ldquoltBODYgtltHTMLgtrdquo)

5 Attempt any two of the following Marks 16

a) Write a program to display all records from Employee table from database using

JDBC

(Assume suitable data for table- Load driver create connection execute Query - 1 Mark

each Display data- 3 Marks Syntax ndash 2 Marks)

Ans import javasql

import javasqlStatement

import javaapplet

import javaawt

public class DisplayTable

public static void main( String args[])

RsultSet rs

Connection conn

try

String s1

ClassforName(sun jdbcodbcJdbcOdbcDriver)

Systemoutprintln(Connecting to a selected database)

String url=rdquojdbcodbcabcrdquo

conn = DriverManagergetConnection(DB_URL USER PASS)

Systemoutprintln(Connected database successfully)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 25 of 38

Systemoutprintln(Creating statement)

stmt = conncreateStatement()

sql = SELECT FROM Employee

ResultSet rs = stmtexecuteQuery(sql)

Tables fields assumed are id first last age

while(rsnext())

int id = rsgetInt(id)

int age = rsgetInt(age)

String first = rsgetString(first)

String last = rsgetString(last)

Systemoutprint(ID + id)

Systemoutprint( Age + age)

Systemoutprint( First + first)

Systemoutprintln( Last + last)

rsclose()

catch(SQLException se)

Handle errors for JDBC

seprintStackTrace()

catch(Exception e)

Handle errors for ClassforName

eprintStackTrace()

finally

finally block used to close resources

try

if(stmt=null)

connclose()

catch(SQLException se)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 26 of 38

b) Define the term

i) Reserved socket ii) proxy server

iii) Datagram iv) URL connection 4

(Each term- 2 Marks)

Ans i) Reserved socket

A socket is one end-point of a two-way communication link between two programs running on

the network Socket classes are used to represent the connection between a client program and a

server program

Reserved socket The socket which are reserved for specific protocols for communication

purpose are known as reseved sockets

TCPIP uses or reserves the lower 1024 ports for specific protocols

Example port number 23 is for Telnet 25 is for smtp 21 is for ftp 13 for daytime 110 for pop3

and so on Protocol decides how a client should interact with the port

ii) Proxy server

A proxy server is a computer that offers a computer network service to allow clients to make

indirect network connections to other network services A client connects to the proxy server

then requests a connection file or other resource available on a different server The proxy

provides the resource either by connecting to the specified server or by serving it from a cache In

some cases the proxy may alter the clients request or the servers response for various purposes

Purposes of the proxy servers

To keep machines behind it anonymous mainly for security

To speed up access to resources (using caching) Web proxies are commonly used to

cache web pages from a web server

To prevent downloading the same content multiple times (and save bandwidth)

To log audit usage eg to provide company employee Internet usage reporting

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 27 of 38

To scan transmitted content for malware before delivery

To scan outbound content eg for data loss prevention

iii) Datagram

Datagrams are bundles of information passed between machines They are somewhat like a hard

throw from a well-trained but blindfolded catcher to the third baseman Once the datagram has

been released to its intended target there is no assurance that it will arrive or even that

someone will be there to catch it Likewise when the datagram is received there is no

assurance that it hasnrsquot been damaged in transit or that whoever sent it is still there to receive a

response

Java implements datagrams on top of the UDP protocol by using two classes

The DatagramPacket object is the data container while the DatagramSocket is the mechanism

used to send or receive the DatagramPackets

iv) URL connection

URLConnection is a general-purpose class for accessing the attributes of a remote resource

Once you make a connection to a remote server you can use URLConnection to inspect the

Properties of the remote object before actually transporting it locally These attributes are

exposed by the HTTP protocol specification and as such only make sense for URL objects

that are using the HTTP protocol

URLConnection defines several methods

int getContentLength( )

String getContentType( )

long getDate( )

long getExpiration( )

String getHeaderField(int idx)

long getLastModified( )

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 28 of 38

c) Write a program to display three text fields and a button below to all an Applet Insert

the integer valuer from three text fields After pressing the button the background colour

of applet will be changed as per the RGB combination of the values given in the text field

(Correct logic - 6 Marks Syntax - 2 Marks)

4

Ans import javaawt

import javaawtevent

import javaapplet

ltapplet code=rdquoClrclassrdquo width=250 heigth=250gtltappletgt

public class Clrextends Applet implements ActionListener

int r g b

TextField t1t2t3

Button b1

Color c1

public void init()

t1= new TextField(5)

t2= new TextField(8)

t3= new TextField(11)

b1 = new Button(ldquo Set Colorrdquo)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 29 of 38

add(t1)

add(t2)

add(t3)

add(b1)

b1addActionListener(this)

public void void paint( )

setBackground(c1)

public void actionPerformed(ActionEvent ae)

r=IntegerparseInt(t1getText())

g=IntegerparseInt(t2getText())

b=IntegerparseInt(t3getText())

c1= new Color(rgb)

repaint()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 30 of 38

6) Attempt any four of the following Marks 16

a) How to check how many fonts are available in the computer system 4

Explain with example

(Explanation -2 Marks Example-2 Marks)

Ans When working with fonts often you need to know which fonts are available on your machine To

ontain this information you can use the getAvailableFontFamilyNames() method defined by the

GraphicsEnvironment classIt is shown here

String[ ] getAvailableFontFamilyNames( )

This method returns an array of string that contains the names of the available font families

Since this methods is members of GraphicsEnvironment you need a GraphicsEnvironment

reference to call itYou can obtain this reference by using the getlocalGrahicsEnvironmet() static

method which is derfined by GraphicsEnvironmentIt is shown here

static GraphicsEnvironment getLocalGraphicsEnvironment( )

Here is an applet that shown how to obtain the names of the available font families

ltapplet code=rdquoAllFontsrdquo width=500 height=100gt

ltappletgt

import javaapplet

import javaawt

public class AllFonts extends Applet

public void paint(Graphics g)

string fonts= ldquo rdquo

stirng allFontsList[]

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 31 of 38

GraphicsEnvironment t = GraphicsEnvironmentgetLocalGraphicsEnvironment()

allFontList = tgetAvailableFontFamilyNames()

for(int i= 0 ilt allFontsListlength i++)

fonts= fonts + allFontList[i] + ldquo rdquo

gdrawString(msg416)

b) Explain following check box class methods with appropriate example 4

i) Void setLable (String str) ii) Boolean getState ( )

(Explanation of each method-1 Marks Example-2 Marks)

Ans

i) void setLable(String str)

This method is used to set the label of check box

ii) Boolean getState()

This method is used to retrieve the current state of a check box It returns the value either true or

false depends on check box is selected or not

Example

Demonstrate check boxes

import javaawt

import javaawtevent

import javaapplet

ltapplet code=CheckboxDemo width=250 height=200gt

ltappletgt

public class CheckboxDemo extends Applet implements ItemListener

String msg =

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 32 of 38

Checkbox winXP winVista solaris mac

public void init()

winXP = new Checkbox(Windows XP null true)

mac = new Checkbox()

macsetLable(ldquoMac OSrdquo)

add(winXP)

add(mac)

winXPaddItemListener(this)

macaddItemListener(this)

public void itemStateChanged(ItemEvent ie)

repaint()

Display current state of the check boxes

public void paint(Graphics g)

msg = Current state

gdrawString(msg 6 80)

msg = Windows XP + winXPgetState()

gdrawString(msg 6 100)

msg = Mac OS + macgetState()

gdrawString(msg 6 120)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 33 of 38

c) Explain the techniques of session tracking management

(Any four techniques with explanation- 1 Mark each)

Ans Session tracking Techniques

1 User Authorization

Users can be authorized to use the web application in different ways Basic concept is that the

user will provide username and password to login to the application Based on that the user can

be identified and the session can be maintained

2 Hidden Fields

ltINPUT TYPE=rdquohiddenrdquo NAME=rdquotechnologyrdquo VALUE=rdquoservletrdquogt

Hidden fields like the above can be inserted in the webpages and information can be sent to the

server for session tracking These fields are not visible directly to the user but can be viewed

using view source option from the browsers This type doesnrsquot need any special configuration

from the browser of server and by default available to use for session tracking This cannot be

used for session tracking when the conversation included static resources lik html pages

3 URL Rewriting

Original URL httpserverportservletServletName

ewritten URL httpserverportservletServletNamesessionid=7456

When a request is made additional parameter is appended with the url In general added

additional parameter will be sessionid or sometimes the userid It will suffice to track the

session This type of session tracking doesnrsquot need any special support from the browser

Disadvantage is implementing this type of session tracking is tedious We need to keep track of

the parameter as a chain link until the conversation completes and also should make sure that

the parameter doesnrsquot clash with other application parameters

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 34 of 38

4 Cookies

Cookies are the mostly used technology for session tracking Cookie is a key value pair of

information sent by the server to the browser This should be saved by the browser in its space

in the client computer Whenever the browser sends a request to that server it sends the cookie

along with it Then the server can identify the client using the cookie

In java following is the source code snippet to create a cookie

Cookie cookie = new Cookie (ldquouserIDrdquo ldquo7456Prime)

resaddCookie(cookie)

5 Session tracking API

Session tracking API is built on top of the first four methods This is inorder to help the

developer to minimize the overhead of session tracking This type of session tracking is

provided by the underlying technology Lets take the java servlet example Then the servlet

container manages the session tracking task and the user need not do it explicitly using the java

servlets This is the best of all methods because all the management and errors related to

session tracking will be taken care of by the container itself

d) Give sequential steps for JTree in swing with example

(Steps- 2 Marks any small Example- 2 Marks)

Ans Steps for JTree

Atree is a component that presents a hierarchical view of data The user has the ability to

expand or collapse individual subtrees in this display Trees are implemented in Swing by

the JTree class

Here are the steps to follow to use a tree

1 Create an instance of JTree

2 Create a JScrollPane and specify the tree as the object to be scrolled

3 Add the tree to the scroll pane

4 Add the scroll pane to the content pane

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 35 of 38

Example

Demonstrate JTree

import javaawt

import javaxswingevent

import javaxswing

import javaxswingtree

ltapplet code=JTreeDemo width=400 height=200gt

ltappletgt

public class JTreeDemo extends JApplet

JTree tree

JLabel jlab

public void init()

try

SwingUtilitiesinvokeAndWait(

new Runnable()

public void run()

makeGUI()

)

catch (Exception exc)

Systemoutprintln(Cant create because of + exc)

private void makeGUI()

Create top node of tree

DefaultMutableTreeNode top = new DefaultMutableTreeNode(Options)

Create subtree of A

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 36 of 38

DefaultMutableTreeNode a = new DefaultMutableTreeNode(A)

topadd(a)

DefaultMutableTreeNode a1 = new DefaultMutableTreeNode(A1)

aadd(a1)

DefaultMutableTreeNode a2 = new DefaultMutableTreeNode(A2)

aadd(a2)

Create subtree of B

DefaultMutableTreeNode b = new DefaultMutableTreeNode(B)

topadd(b)

DefaultMutableTreeNode b1 = new DefaultMutableTreeNode(B1)

badd(b1)

DefaultMutableTreeNode b2 = new DefaultMutableTreeNode(B2)

badd(b2)

DefaultMutableTreeNode b3 = new DefaultMutableTreeNode(B3)

badd(b3)

Create the tree

tree = new JTree(top)

Add the tree to a scroll pane

JScrollPane jsp = new JScrollPane(tree)

Add the scroll pane to the content pane

add(jsp)

Add the label to the content pane

jlab = new JLabel()

add(jlab BorderLayoutSOUTH)

Handle tree selection events

treeaddTreeSelectionListener(new TreeSelectionListener()

public void valueChanged(TreeSelectionEvent tse)

jlabsetText(Selection is + tsegetPath())

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 37 of 38

e) Draw and explain the life cycle of servlet

(Explanation ndash 3 Marks Diagram -1 Marks)

Ans Three methods are central to the life cycle of a servlet

These are init( ) service( ) and destroy( )

They are implemented by every servlet and are invoked at specific times by the server Let

us consider a typical user scenario to understand when these methods are called

First assume that a user enters a Uniform Resource Locator (URL) to a web browser

The browser then generates an HTTP request for this URL This request is then sent to the

appropriate server

Second this HTTP request is received by the web server The server maps this request to

a particular servlet The servlet is dynamically retrieved and loaded into the address space

of the server

Third the server invokes the init( ) method of the servlet This method is invoked only

when the servlet is first loaded into memory It is possible to pass initialization parameters

to the servlet so it may configure itself

Fourth the server invokes the service( ) method of the servlet This method is called to

process the HTTP request You will see that it is possible for the servlet to read data that has

been provided in the HTTP request It may also formulate an HTTP response for the client

The servlet remains in the serverrsquos address space and is available to process any other

HTTP requests received from clients The service( ) method is called for each HTTP request

Finally the server may decide to unload the servlet from its memory The algorithms by

which this determination is made are specific to each server The server calls the destroy( )

method to relinquish any resources such as file handles that are allocated for the servlet

Important data may be saved to a persistent store The memory allocated for the servlet and

its objects can then be garbage collected

A servlet life cycle can be defined as the entire process from its creation till the destruction The

following are the paths followed by a servlet

The servlet is initialized by calling the init () method

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 38 of 38

The servlet calls service() method to process a clients request

The servlet is terminated by calling the destroy() method

Finally servlet is garbage collected by the garbage collector of the JVM

Initialization

(Load Resources)

Services

(Accept Requests)

Destruction

(Unload Resources)

Servlet

Request

Response

Page 12: AJP

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 12 of 38

public void init()

JTabbedPane jtp= new JTabbedPane()

jtpaddTab(ldquocitiesrdquonew citiesPanel())

jtpaddTab(ldquocolorsrdquonew colorsPanel())

jtpaddTab(ldquoFlavourrdquonew flavourPanel())

getContentPane()add(jtp)

class citiespanel extends JPanel

Public citiesPanel()

JButton b1=new Button(ldquoNew Yorkrdquo)

add(b1)

JButton b2=new Button(ldquolondonrdquo)

add(b2)

class colorpanel extends JPanel

Public colorPanel()

JCheckBox cb1=new JCheckBox(ldquoredrdquo)

add(cb1)

JCheckBox cb2=new JCheckBox (ldquogreenrdquo)

add(cb2)

class flavourpanel extends JPanel

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 13 of 38

public flavourPanel()

JComboBox b=new JComboBox()

jcbaddItem(ldquovanillardquo)

jcbaddItem(ldquochocolaterdquo)

add(jcb)

3 Attempt any four of the following Marks 16

a) Example the use of prepared statement with example 4

(Explanation-2 Marks Example-2 Marks)

Ans PrepareStatement ()

The preparedStatement() method creates a PreparedStatement object and returns it as a return

value The Prepared statement object is used to execute dynamic SQL statement against the

databaseA dynamic SQL statement is a statement in which some of the parameters in the

statement are unknown when the statement is created The parameter is placed into the SQL

statement as they are determined by the application When all the parameters are specified for the

SQL statement the dynamic SQL statement will be executed just as a static statement is executed

To create a dynamic SQL statement that takes a first name and last name as parameters use the

following code

try

String sql=rdquoSelect from temployeerdquo + ldquowhere Firstname=rdquo + ldquoand Lastname=rdquo

PreparedStatement p=connectionpreparedStatement(sql)

Catch(SQLException e)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 14 of 38

b) List any four differences between AWT and swing 4

(Any four points ndash 1 Mark each)

Ans

Swing AWT

It uses javaxswing package It uses javaapplet package

It uses JApplet class It uses Applet class

Swing is light weight component AWT is heavy weight component

It does not have add() method to add

control

It has add() method to add control

AWT provides less features than

swing

Swing has variety of component amp

features which is not in AWT

Awt has huge collection of classes amp

interfaces

Swing has bigger collection of classes

amp interfaces than AWT

AWT has predefined formats of

appearance amp behavior of component

Swing provides a facility of different

appearance amp behavior of the same

component

c) List four interfaces in javaxservlet package 4

(Any four points ndash 1 Mark each)

Ans Following are the interfaces in javaxservlet package

1 Servlet All servlets must implement the Servlet interface It declares the init( ) service( )

and destroy( ) methods that are called by the server during the life cycle of a servlet

2 ServletConfig The ServletContextinterface is implemented by the server It enables servlets

to obtain information about their environment

3 ServletContext The ServletContextinterface is implemented by the server It enables

servlets to obtain information about their environment

4 ServletRequest The ServletRequestinterface is implemented by the server It enables a

servlet to obtain information about a client request

5 ServletResponse The ServletResponseinterface is implemented by the server It enables a

servlet to formulate a response for a client

6 SingleThreadModel This interface is used to indicate that only a single thread will execute

the service( ) method of a servlet at a given time It defines no constants and declares no

methods

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 15 of 38

d) Give the use of ImageIcon class with example 4

(Explanation ndash 2 Marks Example- 2 Marks)

Ans In Swing icons are encapsulated by the ImageIconclass which paints an icon from an

image Two of its constructors are shown here

ImageIcon(String filename)

ImageIcon(URL url)

The first form uses the image in the file named filename The second form uses the

image in the resource identified by url

The ImageIconclass implements the Icon interface that declares the methods

As follows

Method Description

intgetIconHeight( ) Returns the height of the iconin pixels

intgetIconWidth( ) Returns the width of the iconin pixels

voidpaintIcon(Component comp Graphics gintx inty)Paints the icon at position x y onthe

graphics context g Additionalinformation about the paintoperation can be provided in comp

Example

import javaawt

import javaxswing

ltapplet code=JLabelDemo width=250 height=150gt

ltappletgt

public class JLabelDemo extends JApplet

public void init()

Get content pane

Container contentPane = getContentPane()

Create an icon

ImageIcon ii = new ImageIcon(francegif)

Create a label

JLabeljl = new JLabel(France ii JLabelCENTER)

Add label to the content pane

contentPaneadd(jl)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 16 of 38

e) Give the use of URL class along with syntax of constructors of URL class 4

(Use - 2 Marks Any two Constructor - 1 Mark each)

Ans The URL provides a reasonably intelligible form to uniquely identify or address information on the

Internet URLs are ubiquitous every browser uses them to identify information on the Web In

fact the Web is really just that same old Internet with all of its resources addressed as URLs plus

HTML

Javas URL class has several constructors One commonly used form specifies the URL with a

string that is identical to what you see displayed in a browser

1 URL(String urlSpecifier)

The next two forms of the constructor allow you to break up the URL into its componentparts

2 URL(String protocolName String hostName intport String path)

3 URL(String protocolName String hostName String path)

Another frequently used constructor allows you to use an existing URL as a referencecontext and

then create a new URL from that context Although this sounds a littlecontorted its really quite

easy and useful

4 URL(URL urlObj String urlSpecifier)

4 A) Attempt any three of the following Marks 12

a) Give the use of following methods of statement interface 4

i) executeQuery( ) ii) execute Update ( )

(Each method ndash 2 Marks)

Ans i) executeQuery()

The executeQuery() method of the statement object enables you to send SQL select statement to

the database and to receive result from the database Executing a query in effect sends a SQL

select statement to the database and returns the appropriate results back in the Resultset object

The executeQuery() method takes a SQL select statement as a parameter and returns a ResultSet

object that contains all the records that match the select statements criteria

ii) executeUpdate()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 17 of 38

The executeUpdate() method of the Statement object enables you to execute SQL update

statements such as delete insert and update The method takes a String containing the SQL update

statement and returns an integers that determines how many records were affected by the SQL

statement

b) Define Layout Manager Describe the use of GridLayout Manager 4

(Layout manager- 2 Marks Use-2 Marks)

Ans Each Container object has a layout manager associated with it A layout manager

is an instance of any class that implements the LayoutManagerinterface The layout

manager is set by the setLayout( ) method If no call to setLayout( ) is made then the

default layout manager is used Whenever a container is resized (or sized for the first

time) the layout manager is used to position each of the components within it

The setLayout( ) method has the following general form

voidsetLayout(LayoutManagerlayoutObj)

GridLayoutManager

GridLayout lays out components in a two-dimensional grid When you instantiate

a GridLayout you define the number of rows and columns The constructors

supported by GridLayoutare shown here

GridLayout( )

GridLayout(intnumRows intnumColumns)

GridLayout(intnumRows intnumColumns inthorz intvert)

c) Explain the use of cookies with example 4

(Explanation - 2 Marks Example - 2 Marks any one)

Ans Cookie is a small piece of information that is passed back and forth in the HTTP request and

response Even though a cookie can be created on the client side using some scripting language

such as JavaScript it is usually created by the server resource such as a Servlet The Cookies sent

by the server when the client requests another page from the same application In Servlet

programming a cookie is represented by a Cookie class in the javaxservlethttp package You can

create a cookie by calling the Cookie class constructor and passing two string objects the name

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 18 of 38

and value of the cookie For instance the following code creates a cookie object called c1The

cookie has the name ldquomyCookierdquo and value of rdquosecretrdquo

Cookie c1=new Cookie(ldquomyCookierdquordquosecretrdquo)

You then can add the cookie to the http response using addCookie method of the

HTTPServletResponse interfaceResponseaddCookie(c1)

Program for Add cookies

import javaio

importjavaxservlet

importjavaxservlethttp

public class AddCookieServlet extends HttpServlet

public void doPost(HttpServletRequest requestHttpServletResponse response)

throwsServletException IOException

Get parameter from HTTP request

String data = requestgetParameter(data)

Create cookie

Cookie cookie = new Cookie(MyCookie data)

Add cookie to HTTP response

responseaddCookie(cookie)

Write output to browser

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgtMyCookie has been set to)

pwprintln(data)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 19 of 38

pwclose()

OR

Program for Get Cookies

import javaio

importjavaxservlet

importjavaxservlethttp

public class GetCookiesServlet extends HttpServlet

public void doGet(HttpServletRequest requestHttpServletResponse response)

throwsServletException IOException

Get cookies from header of HTTP request

Cookie[] cookies = requestgetCookies()

Display these cookies

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgt)

for(inti = 0 iltcookieslength i++)

String name = cookies[i]getName()

String value = cookies[i]getValue()

pwprintln(name = + name +

value = + value)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 20 of 38

pwclose()

d) Give steps to create simple servlet with example 4

(Steps- 2 Marks Any one Example ndash 2 Marks)

Ans Steps 1) Write a java servet code

Steps 2) Compile Servet by setting classpath with servlet-api library

Step 3) Copy the class servlet file in web apps classpath directory

Steps 4) Open the webxml open it and add servlet tag and sevlet mapping tag

Steps 5) Start web server(apche tomcat)

Steps 6) Browse servlet using java compatible browser like IE

Example shows to start create a file named WelcomeServletjava that contains the following

program

import javaio

importjavaxservlet

public class WelcomeServletDemo extends GenericServlet

public void service(ServletRequestrequestServletResponse response) throws

ServletExceptionIOException

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgtWelcome to Servlet)

pwclose()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 21 of 38

B) Attempt any one of the following Marks 6

a) Describe the two ndashtier and three ndashtier database design of JDBC API with neat diagram

(Explanation of Two-tier-2 Marks and Three-tier-2 Marks Diagram ndash 1 Mark each)

Ans Two Tier Architecture

In a two tier model a java application is designed to interact directly with the database

Application functionality is divided into these two layers

1) Application Layer Including the JDBC driver business logic and user interface

2) Database Layer including RDBMS

The interface to the database is handled by the Java Database Connectivity(JDBC) Driver

appropriate to the particularly database management system being accessed The JDBC Driver

passes SQL statements to the database and returns the results of those statements to the

application

A clientserver configuration is the special case of the two tier model where the database is

located on another machine referred to as the server The application runs on the client machine

which is connected to the server over a network Commonly the network is an Intranet using

dedicated database servers to support multiple clients but it can just as easily be the internet

Three Tier Architecture-

In the three tier model the client typically sends requests to an application server forming the

middle tier The application server interprets these requests and formats the necessary SQL

statement to fulfill

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 22 of 38

These requests and sends them to the database The database process the SQL statements and

sends result back to the application server which then sends them to the client

Following are some advantages of Three-tier architecture

1 Performance can be improved by separating the application server and database server

2 Business logic is clearly separated from the database

3 Client application can use a simple protocol such as CGI to access services

The three-tier model show in following fig is a common in web application In this scenario the

client tier is frequently implemented in a browse on a client machine the middle tier is

implemented in a web server with a Servlet engine and the database management system runs on

a dedicated database server

Following are the main components of three tier architecture

1 Client Tier - Typically this is thin presentation layer that may be implemented using a web

browser

2 Middle Tier - This tier handles the business or application logic This may be implemented

using a Servlet engine such as Tomcat or an application server such as JBOSS The JDBC

driver also resides in this layer

3 Data source layer This component includes the RDBMS

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 23 of 38

b) Write servlet which shows how many times user has visited the page in session

(Any Correct Logic ndash4 Marks Syntax ndash 2 Marks)

Ans import javaio

import javaxservlet

import javaxservlethttp

public class Session Travker extends HttpServlet

public void doGet(HttpServletRequest req HttpServletResponse res) throws ServletException

IOException

ressetContentType(ldquotexthtmlrdquo)

PrintWriter out = resgetWriter()

HttpSession session = reqgetSession(true)

Integer count= (Integer)sessiongetValue(ldquotrackercountrdquo)

if(count== null) count=new Interger(1)

else count = new Interger(count intValue() +1)

sessionputValue(ldquotrackercountrdquocount)

outprintln(ldquoltHTMLgtltHEADgtltTITLEgtSession TrackerltTITLEgtltHEADgtrdquo)

outprintln(ldquoltBODYgtltH1gtSession Tracking DemoltH1gtrdquo)

outprintln(ldquoYou have visited this pagerdquo +count +((countintValue() == 1)rdquotimerdquo

ldquotimesrdquo))outprinln(ltPgtrdquo)

outprintln(ldquoltH2gtSesssion dataltH2gtrdquo)

String[] names = sessiongetValueNames()

for(int i=0 ilt nameslength i++)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 24 of 38

outprintln(names[i] + ldquo rdquo + sessiongetvalue(names[i])+ ldquoltBRgtrdquo)

outprintln(ldquoltBODYgtltHTMLgtrdquo)

5 Attempt any two of the following Marks 16

a) Write a program to display all records from Employee table from database using

JDBC

(Assume suitable data for table- Load driver create connection execute Query - 1 Mark

each Display data- 3 Marks Syntax ndash 2 Marks)

Ans import javasql

import javasqlStatement

import javaapplet

import javaawt

public class DisplayTable

public static void main( String args[])

RsultSet rs

Connection conn

try

String s1

ClassforName(sun jdbcodbcJdbcOdbcDriver)

Systemoutprintln(Connecting to a selected database)

String url=rdquojdbcodbcabcrdquo

conn = DriverManagergetConnection(DB_URL USER PASS)

Systemoutprintln(Connected database successfully)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 25 of 38

Systemoutprintln(Creating statement)

stmt = conncreateStatement()

sql = SELECT FROM Employee

ResultSet rs = stmtexecuteQuery(sql)

Tables fields assumed are id first last age

while(rsnext())

int id = rsgetInt(id)

int age = rsgetInt(age)

String first = rsgetString(first)

String last = rsgetString(last)

Systemoutprint(ID + id)

Systemoutprint( Age + age)

Systemoutprint( First + first)

Systemoutprintln( Last + last)

rsclose()

catch(SQLException se)

Handle errors for JDBC

seprintStackTrace()

catch(Exception e)

Handle errors for ClassforName

eprintStackTrace()

finally

finally block used to close resources

try

if(stmt=null)

connclose()

catch(SQLException se)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 26 of 38

b) Define the term

i) Reserved socket ii) proxy server

iii) Datagram iv) URL connection 4

(Each term- 2 Marks)

Ans i) Reserved socket

A socket is one end-point of a two-way communication link between two programs running on

the network Socket classes are used to represent the connection between a client program and a

server program

Reserved socket The socket which are reserved for specific protocols for communication

purpose are known as reseved sockets

TCPIP uses or reserves the lower 1024 ports for specific protocols

Example port number 23 is for Telnet 25 is for smtp 21 is for ftp 13 for daytime 110 for pop3

and so on Protocol decides how a client should interact with the port

ii) Proxy server

A proxy server is a computer that offers a computer network service to allow clients to make

indirect network connections to other network services A client connects to the proxy server

then requests a connection file or other resource available on a different server The proxy

provides the resource either by connecting to the specified server or by serving it from a cache In

some cases the proxy may alter the clients request or the servers response for various purposes

Purposes of the proxy servers

To keep machines behind it anonymous mainly for security

To speed up access to resources (using caching) Web proxies are commonly used to

cache web pages from a web server

To prevent downloading the same content multiple times (and save bandwidth)

To log audit usage eg to provide company employee Internet usage reporting

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 27 of 38

To scan transmitted content for malware before delivery

To scan outbound content eg for data loss prevention

iii) Datagram

Datagrams are bundles of information passed between machines They are somewhat like a hard

throw from a well-trained but blindfolded catcher to the third baseman Once the datagram has

been released to its intended target there is no assurance that it will arrive or even that

someone will be there to catch it Likewise when the datagram is received there is no

assurance that it hasnrsquot been damaged in transit or that whoever sent it is still there to receive a

response

Java implements datagrams on top of the UDP protocol by using two classes

The DatagramPacket object is the data container while the DatagramSocket is the mechanism

used to send or receive the DatagramPackets

iv) URL connection

URLConnection is a general-purpose class for accessing the attributes of a remote resource

Once you make a connection to a remote server you can use URLConnection to inspect the

Properties of the remote object before actually transporting it locally These attributes are

exposed by the HTTP protocol specification and as such only make sense for URL objects

that are using the HTTP protocol

URLConnection defines several methods

int getContentLength( )

String getContentType( )

long getDate( )

long getExpiration( )

String getHeaderField(int idx)

long getLastModified( )

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 28 of 38

c) Write a program to display three text fields and a button below to all an Applet Insert

the integer valuer from three text fields After pressing the button the background colour

of applet will be changed as per the RGB combination of the values given in the text field

(Correct logic - 6 Marks Syntax - 2 Marks)

4

Ans import javaawt

import javaawtevent

import javaapplet

ltapplet code=rdquoClrclassrdquo width=250 heigth=250gtltappletgt

public class Clrextends Applet implements ActionListener

int r g b

TextField t1t2t3

Button b1

Color c1

public void init()

t1= new TextField(5)

t2= new TextField(8)

t3= new TextField(11)

b1 = new Button(ldquo Set Colorrdquo)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 29 of 38

add(t1)

add(t2)

add(t3)

add(b1)

b1addActionListener(this)

public void void paint( )

setBackground(c1)

public void actionPerformed(ActionEvent ae)

r=IntegerparseInt(t1getText())

g=IntegerparseInt(t2getText())

b=IntegerparseInt(t3getText())

c1= new Color(rgb)

repaint()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 30 of 38

6) Attempt any four of the following Marks 16

a) How to check how many fonts are available in the computer system 4

Explain with example

(Explanation -2 Marks Example-2 Marks)

Ans When working with fonts often you need to know which fonts are available on your machine To

ontain this information you can use the getAvailableFontFamilyNames() method defined by the

GraphicsEnvironment classIt is shown here

String[ ] getAvailableFontFamilyNames( )

This method returns an array of string that contains the names of the available font families

Since this methods is members of GraphicsEnvironment you need a GraphicsEnvironment

reference to call itYou can obtain this reference by using the getlocalGrahicsEnvironmet() static

method which is derfined by GraphicsEnvironmentIt is shown here

static GraphicsEnvironment getLocalGraphicsEnvironment( )

Here is an applet that shown how to obtain the names of the available font families

ltapplet code=rdquoAllFontsrdquo width=500 height=100gt

ltappletgt

import javaapplet

import javaawt

public class AllFonts extends Applet

public void paint(Graphics g)

string fonts= ldquo rdquo

stirng allFontsList[]

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 31 of 38

GraphicsEnvironment t = GraphicsEnvironmentgetLocalGraphicsEnvironment()

allFontList = tgetAvailableFontFamilyNames()

for(int i= 0 ilt allFontsListlength i++)

fonts= fonts + allFontList[i] + ldquo rdquo

gdrawString(msg416)

b) Explain following check box class methods with appropriate example 4

i) Void setLable (String str) ii) Boolean getState ( )

(Explanation of each method-1 Marks Example-2 Marks)

Ans

i) void setLable(String str)

This method is used to set the label of check box

ii) Boolean getState()

This method is used to retrieve the current state of a check box It returns the value either true or

false depends on check box is selected or not

Example

Demonstrate check boxes

import javaawt

import javaawtevent

import javaapplet

ltapplet code=CheckboxDemo width=250 height=200gt

ltappletgt

public class CheckboxDemo extends Applet implements ItemListener

String msg =

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 32 of 38

Checkbox winXP winVista solaris mac

public void init()

winXP = new Checkbox(Windows XP null true)

mac = new Checkbox()

macsetLable(ldquoMac OSrdquo)

add(winXP)

add(mac)

winXPaddItemListener(this)

macaddItemListener(this)

public void itemStateChanged(ItemEvent ie)

repaint()

Display current state of the check boxes

public void paint(Graphics g)

msg = Current state

gdrawString(msg 6 80)

msg = Windows XP + winXPgetState()

gdrawString(msg 6 100)

msg = Mac OS + macgetState()

gdrawString(msg 6 120)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 33 of 38

c) Explain the techniques of session tracking management

(Any four techniques with explanation- 1 Mark each)

Ans Session tracking Techniques

1 User Authorization

Users can be authorized to use the web application in different ways Basic concept is that the

user will provide username and password to login to the application Based on that the user can

be identified and the session can be maintained

2 Hidden Fields

ltINPUT TYPE=rdquohiddenrdquo NAME=rdquotechnologyrdquo VALUE=rdquoservletrdquogt

Hidden fields like the above can be inserted in the webpages and information can be sent to the

server for session tracking These fields are not visible directly to the user but can be viewed

using view source option from the browsers This type doesnrsquot need any special configuration

from the browser of server and by default available to use for session tracking This cannot be

used for session tracking when the conversation included static resources lik html pages

3 URL Rewriting

Original URL httpserverportservletServletName

ewritten URL httpserverportservletServletNamesessionid=7456

When a request is made additional parameter is appended with the url In general added

additional parameter will be sessionid or sometimes the userid It will suffice to track the

session This type of session tracking doesnrsquot need any special support from the browser

Disadvantage is implementing this type of session tracking is tedious We need to keep track of

the parameter as a chain link until the conversation completes and also should make sure that

the parameter doesnrsquot clash with other application parameters

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 34 of 38

4 Cookies

Cookies are the mostly used technology for session tracking Cookie is a key value pair of

information sent by the server to the browser This should be saved by the browser in its space

in the client computer Whenever the browser sends a request to that server it sends the cookie

along with it Then the server can identify the client using the cookie

In java following is the source code snippet to create a cookie

Cookie cookie = new Cookie (ldquouserIDrdquo ldquo7456Prime)

resaddCookie(cookie)

5 Session tracking API

Session tracking API is built on top of the first four methods This is inorder to help the

developer to minimize the overhead of session tracking This type of session tracking is

provided by the underlying technology Lets take the java servlet example Then the servlet

container manages the session tracking task and the user need not do it explicitly using the java

servlets This is the best of all methods because all the management and errors related to

session tracking will be taken care of by the container itself

d) Give sequential steps for JTree in swing with example

(Steps- 2 Marks any small Example- 2 Marks)

Ans Steps for JTree

Atree is a component that presents a hierarchical view of data The user has the ability to

expand or collapse individual subtrees in this display Trees are implemented in Swing by

the JTree class

Here are the steps to follow to use a tree

1 Create an instance of JTree

2 Create a JScrollPane and specify the tree as the object to be scrolled

3 Add the tree to the scroll pane

4 Add the scroll pane to the content pane

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 35 of 38

Example

Demonstrate JTree

import javaawt

import javaxswingevent

import javaxswing

import javaxswingtree

ltapplet code=JTreeDemo width=400 height=200gt

ltappletgt

public class JTreeDemo extends JApplet

JTree tree

JLabel jlab

public void init()

try

SwingUtilitiesinvokeAndWait(

new Runnable()

public void run()

makeGUI()

)

catch (Exception exc)

Systemoutprintln(Cant create because of + exc)

private void makeGUI()

Create top node of tree

DefaultMutableTreeNode top = new DefaultMutableTreeNode(Options)

Create subtree of A

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 36 of 38

DefaultMutableTreeNode a = new DefaultMutableTreeNode(A)

topadd(a)

DefaultMutableTreeNode a1 = new DefaultMutableTreeNode(A1)

aadd(a1)

DefaultMutableTreeNode a2 = new DefaultMutableTreeNode(A2)

aadd(a2)

Create subtree of B

DefaultMutableTreeNode b = new DefaultMutableTreeNode(B)

topadd(b)

DefaultMutableTreeNode b1 = new DefaultMutableTreeNode(B1)

badd(b1)

DefaultMutableTreeNode b2 = new DefaultMutableTreeNode(B2)

badd(b2)

DefaultMutableTreeNode b3 = new DefaultMutableTreeNode(B3)

badd(b3)

Create the tree

tree = new JTree(top)

Add the tree to a scroll pane

JScrollPane jsp = new JScrollPane(tree)

Add the scroll pane to the content pane

add(jsp)

Add the label to the content pane

jlab = new JLabel()

add(jlab BorderLayoutSOUTH)

Handle tree selection events

treeaddTreeSelectionListener(new TreeSelectionListener()

public void valueChanged(TreeSelectionEvent tse)

jlabsetText(Selection is + tsegetPath())

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 37 of 38

e) Draw and explain the life cycle of servlet

(Explanation ndash 3 Marks Diagram -1 Marks)

Ans Three methods are central to the life cycle of a servlet

These are init( ) service( ) and destroy( )

They are implemented by every servlet and are invoked at specific times by the server Let

us consider a typical user scenario to understand when these methods are called

First assume that a user enters a Uniform Resource Locator (URL) to a web browser

The browser then generates an HTTP request for this URL This request is then sent to the

appropriate server

Second this HTTP request is received by the web server The server maps this request to

a particular servlet The servlet is dynamically retrieved and loaded into the address space

of the server

Third the server invokes the init( ) method of the servlet This method is invoked only

when the servlet is first loaded into memory It is possible to pass initialization parameters

to the servlet so it may configure itself

Fourth the server invokes the service( ) method of the servlet This method is called to

process the HTTP request You will see that it is possible for the servlet to read data that has

been provided in the HTTP request It may also formulate an HTTP response for the client

The servlet remains in the serverrsquos address space and is available to process any other

HTTP requests received from clients The service( ) method is called for each HTTP request

Finally the server may decide to unload the servlet from its memory The algorithms by

which this determination is made are specific to each server The server calls the destroy( )

method to relinquish any resources such as file handles that are allocated for the servlet

Important data may be saved to a persistent store The memory allocated for the servlet and

its objects can then be garbage collected

A servlet life cycle can be defined as the entire process from its creation till the destruction The

following are the paths followed by a servlet

The servlet is initialized by calling the init () method

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 38 of 38

The servlet calls service() method to process a clients request

The servlet is terminated by calling the destroy() method

Finally servlet is garbage collected by the garbage collector of the JVM

Initialization

(Load Resources)

Services

(Accept Requests)

Destruction

(Unload Resources)

Servlet

Request

Response

Page 13: AJP

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 13 of 38

public flavourPanel()

JComboBox b=new JComboBox()

jcbaddItem(ldquovanillardquo)

jcbaddItem(ldquochocolaterdquo)

add(jcb)

3 Attempt any four of the following Marks 16

a) Example the use of prepared statement with example 4

(Explanation-2 Marks Example-2 Marks)

Ans PrepareStatement ()

The preparedStatement() method creates a PreparedStatement object and returns it as a return

value The Prepared statement object is used to execute dynamic SQL statement against the

databaseA dynamic SQL statement is a statement in which some of the parameters in the

statement are unknown when the statement is created The parameter is placed into the SQL

statement as they are determined by the application When all the parameters are specified for the

SQL statement the dynamic SQL statement will be executed just as a static statement is executed

To create a dynamic SQL statement that takes a first name and last name as parameters use the

following code

try

String sql=rdquoSelect from temployeerdquo + ldquowhere Firstname=rdquo + ldquoand Lastname=rdquo

PreparedStatement p=connectionpreparedStatement(sql)

Catch(SQLException e)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 14 of 38

b) List any four differences between AWT and swing 4

(Any four points ndash 1 Mark each)

Ans

Swing AWT

It uses javaxswing package It uses javaapplet package

It uses JApplet class It uses Applet class

Swing is light weight component AWT is heavy weight component

It does not have add() method to add

control

It has add() method to add control

AWT provides less features than

swing

Swing has variety of component amp

features which is not in AWT

Awt has huge collection of classes amp

interfaces

Swing has bigger collection of classes

amp interfaces than AWT

AWT has predefined formats of

appearance amp behavior of component

Swing provides a facility of different

appearance amp behavior of the same

component

c) List four interfaces in javaxservlet package 4

(Any four points ndash 1 Mark each)

Ans Following are the interfaces in javaxservlet package

1 Servlet All servlets must implement the Servlet interface It declares the init( ) service( )

and destroy( ) methods that are called by the server during the life cycle of a servlet

2 ServletConfig The ServletContextinterface is implemented by the server It enables servlets

to obtain information about their environment

3 ServletContext The ServletContextinterface is implemented by the server It enables

servlets to obtain information about their environment

4 ServletRequest The ServletRequestinterface is implemented by the server It enables a

servlet to obtain information about a client request

5 ServletResponse The ServletResponseinterface is implemented by the server It enables a

servlet to formulate a response for a client

6 SingleThreadModel This interface is used to indicate that only a single thread will execute

the service( ) method of a servlet at a given time It defines no constants and declares no

methods

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 15 of 38

d) Give the use of ImageIcon class with example 4

(Explanation ndash 2 Marks Example- 2 Marks)

Ans In Swing icons are encapsulated by the ImageIconclass which paints an icon from an

image Two of its constructors are shown here

ImageIcon(String filename)

ImageIcon(URL url)

The first form uses the image in the file named filename The second form uses the

image in the resource identified by url

The ImageIconclass implements the Icon interface that declares the methods

As follows

Method Description

intgetIconHeight( ) Returns the height of the iconin pixels

intgetIconWidth( ) Returns the width of the iconin pixels

voidpaintIcon(Component comp Graphics gintx inty)Paints the icon at position x y onthe

graphics context g Additionalinformation about the paintoperation can be provided in comp

Example

import javaawt

import javaxswing

ltapplet code=JLabelDemo width=250 height=150gt

ltappletgt

public class JLabelDemo extends JApplet

public void init()

Get content pane

Container contentPane = getContentPane()

Create an icon

ImageIcon ii = new ImageIcon(francegif)

Create a label

JLabeljl = new JLabel(France ii JLabelCENTER)

Add label to the content pane

contentPaneadd(jl)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 16 of 38

e) Give the use of URL class along with syntax of constructors of URL class 4

(Use - 2 Marks Any two Constructor - 1 Mark each)

Ans The URL provides a reasonably intelligible form to uniquely identify or address information on the

Internet URLs are ubiquitous every browser uses them to identify information on the Web In

fact the Web is really just that same old Internet with all of its resources addressed as URLs plus

HTML

Javas URL class has several constructors One commonly used form specifies the URL with a

string that is identical to what you see displayed in a browser

1 URL(String urlSpecifier)

The next two forms of the constructor allow you to break up the URL into its componentparts

2 URL(String protocolName String hostName intport String path)

3 URL(String protocolName String hostName String path)

Another frequently used constructor allows you to use an existing URL as a referencecontext and

then create a new URL from that context Although this sounds a littlecontorted its really quite

easy and useful

4 URL(URL urlObj String urlSpecifier)

4 A) Attempt any three of the following Marks 12

a) Give the use of following methods of statement interface 4

i) executeQuery( ) ii) execute Update ( )

(Each method ndash 2 Marks)

Ans i) executeQuery()

The executeQuery() method of the statement object enables you to send SQL select statement to

the database and to receive result from the database Executing a query in effect sends a SQL

select statement to the database and returns the appropriate results back in the Resultset object

The executeQuery() method takes a SQL select statement as a parameter and returns a ResultSet

object that contains all the records that match the select statements criteria

ii) executeUpdate()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 17 of 38

The executeUpdate() method of the Statement object enables you to execute SQL update

statements such as delete insert and update The method takes a String containing the SQL update

statement and returns an integers that determines how many records were affected by the SQL

statement

b) Define Layout Manager Describe the use of GridLayout Manager 4

(Layout manager- 2 Marks Use-2 Marks)

Ans Each Container object has a layout manager associated with it A layout manager

is an instance of any class that implements the LayoutManagerinterface The layout

manager is set by the setLayout( ) method If no call to setLayout( ) is made then the

default layout manager is used Whenever a container is resized (or sized for the first

time) the layout manager is used to position each of the components within it

The setLayout( ) method has the following general form

voidsetLayout(LayoutManagerlayoutObj)

GridLayoutManager

GridLayout lays out components in a two-dimensional grid When you instantiate

a GridLayout you define the number of rows and columns The constructors

supported by GridLayoutare shown here

GridLayout( )

GridLayout(intnumRows intnumColumns)

GridLayout(intnumRows intnumColumns inthorz intvert)

c) Explain the use of cookies with example 4

(Explanation - 2 Marks Example - 2 Marks any one)

Ans Cookie is a small piece of information that is passed back and forth in the HTTP request and

response Even though a cookie can be created on the client side using some scripting language

such as JavaScript it is usually created by the server resource such as a Servlet The Cookies sent

by the server when the client requests another page from the same application In Servlet

programming a cookie is represented by a Cookie class in the javaxservlethttp package You can

create a cookie by calling the Cookie class constructor and passing two string objects the name

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 18 of 38

and value of the cookie For instance the following code creates a cookie object called c1The

cookie has the name ldquomyCookierdquo and value of rdquosecretrdquo

Cookie c1=new Cookie(ldquomyCookierdquordquosecretrdquo)

You then can add the cookie to the http response using addCookie method of the

HTTPServletResponse interfaceResponseaddCookie(c1)

Program for Add cookies

import javaio

importjavaxservlet

importjavaxservlethttp

public class AddCookieServlet extends HttpServlet

public void doPost(HttpServletRequest requestHttpServletResponse response)

throwsServletException IOException

Get parameter from HTTP request

String data = requestgetParameter(data)

Create cookie

Cookie cookie = new Cookie(MyCookie data)

Add cookie to HTTP response

responseaddCookie(cookie)

Write output to browser

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgtMyCookie has been set to)

pwprintln(data)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 19 of 38

pwclose()

OR

Program for Get Cookies

import javaio

importjavaxservlet

importjavaxservlethttp

public class GetCookiesServlet extends HttpServlet

public void doGet(HttpServletRequest requestHttpServletResponse response)

throwsServletException IOException

Get cookies from header of HTTP request

Cookie[] cookies = requestgetCookies()

Display these cookies

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgt)

for(inti = 0 iltcookieslength i++)

String name = cookies[i]getName()

String value = cookies[i]getValue()

pwprintln(name = + name +

value = + value)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 20 of 38

pwclose()

d) Give steps to create simple servlet with example 4

(Steps- 2 Marks Any one Example ndash 2 Marks)

Ans Steps 1) Write a java servet code

Steps 2) Compile Servet by setting classpath with servlet-api library

Step 3) Copy the class servlet file in web apps classpath directory

Steps 4) Open the webxml open it and add servlet tag and sevlet mapping tag

Steps 5) Start web server(apche tomcat)

Steps 6) Browse servlet using java compatible browser like IE

Example shows to start create a file named WelcomeServletjava that contains the following

program

import javaio

importjavaxservlet

public class WelcomeServletDemo extends GenericServlet

public void service(ServletRequestrequestServletResponse response) throws

ServletExceptionIOException

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgtWelcome to Servlet)

pwclose()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 21 of 38

B) Attempt any one of the following Marks 6

a) Describe the two ndashtier and three ndashtier database design of JDBC API with neat diagram

(Explanation of Two-tier-2 Marks and Three-tier-2 Marks Diagram ndash 1 Mark each)

Ans Two Tier Architecture

In a two tier model a java application is designed to interact directly with the database

Application functionality is divided into these two layers

1) Application Layer Including the JDBC driver business logic and user interface

2) Database Layer including RDBMS

The interface to the database is handled by the Java Database Connectivity(JDBC) Driver

appropriate to the particularly database management system being accessed The JDBC Driver

passes SQL statements to the database and returns the results of those statements to the

application

A clientserver configuration is the special case of the two tier model where the database is

located on another machine referred to as the server The application runs on the client machine

which is connected to the server over a network Commonly the network is an Intranet using

dedicated database servers to support multiple clients but it can just as easily be the internet

Three Tier Architecture-

In the three tier model the client typically sends requests to an application server forming the

middle tier The application server interprets these requests and formats the necessary SQL

statement to fulfill

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 22 of 38

These requests and sends them to the database The database process the SQL statements and

sends result back to the application server which then sends them to the client

Following are some advantages of Three-tier architecture

1 Performance can be improved by separating the application server and database server

2 Business logic is clearly separated from the database

3 Client application can use a simple protocol such as CGI to access services

The three-tier model show in following fig is a common in web application In this scenario the

client tier is frequently implemented in a browse on a client machine the middle tier is

implemented in a web server with a Servlet engine and the database management system runs on

a dedicated database server

Following are the main components of three tier architecture

1 Client Tier - Typically this is thin presentation layer that may be implemented using a web

browser

2 Middle Tier - This tier handles the business or application logic This may be implemented

using a Servlet engine such as Tomcat or an application server such as JBOSS The JDBC

driver also resides in this layer

3 Data source layer This component includes the RDBMS

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 23 of 38

b) Write servlet which shows how many times user has visited the page in session

(Any Correct Logic ndash4 Marks Syntax ndash 2 Marks)

Ans import javaio

import javaxservlet

import javaxservlethttp

public class Session Travker extends HttpServlet

public void doGet(HttpServletRequest req HttpServletResponse res) throws ServletException

IOException

ressetContentType(ldquotexthtmlrdquo)

PrintWriter out = resgetWriter()

HttpSession session = reqgetSession(true)

Integer count= (Integer)sessiongetValue(ldquotrackercountrdquo)

if(count== null) count=new Interger(1)

else count = new Interger(count intValue() +1)

sessionputValue(ldquotrackercountrdquocount)

outprintln(ldquoltHTMLgtltHEADgtltTITLEgtSession TrackerltTITLEgtltHEADgtrdquo)

outprintln(ldquoltBODYgtltH1gtSession Tracking DemoltH1gtrdquo)

outprintln(ldquoYou have visited this pagerdquo +count +((countintValue() == 1)rdquotimerdquo

ldquotimesrdquo))outprinln(ltPgtrdquo)

outprintln(ldquoltH2gtSesssion dataltH2gtrdquo)

String[] names = sessiongetValueNames()

for(int i=0 ilt nameslength i++)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 24 of 38

outprintln(names[i] + ldquo rdquo + sessiongetvalue(names[i])+ ldquoltBRgtrdquo)

outprintln(ldquoltBODYgtltHTMLgtrdquo)

5 Attempt any two of the following Marks 16

a) Write a program to display all records from Employee table from database using

JDBC

(Assume suitable data for table- Load driver create connection execute Query - 1 Mark

each Display data- 3 Marks Syntax ndash 2 Marks)

Ans import javasql

import javasqlStatement

import javaapplet

import javaawt

public class DisplayTable

public static void main( String args[])

RsultSet rs

Connection conn

try

String s1

ClassforName(sun jdbcodbcJdbcOdbcDriver)

Systemoutprintln(Connecting to a selected database)

String url=rdquojdbcodbcabcrdquo

conn = DriverManagergetConnection(DB_URL USER PASS)

Systemoutprintln(Connected database successfully)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 25 of 38

Systemoutprintln(Creating statement)

stmt = conncreateStatement()

sql = SELECT FROM Employee

ResultSet rs = stmtexecuteQuery(sql)

Tables fields assumed are id first last age

while(rsnext())

int id = rsgetInt(id)

int age = rsgetInt(age)

String first = rsgetString(first)

String last = rsgetString(last)

Systemoutprint(ID + id)

Systemoutprint( Age + age)

Systemoutprint( First + first)

Systemoutprintln( Last + last)

rsclose()

catch(SQLException se)

Handle errors for JDBC

seprintStackTrace()

catch(Exception e)

Handle errors for ClassforName

eprintStackTrace()

finally

finally block used to close resources

try

if(stmt=null)

connclose()

catch(SQLException se)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 26 of 38

b) Define the term

i) Reserved socket ii) proxy server

iii) Datagram iv) URL connection 4

(Each term- 2 Marks)

Ans i) Reserved socket

A socket is one end-point of a two-way communication link between two programs running on

the network Socket classes are used to represent the connection between a client program and a

server program

Reserved socket The socket which are reserved for specific protocols for communication

purpose are known as reseved sockets

TCPIP uses or reserves the lower 1024 ports for specific protocols

Example port number 23 is for Telnet 25 is for smtp 21 is for ftp 13 for daytime 110 for pop3

and so on Protocol decides how a client should interact with the port

ii) Proxy server

A proxy server is a computer that offers a computer network service to allow clients to make

indirect network connections to other network services A client connects to the proxy server

then requests a connection file or other resource available on a different server The proxy

provides the resource either by connecting to the specified server or by serving it from a cache In

some cases the proxy may alter the clients request or the servers response for various purposes

Purposes of the proxy servers

To keep machines behind it anonymous mainly for security

To speed up access to resources (using caching) Web proxies are commonly used to

cache web pages from a web server

To prevent downloading the same content multiple times (and save bandwidth)

To log audit usage eg to provide company employee Internet usage reporting

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 27 of 38

To scan transmitted content for malware before delivery

To scan outbound content eg for data loss prevention

iii) Datagram

Datagrams are bundles of information passed between machines They are somewhat like a hard

throw from a well-trained but blindfolded catcher to the third baseman Once the datagram has

been released to its intended target there is no assurance that it will arrive or even that

someone will be there to catch it Likewise when the datagram is received there is no

assurance that it hasnrsquot been damaged in transit or that whoever sent it is still there to receive a

response

Java implements datagrams on top of the UDP protocol by using two classes

The DatagramPacket object is the data container while the DatagramSocket is the mechanism

used to send or receive the DatagramPackets

iv) URL connection

URLConnection is a general-purpose class for accessing the attributes of a remote resource

Once you make a connection to a remote server you can use URLConnection to inspect the

Properties of the remote object before actually transporting it locally These attributes are

exposed by the HTTP protocol specification and as such only make sense for URL objects

that are using the HTTP protocol

URLConnection defines several methods

int getContentLength( )

String getContentType( )

long getDate( )

long getExpiration( )

String getHeaderField(int idx)

long getLastModified( )

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 28 of 38

c) Write a program to display three text fields and a button below to all an Applet Insert

the integer valuer from three text fields After pressing the button the background colour

of applet will be changed as per the RGB combination of the values given in the text field

(Correct logic - 6 Marks Syntax - 2 Marks)

4

Ans import javaawt

import javaawtevent

import javaapplet

ltapplet code=rdquoClrclassrdquo width=250 heigth=250gtltappletgt

public class Clrextends Applet implements ActionListener

int r g b

TextField t1t2t3

Button b1

Color c1

public void init()

t1= new TextField(5)

t2= new TextField(8)

t3= new TextField(11)

b1 = new Button(ldquo Set Colorrdquo)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 29 of 38

add(t1)

add(t2)

add(t3)

add(b1)

b1addActionListener(this)

public void void paint( )

setBackground(c1)

public void actionPerformed(ActionEvent ae)

r=IntegerparseInt(t1getText())

g=IntegerparseInt(t2getText())

b=IntegerparseInt(t3getText())

c1= new Color(rgb)

repaint()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 30 of 38

6) Attempt any four of the following Marks 16

a) How to check how many fonts are available in the computer system 4

Explain with example

(Explanation -2 Marks Example-2 Marks)

Ans When working with fonts often you need to know which fonts are available on your machine To

ontain this information you can use the getAvailableFontFamilyNames() method defined by the

GraphicsEnvironment classIt is shown here

String[ ] getAvailableFontFamilyNames( )

This method returns an array of string that contains the names of the available font families

Since this methods is members of GraphicsEnvironment you need a GraphicsEnvironment

reference to call itYou can obtain this reference by using the getlocalGrahicsEnvironmet() static

method which is derfined by GraphicsEnvironmentIt is shown here

static GraphicsEnvironment getLocalGraphicsEnvironment( )

Here is an applet that shown how to obtain the names of the available font families

ltapplet code=rdquoAllFontsrdquo width=500 height=100gt

ltappletgt

import javaapplet

import javaawt

public class AllFonts extends Applet

public void paint(Graphics g)

string fonts= ldquo rdquo

stirng allFontsList[]

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 31 of 38

GraphicsEnvironment t = GraphicsEnvironmentgetLocalGraphicsEnvironment()

allFontList = tgetAvailableFontFamilyNames()

for(int i= 0 ilt allFontsListlength i++)

fonts= fonts + allFontList[i] + ldquo rdquo

gdrawString(msg416)

b) Explain following check box class methods with appropriate example 4

i) Void setLable (String str) ii) Boolean getState ( )

(Explanation of each method-1 Marks Example-2 Marks)

Ans

i) void setLable(String str)

This method is used to set the label of check box

ii) Boolean getState()

This method is used to retrieve the current state of a check box It returns the value either true or

false depends on check box is selected or not

Example

Demonstrate check boxes

import javaawt

import javaawtevent

import javaapplet

ltapplet code=CheckboxDemo width=250 height=200gt

ltappletgt

public class CheckboxDemo extends Applet implements ItemListener

String msg =

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 32 of 38

Checkbox winXP winVista solaris mac

public void init()

winXP = new Checkbox(Windows XP null true)

mac = new Checkbox()

macsetLable(ldquoMac OSrdquo)

add(winXP)

add(mac)

winXPaddItemListener(this)

macaddItemListener(this)

public void itemStateChanged(ItemEvent ie)

repaint()

Display current state of the check boxes

public void paint(Graphics g)

msg = Current state

gdrawString(msg 6 80)

msg = Windows XP + winXPgetState()

gdrawString(msg 6 100)

msg = Mac OS + macgetState()

gdrawString(msg 6 120)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 33 of 38

c) Explain the techniques of session tracking management

(Any four techniques with explanation- 1 Mark each)

Ans Session tracking Techniques

1 User Authorization

Users can be authorized to use the web application in different ways Basic concept is that the

user will provide username and password to login to the application Based on that the user can

be identified and the session can be maintained

2 Hidden Fields

ltINPUT TYPE=rdquohiddenrdquo NAME=rdquotechnologyrdquo VALUE=rdquoservletrdquogt

Hidden fields like the above can be inserted in the webpages and information can be sent to the

server for session tracking These fields are not visible directly to the user but can be viewed

using view source option from the browsers This type doesnrsquot need any special configuration

from the browser of server and by default available to use for session tracking This cannot be

used for session tracking when the conversation included static resources lik html pages

3 URL Rewriting

Original URL httpserverportservletServletName

ewritten URL httpserverportservletServletNamesessionid=7456

When a request is made additional parameter is appended with the url In general added

additional parameter will be sessionid or sometimes the userid It will suffice to track the

session This type of session tracking doesnrsquot need any special support from the browser

Disadvantage is implementing this type of session tracking is tedious We need to keep track of

the parameter as a chain link until the conversation completes and also should make sure that

the parameter doesnrsquot clash with other application parameters

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 34 of 38

4 Cookies

Cookies are the mostly used technology for session tracking Cookie is a key value pair of

information sent by the server to the browser This should be saved by the browser in its space

in the client computer Whenever the browser sends a request to that server it sends the cookie

along with it Then the server can identify the client using the cookie

In java following is the source code snippet to create a cookie

Cookie cookie = new Cookie (ldquouserIDrdquo ldquo7456Prime)

resaddCookie(cookie)

5 Session tracking API

Session tracking API is built on top of the first four methods This is inorder to help the

developer to minimize the overhead of session tracking This type of session tracking is

provided by the underlying technology Lets take the java servlet example Then the servlet

container manages the session tracking task and the user need not do it explicitly using the java

servlets This is the best of all methods because all the management and errors related to

session tracking will be taken care of by the container itself

d) Give sequential steps for JTree in swing with example

(Steps- 2 Marks any small Example- 2 Marks)

Ans Steps for JTree

Atree is a component that presents a hierarchical view of data The user has the ability to

expand or collapse individual subtrees in this display Trees are implemented in Swing by

the JTree class

Here are the steps to follow to use a tree

1 Create an instance of JTree

2 Create a JScrollPane and specify the tree as the object to be scrolled

3 Add the tree to the scroll pane

4 Add the scroll pane to the content pane

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 35 of 38

Example

Demonstrate JTree

import javaawt

import javaxswingevent

import javaxswing

import javaxswingtree

ltapplet code=JTreeDemo width=400 height=200gt

ltappletgt

public class JTreeDemo extends JApplet

JTree tree

JLabel jlab

public void init()

try

SwingUtilitiesinvokeAndWait(

new Runnable()

public void run()

makeGUI()

)

catch (Exception exc)

Systemoutprintln(Cant create because of + exc)

private void makeGUI()

Create top node of tree

DefaultMutableTreeNode top = new DefaultMutableTreeNode(Options)

Create subtree of A

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 36 of 38

DefaultMutableTreeNode a = new DefaultMutableTreeNode(A)

topadd(a)

DefaultMutableTreeNode a1 = new DefaultMutableTreeNode(A1)

aadd(a1)

DefaultMutableTreeNode a2 = new DefaultMutableTreeNode(A2)

aadd(a2)

Create subtree of B

DefaultMutableTreeNode b = new DefaultMutableTreeNode(B)

topadd(b)

DefaultMutableTreeNode b1 = new DefaultMutableTreeNode(B1)

badd(b1)

DefaultMutableTreeNode b2 = new DefaultMutableTreeNode(B2)

badd(b2)

DefaultMutableTreeNode b3 = new DefaultMutableTreeNode(B3)

badd(b3)

Create the tree

tree = new JTree(top)

Add the tree to a scroll pane

JScrollPane jsp = new JScrollPane(tree)

Add the scroll pane to the content pane

add(jsp)

Add the label to the content pane

jlab = new JLabel()

add(jlab BorderLayoutSOUTH)

Handle tree selection events

treeaddTreeSelectionListener(new TreeSelectionListener()

public void valueChanged(TreeSelectionEvent tse)

jlabsetText(Selection is + tsegetPath())

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 37 of 38

e) Draw and explain the life cycle of servlet

(Explanation ndash 3 Marks Diagram -1 Marks)

Ans Three methods are central to the life cycle of a servlet

These are init( ) service( ) and destroy( )

They are implemented by every servlet and are invoked at specific times by the server Let

us consider a typical user scenario to understand when these methods are called

First assume that a user enters a Uniform Resource Locator (URL) to a web browser

The browser then generates an HTTP request for this URL This request is then sent to the

appropriate server

Second this HTTP request is received by the web server The server maps this request to

a particular servlet The servlet is dynamically retrieved and loaded into the address space

of the server

Third the server invokes the init( ) method of the servlet This method is invoked only

when the servlet is first loaded into memory It is possible to pass initialization parameters

to the servlet so it may configure itself

Fourth the server invokes the service( ) method of the servlet This method is called to

process the HTTP request You will see that it is possible for the servlet to read data that has

been provided in the HTTP request It may also formulate an HTTP response for the client

The servlet remains in the serverrsquos address space and is available to process any other

HTTP requests received from clients The service( ) method is called for each HTTP request

Finally the server may decide to unload the servlet from its memory The algorithms by

which this determination is made are specific to each server The server calls the destroy( )

method to relinquish any resources such as file handles that are allocated for the servlet

Important data may be saved to a persistent store The memory allocated for the servlet and

its objects can then be garbage collected

A servlet life cycle can be defined as the entire process from its creation till the destruction The

following are the paths followed by a servlet

The servlet is initialized by calling the init () method

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 38 of 38

The servlet calls service() method to process a clients request

The servlet is terminated by calling the destroy() method

Finally servlet is garbage collected by the garbage collector of the JVM

Initialization

(Load Resources)

Services

(Accept Requests)

Destruction

(Unload Resources)

Servlet

Request

Response

Page 14: AJP

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 14 of 38

b) List any four differences between AWT and swing 4

(Any four points ndash 1 Mark each)

Ans

Swing AWT

It uses javaxswing package It uses javaapplet package

It uses JApplet class It uses Applet class

Swing is light weight component AWT is heavy weight component

It does not have add() method to add

control

It has add() method to add control

AWT provides less features than

swing

Swing has variety of component amp

features which is not in AWT

Awt has huge collection of classes amp

interfaces

Swing has bigger collection of classes

amp interfaces than AWT

AWT has predefined formats of

appearance amp behavior of component

Swing provides a facility of different

appearance amp behavior of the same

component

c) List four interfaces in javaxservlet package 4

(Any four points ndash 1 Mark each)

Ans Following are the interfaces in javaxservlet package

1 Servlet All servlets must implement the Servlet interface It declares the init( ) service( )

and destroy( ) methods that are called by the server during the life cycle of a servlet

2 ServletConfig The ServletContextinterface is implemented by the server It enables servlets

to obtain information about their environment

3 ServletContext The ServletContextinterface is implemented by the server It enables

servlets to obtain information about their environment

4 ServletRequest The ServletRequestinterface is implemented by the server It enables a

servlet to obtain information about a client request

5 ServletResponse The ServletResponseinterface is implemented by the server It enables a

servlet to formulate a response for a client

6 SingleThreadModel This interface is used to indicate that only a single thread will execute

the service( ) method of a servlet at a given time It defines no constants and declares no

methods

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 15 of 38

d) Give the use of ImageIcon class with example 4

(Explanation ndash 2 Marks Example- 2 Marks)

Ans In Swing icons are encapsulated by the ImageIconclass which paints an icon from an

image Two of its constructors are shown here

ImageIcon(String filename)

ImageIcon(URL url)

The first form uses the image in the file named filename The second form uses the

image in the resource identified by url

The ImageIconclass implements the Icon interface that declares the methods

As follows

Method Description

intgetIconHeight( ) Returns the height of the iconin pixels

intgetIconWidth( ) Returns the width of the iconin pixels

voidpaintIcon(Component comp Graphics gintx inty)Paints the icon at position x y onthe

graphics context g Additionalinformation about the paintoperation can be provided in comp

Example

import javaawt

import javaxswing

ltapplet code=JLabelDemo width=250 height=150gt

ltappletgt

public class JLabelDemo extends JApplet

public void init()

Get content pane

Container contentPane = getContentPane()

Create an icon

ImageIcon ii = new ImageIcon(francegif)

Create a label

JLabeljl = new JLabel(France ii JLabelCENTER)

Add label to the content pane

contentPaneadd(jl)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 16 of 38

e) Give the use of URL class along with syntax of constructors of URL class 4

(Use - 2 Marks Any two Constructor - 1 Mark each)

Ans The URL provides a reasonably intelligible form to uniquely identify or address information on the

Internet URLs are ubiquitous every browser uses them to identify information on the Web In

fact the Web is really just that same old Internet with all of its resources addressed as URLs plus

HTML

Javas URL class has several constructors One commonly used form specifies the URL with a

string that is identical to what you see displayed in a browser

1 URL(String urlSpecifier)

The next two forms of the constructor allow you to break up the URL into its componentparts

2 URL(String protocolName String hostName intport String path)

3 URL(String protocolName String hostName String path)

Another frequently used constructor allows you to use an existing URL as a referencecontext and

then create a new URL from that context Although this sounds a littlecontorted its really quite

easy and useful

4 URL(URL urlObj String urlSpecifier)

4 A) Attempt any three of the following Marks 12

a) Give the use of following methods of statement interface 4

i) executeQuery( ) ii) execute Update ( )

(Each method ndash 2 Marks)

Ans i) executeQuery()

The executeQuery() method of the statement object enables you to send SQL select statement to

the database and to receive result from the database Executing a query in effect sends a SQL

select statement to the database and returns the appropriate results back in the Resultset object

The executeQuery() method takes a SQL select statement as a parameter and returns a ResultSet

object that contains all the records that match the select statements criteria

ii) executeUpdate()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 17 of 38

The executeUpdate() method of the Statement object enables you to execute SQL update

statements such as delete insert and update The method takes a String containing the SQL update

statement and returns an integers that determines how many records were affected by the SQL

statement

b) Define Layout Manager Describe the use of GridLayout Manager 4

(Layout manager- 2 Marks Use-2 Marks)

Ans Each Container object has a layout manager associated with it A layout manager

is an instance of any class that implements the LayoutManagerinterface The layout

manager is set by the setLayout( ) method If no call to setLayout( ) is made then the

default layout manager is used Whenever a container is resized (or sized for the first

time) the layout manager is used to position each of the components within it

The setLayout( ) method has the following general form

voidsetLayout(LayoutManagerlayoutObj)

GridLayoutManager

GridLayout lays out components in a two-dimensional grid When you instantiate

a GridLayout you define the number of rows and columns The constructors

supported by GridLayoutare shown here

GridLayout( )

GridLayout(intnumRows intnumColumns)

GridLayout(intnumRows intnumColumns inthorz intvert)

c) Explain the use of cookies with example 4

(Explanation - 2 Marks Example - 2 Marks any one)

Ans Cookie is a small piece of information that is passed back and forth in the HTTP request and

response Even though a cookie can be created on the client side using some scripting language

such as JavaScript it is usually created by the server resource such as a Servlet The Cookies sent

by the server when the client requests another page from the same application In Servlet

programming a cookie is represented by a Cookie class in the javaxservlethttp package You can

create a cookie by calling the Cookie class constructor and passing two string objects the name

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 18 of 38

and value of the cookie For instance the following code creates a cookie object called c1The

cookie has the name ldquomyCookierdquo and value of rdquosecretrdquo

Cookie c1=new Cookie(ldquomyCookierdquordquosecretrdquo)

You then can add the cookie to the http response using addCookie method of the

HTTPServletResponse interfaceResponseaddCookie(c1)

Program for Add cookies

import javaio

importjavaxservlet

importjavaxservlethttp

public class AddCookieServlet extends HttpServlet

public void doPost(HttpServletRequest requestHttpServletResponse response)

throwsServletException IOException

Get parameter from HTTP request

String data = requestgetParameter(data)

Create cookie

Cookie cookie = new Cookie(MyCookie data)

Add cookie to HTTP response

responseaddCookie(cookie)

Write output to browser

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgtMyCookie has been set to)

pwprintln(data)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 19 of 38

pwclose()

OR

Program for Get Cookies

import javaio

importjavaxservlet

importjavaxservlethttp

public class GetCookiesServlet extends HttpServlet

public void doGet(HttpServletRequest requestHttpServletResponse response)

throwsServletException IOException

Get cookies from header of HTTP request

Cookie[] cookies = requestgetCookies()

Display these cookies

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgt)

for(inti = 0 iltcookieslength i++)

String name = cookies[i]getName()

String value = cookies[i]getValue()

pwprintln(name = + name +

value = + value)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 20 of 38

pwclose()

d) Give steps to create simple servlet with example 4

(Steps- 2 Marks Any one Example ndash 2 Marks)

Ans Steps 1) Write a java servet code

Steps 2) Compile Servet by setting classpath with servlet-api library

Step 3) Copy the class servlet file in web apps classpath directory

Steps 4) Open the webxml open it and add servlet tag and sevlet mapping tag

Steps 5) Start web server(apche tomcat)

Steps 6) Browse servlet using java compatible browser like IE

Example shows to start create a file named WelcomeServletjava that contains the following

program

import javaio

importjavaxservlet

public class WelcomeServletDemo extends GenericServlet

public void service(ServletRequestrequestServletResponse response) throws

ServletExceptionIOException

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgtWelcome to Servlet)

pwclose()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 21 of 38

B) Attempt any one of the following Marks 6

a) Describe the two ndashtier and three ndashtier database design of JDBC API with neat diagram

(Explanation of Two-tier-2 Marks and Three-tier-2 Marks Diagram ndash 1 Mark each)

Ans Two Tier Architecture

In a two tier model a java application is designed to interact directly with the database

Application functionality is divided into these two layers

1) Application Layer Including the JDBC driver business logic and user interface

2) Database Layer including RDBMS

The interface to the database is handled by the Java Database Connectivity(JDBC) Driver

appropriate to the particularly database management system being accessed The JDBC Driver

passes SQL statements to the database and returns the results of those statements to the

application

A clientserver configuration is the special case of the two tier model where the database is

located on another machine referred to as the server The application runs on the client machine

which is connected to the server over a network Commonly the network is an Intranet using

dedicated database servers to support multiple clients but it can just as easily be the internet

Three Tier Architecture-

In the three tier model the client typically sends requests to an application server forming the

middle tier The application server interprets these requests and formats the necessary SQL

statement to fulfill

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 22 of 38

These requests and sends them to the database The database process the SQL statements and

sends result back to the application server which then sends them to the client

Following are some advantages of Three-tier architecture

1 Performance can be improved by separating the application server and database server

2 Business logic is clearly separated from the database

3 Client application can use a simple protocol such as CGI to access services

The three-tier model show in following fig is a common in web application In this scenario the

client tier is frequently implemented in a browse on a client machine the middle tier is

implemented in a web server with a Servlet engine and the database management system runs on

a dedicated database server

Following are the main components of three tier architecture

1 Client Tier - Typically this is thin presentation layer that may be implemented using a web

browser

2 Middle Tier - This tier handles the business or application logic This may be implemented

using a Servlet engine such as Tomcat or an application server such as JBOSS The JDBC

driver also resides in this layer

3 Data source layer This component includes the RDBMS

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 23 of 38

b) Write servlet which shows how many times user has visited the page in session

(Any Correct Logic ndash4 Marks Syntax ndash 2 Marks)

Ans import javaio

import javaxservlet

import javaxservlethttp

public class Session Travker extends HttpServlet

public void doGet(HttpServletRequest req HttpServletResponse res) throws ServletException

IOException

ressetContentType(ldquotexthtmlrdquo)

PrintWriter out = resgetWriter()

HttpSession session = reqgetSession(true)

Integer count= (Integer)sessiongetValue(ldquotrackercountrdquo)

if(count== null) count=new Interger(1)

else count = new Interger(count intValue() +1)

sessionputValue(ldquotrackercountrdquocount)

outprintln(ldquoltHTMLgtltHEADgtltTITLEgtSession TrackerltTITLEgtltHEADgtrdquo)

outprintln(ldquoltBODYgtltH1gtSession Tracking DemoltH1gtrdquo)

outprintln(ldquoYou have visited this pagerdquo +count +((countintValue() == 1)rdquotimerdquo

ldquotimesrdquo))outprinln(ltPgtrdquo)

outprintln(ldquoltH2gtSesssion dataltH2gtrdquo)

String[] names = sessiongetValueNames()

for(int i=0 ilt nameslength i++)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 24 of 38

outprintln(names[i] + ldquo rdquo + sessiongetvalue(names[i])+ ldquoltBRgtrdquo)

outprintln(ldquoltBODYgtltHTMLgtrdquo)

5 Attempt any two of the following Marks 16

a) Write a program to display all records from Employee table from database using

JDBC

(Assume suitable data for table- Load driver create connection execute Query - 1 Mark

each Display data- 3 Marks Syntax ndash 2 Marks)

Ans import javasql

import javasqlStatement

import javaapplet

import javaawt

public class DisplayTable

public static void main( String args[])

RsultSet rs

Connection conn

try

String s1

ClassforName(sun jdbcodbcJdbcOdbcDriver)

Systemoutprintln(Connecting to a selected database)

String url=rdquojdbcodbcabcrdquo

conn = DriverManagergetConnection(DB_URL USER PASS)

Systemoutprintln(Connected database successfully)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 25 of 38

Systemoutprintln(Creating statement)

stmt = conncreateStatement()

sql = SELECT FROM Employee

ResultSet rs = stmtexecuteQuery(sql)

Tables fields assumed are id first last age

while(rsnext())

int id = rsgetInt(id)

int age = rsgetInt(age)

String first = rsgetString(first)

String last = rsgetString(last)

Systemoutprint(ID + id)

Systemoutprint( Age + age)

Systemoutprint( First + first)

Systemoutprintln( Last + last)

rsclose()

catch(SQLException se)

Handle errors for JDBC

seprintStackTrace()

catch(Exception e)

Handle errors for ClassforName

eprintStackTrace()

finally

finally block used to close resources

try

if(stmt=null)

connclose()

catch(SQLException se)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 26 of 38

b) Define the term

i) Reserved socket ii) proxy server

iii) Datagram iv) URL connection 4

(Each term- 2 Marks)

Ans i) Reserved socket

A socket is one end-point of a two-way communication link between two programs running on

the network Socket classes are used to represent the connection between a client program and a

server program

Reserved socket The socket which are reserved for specific protocols for communication

purpose are known as reseved sockets

TCPIP uses or reserves the lower 1024 ports for specific protocols

Example port number 23 is for Telnet 25 is for smtp 21 is for ftp 13 for daytime 110 for pop3

and so on Protocol decides how a client should interact with the port

ii) Proxy server

A proxy server is a computer that offers a computer network service to allow clients to make

indirect network connections to other network services A client connects to the proxy server

then requests a connection file or other resource available on a different server The proxy

provides the resource either by connecting to the specified server or by serving it from a cache In

some cases the proxy may alter the clients request or the servers response for various purposes

Purposes of the proxy servers

To keep machines behind it anonymous mainly for security

To speed up access to resources (using caching) Web proxies are commonly used to

cache web pages from a web server

To prevent downloading the same content multiple times (and save bandwidth)

To log audit usage eg to provide company employee Internet usage reporting

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 27 of 38

To scan transmitted content for malware before delivery

To scan outbound content eg for data loss prevention

iii) Datagram

Datagrams are bundles of information passed between machines They are somewhat like a hard

throw from a well-trained but blindfolded catcher to the third baseman Once the datagram has

been released to its intended target there is no assurance that it will arrive or even that

someone will be there to catch it Likewise when the datagram is received there is no

assurance that it hasnrsquot been damaged in transit or that whoever sent it is still there to receive a

response

Java implements datagrams on top of the UDP protocol by using two classes

The DatagramPacket object is the data container while the DatagramSocket is the mechanism

used to send or receive the DatagramPackets

iv) URL connection

URLConnection is a general-purpose class for accessing the attributes of a remote resource

Once you make a connection to a remote server you can use URLConnection to inspect the

Properties of the remote object before actually transporting it locally These attributes are

exposed by the HTTP protocol specification and as such only make sense for URL objects

that are using the HTTP protocol

URLConnection defines several methods

int getContentLength( )

String getContentType( )

long getDate( )

long getExpiration( )

String getHeaderField(int idx)

long getLastModified( )

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 28 of 38

c) Write a program to display three text fields and a button below to all an Applet Insert

the integer valuer from three text fields After pressing the button the background colour

of applet will be changed as per the RGB combination of the values given in the text field

(Correct logic - 6 Marks Syntax - 2 Marks)

4

Ans import javaawt

import javaawtevent

import javaapplet

ltapplet code=rdquoClrclassrdquo width=250 heigth=250gtltappletgt

public class Clrextends Applet implements ActionListener

int r g b

TextField t1t2t3

Button b1

Color c1

public void init()

t1= new TextField(5)

t2= new TextField(8)

t3= new TextField(11)

b1 = new Button(ldquo Set Colorrdquo)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 29 of 38

add(t1)

add(t2)

add(t3)

add(b1)

b1addActionListener(this)

public void void paint( )

setBackground(c1)

public void actionPerformed(ActionEvent ae)

r=IntegerparseInt(t1getText())

g=IntegerparseInt(t2getText())

b=IntegerparseInt(t3getText())

c1= new Color(rgb)

repaint()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 30 of 38

6) Attempt any four of the following Marks 16

a) How to check how many fonts are available in the computer system 4

Explain with example

(Explanation -2 Marks Example-2 Marks)

Ans When working with fonts often you need to know which fonts are available on your machine To

ontain this information you can use the getAvailableFontFamilyNames() method defined by the

GraphicsEnvironment classIt is shown here

String[ ] getAvailableFontFamilyNames( )

This method returns an array of string that contains the names of the available font families

Since this methods is members of GraphicsEnvironment you need a GraphicsEnvironment

reference to call itYou can obtain this reference by using the getlocalGrahicsEnvironmet() static

method which is derfined by GraphicsEnvironmentIt is shown here

static GraphicsEnvironment getLocalGraphicsEnvironment( )

Here is an applet that shown how to obtain the names of the available font families

ltapplet code=rdquoAllFontsrdquo width=500 height=100gt

ltappletgt

import javaapplet

import javaawt

public class AllFonts extends Applet

public void paint(Graphics g)

string fonts= ldquo rdquo

stirng allFontsList[]

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 31 of 38

GraphicsEnvironment t = GraphicsEnvironmentgetLocalGraphicsEnvironment()

allFontList = tgetAvailableFontFamilyNames()

for(int i= 0 ilt allFontsListlength i++)

fonts= fonts + allFontList[i] + ldquo rdquo

gdrawString(msg416)

b) Explain following check box class methods with appropriate example 4

i) Void setLable (String str) ii) Boolean getState ( )

(Explanation of each method-1 Marks Example-2 Marks)

Ans

i) void setLable(String str)

This method is used to set the label of check box

ii) Boolean getState()

This method is used to retrieve the current state of a check box It returns the value either true or

false depends on check box is selected or not

Example

Demonstrate check boxes

import javaawt

import javaawtevent

import javaapplet

ltapplet code=CheckboxDemo width=250 height=200gt

ltappletgt

public class CheckboxDemo extends Applet implements ItemListener

String msg =

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 32 of 38

Checkbox winXP winVista solaris mac

public void init()

winXP = new Checkbox(Windows XP null true)

mac = new Checkbox()

macsetLable(ldquoMac OSrdquo)

add(winXP)

add(mac)

winXPaddItemListener(this)

macaddItemListener(this)

public void itemStateChanged(ItemEvent ie)

repaint()

Display current state of the check boxes

public void paint(Graphics g)

msg = Current state

gdrawString(msg 6 80)

msg = Windows XP + winXPgetState()

gdrawString(msg 6 100)

msg = Mac OS + macgetState()

gdrawString(msg 6 120)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 33 of 38

c) Explain the techniques of session tracking management

(Any four techniques with explanation- 1 Mark each)

Ans Session tracking Techniques

1 User Authorization

Users can be authorized to use the web application in different ways Basic concept is that the

user will provide username and password to login to the application Based on that the user can

be identified and the session can be maintained

2 Hidden Fields

ltINPUT TYPE=rdquohiddenrdquo NAME=rdquotechnologyrdquo VALUE=rdquoservletrdquogt

Hidden fields like the above can be inserted in the webpages and information can be sent to the

server for session tracking These fields are not visible directly to the user but can be viewed

using view source option from the browsers This type doesnrsquot need any special configuration

from the browser of server and by default available to use for session tracking This cannot be

used for session tracking when the conversation included static resources lik html pages

3 URL Rewriting

Original URL httpserverportservletServletName

ewritten URL httpserverportservletServletNamesessionid=7456

When a request is made additional parameter is appended with the url In general added

additional parameter will be sessionid or sometimes the userid It will suffice to track the

session This type of session tracking doesnrsquot need any special support from the browser

Disadvantage is implementing this type of session tracking is tedious We need to keep track of

the parameter as a chain link until the conversation completes and also should make sure that

the parameter doesnrsquot clash with other application parameters

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 34 of 38

4 Cookies

Cookies are the mostly used technology for session tracking Cookie is a key value pair of

information sent by the server to the browser This should be saved by the browser in its space

in the client computer Whenever the browser sends a request to that server it sends the cookie

along with it Then the server can identify the client using the cookie

In java following is the source code snippet to create a cookie

Cookie cookie = new Cookie (ldquouserIDrdquo ldquo7456Prime)

resaddCookie(cookie)

5 Session tracking API

Session tracking API is built on top of the first four methods This is inorder to help the

developer to minimize the overhead of session tracking This type of session tracking is

provided by the underlying technology Lets take the java servlet example Then the servlet

container manages the session tracking task and the user need not do it explicitly using the java

servlets This is the best of all methods because all the management and errors related to

session tracking will be taken care of by the container itself

d) Give sequential steps for JTree in swing with example

(Steps- 2 Marks any small Example- 2 Marks)

Ans Steps for JTree

Atree is a component that presents a hierarchical view of data The user has the ability to

expand or collapse individual subtrees in this display Trees are implemented in Swing by

the JTree class

Here are the steps to follow to use a tree

1 Create an instance of JTree

2 Create a JScrollPane and specify the tree as the object to be scrolled

3 Add the tree to the scroll pane

4 Add the scroll pane to the content pane

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 35 of 38

Example

Demonstrate JTree

import javaawt

import javaxswingevent

import javaxswing

import javaxswingtree

ltapplet code=JTreeDemo width=400 height=200gt

ltappletgt

public class JTreeDemo extends JApplet

JTree tree

JLabel jlab

public void init()

try

SwingUtilitiesinvokeAndWait(

new Runnable()

public void run()

makeGUI()

)

catch (Exception exc)

Systemoutprintln(Cant create because of + exc)

private void makeGUI()

Create top node of tree

DefaultMutableTreeNode top = new DefaultMutableTreeNode(Options)

Create subtree of A

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 36 of 38

DefaultMutableTreeNode a = new DefaultMutableTreeNode(A)

topadd(a)

DefaultMutableTreeNode a1 = new DefaultMutableTreeNode(A1)

aadd(a1)

DefaultMutableTreeNode a2 = new DefaultMutableTreeNode(A2)

aadd(a2)

Create subtree of B

DefaultMutableTreeNode b = new DefaultMutableTreeNode(B)

topadd(b)

DefaultMutableTreeNode b1 = new DefaultMutableTreeNode(B1)

badd(b1)

DefaultMutableTreeNode b2 = new DefaultMutableTreeNode(B2)

badd(b2)

DefaultMutableTreeNode b3 = new DefaultMutableTreeNode(B3)

badd(b3)

Create the tree

tree = new JTree(top)

Add the tree to a scroll pane

JScrollPane jsp = new JScrollPane(tree)

Add the scroll pane to the content pane

add(jsp)

Add the label to the content pane

jlab = new JLabel()

add(jlab BorderLayoutSOUTH)

Handle tree selection events

treeaddTreeSelectionListener(new TreeSelectionListener()

public void valueChanged(TreeSelectionEvent tse)

jlabsetText(Selection is + tsegetPath())

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 37 of 38

e) Draw and explain the life cycle of servlet

(Explanation ndash 3 Marks Diagram -1 Marks)

Ans Three methods are central to the life cycle of a servlet

These are init( ) service( ) and destroy( )

They are implemented by every servlet and are invoked at specific times by the server Let

us consider a typical user scenario to understand when these methods are called

First assume that a user enters a Uniform Resource Locator (URL) to a web browser

The browser then generates an HTTP request for this URL This request is then sent to the

appropriate server

Second this HTTP request is received by the web server The server maps this request to

a particular servlet The servlet is dynamically retrieved and loaded into the address space

of the server

Third the server invokes the init( ) method of the servlet This method is invoked only

when the servlet is first loaded into memory It is possible to pass initialization parameters

to the servlet so it may configure itself

Fourth the server invokes the service( ) method of the servlet This method is called to

process the HTTP request You will see that it is possible for the servlet to read data that has

been provided in the HTTP request It may also formulate an HTTP response for the client

The servlet remains in the serverrsquos address space and is available to process any other

HTTP requests received from clients The service( ) method is called for each HTTP request

Finally the server may decide to unload the servlet from its memory The algorithms by

which this determination is made are specific to each server The server calls the destroy( )

method to relinquish any resources such as file handles that are allocated for the servlet

Important data may be saved to a persistent store The memory allocated for the servlet and

its objects can then be garbage collected

A servlet life cycle can be defined as the entire process from its creation till the destruction The

following are the paths followed by a servlet

The servlet is initialized by calling the init () method

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 38 of 38

The servlet calls service() method to process a clients request

The servlet is terminated by calling the destroy() method

Finally servlet is garbage collected by the garbage collector of the JVM

Initialization

(Load Resources)

Services

(Accept Requests)

Destruction

(Unload Resources)

Servlet

Request

Response

Page 15: AJP

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 15 of 38

d) Give the use of ImageIcon class with example 4

(Explanation ndash 2 Marks Example- 2 Marks)

Ans In Swing icons are encapsulated by the ImageIconclass which paints an icon from an

image Two of its constructors are shown here

ImageIcon(String filename)

ImageIcon(URL url)

The first form uses the image in the file named filename The second form uses the

image in the resource identified by url

The ImageIconclass implements the Icon interface that declares the methods

As follows

Method Description

intgetIconHeight( ) Returns the height of the iconin pixels

intgetIconWidth( ) Returns the width of the iconin pixels

voidpaintIcon(Component comp Graphics gintx inty)Paints the icon at position x y onthe

graphics context g Additionalinformation about the paintoperation can be provided in comp

Example

import javaawt

import javaxswing

ltapplet code=JLabelDemo width=250 height=150gt

ltappletgt

public class JLabelDemo extends JApplet

public void init()

Get content pane

Container contentPane = getContentPane()

Create an icon

ImageIcon ii = new ImageIcon(francegif)

Create a label

JLabeljl = new JLabel(France ii JLabelCENTER)

Add label to the content pane

contentPaneadd(jl)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 16 of 38

e) Give the use of URL class along with syntax of constructors of URL class 4

(Use - 2 Marks Any two Constructor - 1 Mark each)

Ans The URL provides a reasonably intelligible form to uniquely identify or address information on the

Internet URLs are ubiquitous every browser uses them to identify information on the Web In

fact the Web is really just that same old Internet with all of its resources addressed as URLs plus

HTML

Javas URL class has several constructors One commonly used form specifies the URL with a

string that is identical to what you see displayed in a browser

1 URL(String urlSpecifier)

The next two forms of the constructor allow you to break up the URL into its componentparts

2 URL(String protocolName String hostName intport String path)

3 URL(String protocolName String hostName String path)

Another frequently used constructor allows you to use an existing URL as a referencecontext and

then create a new URL from that context Although this sounds a littlecontorted its really quite

easy and useful

4 URL(URL urlObj String urlSpecifier)

4 A) Attempt any three of the following Marks 12

a) Give the use of following methods of statement interface 4

i) executeQuery( ) ii) execute Update ( )

(Each method ndash 2 Marks)

Ans i) executeQuery()

The executeQuery() method of the statement object enables you to send SQL select statement to

the database and to receive result from the database Executing a query in effect sends a SQL

select statement to the database and returns the appropriate results back in the Resultset object

The executeQuery() method takes a SQL select statement as a parameter and returns a ResultSet

object that contains all the records that match the select statements criteria

ii) executeUpdate()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 17 of 38

The executeUpdate() method of the Statement object enables you to execute SQL update

statements such as delete insert and update The method takes a String containing the SQL update

statement and returns an integers that determines how many records were affected by the SQL

statement

b) Define Layout Manager Describe the use of GridLayout Manager 4

(Layout manager- 2 Marks Use-2 Marks)

Ans Each Container object has a layout manager associated with it A layout manager

is an instance of any class that implements the LayoutManagerinterface The layout

manager is set by the setLayout( ) method If no call to setLayout( ) is made then the

default layout manager is used Whenever a container is resized (or sized for the first

time) the layout manager is used to position each of the components within it

The setLayout( ) method has the following general form

voidsetLayout(LayoutManagerlayoutObj)

GridLayoutManager

GridLayout lays out components in a two-dimensional grid When you instantiate

a GridLayout you define the number of rows and columns The constructors

supported by GridLayoutare shown here

GridLayout( )

GridLayout(intnumRows intnumColumns)

GridLayout(intnumRows intnumColumns inthorz intvert)

c) Explain the use of cookies with example 4

(Explanation - 2 Marks Example - 2 Marks any one)

Ans Cookie is a small piece of information that is passed back and forth in the HTTP request and

response Even though a cookie can be created on the client side using some scripting language

such as JavaScript it is usually created by the server resource such as a Servlet The Cookies sent

by the server when the client requests another page from the same application In Servlet

programming a cookie is represented by a Cookie class in the javaxservlethttp package You can

create a cookie by calling the Cookie class constructor and passing two string objects the name

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 18 of 38

and value of the cookie For instance the following code creates a cookie object called c1The

cookie has the name ldquomyCookierdquo and value of rdquosecretrdquo

Cookie c1=new Cookie(ldquomyCookierdquordquosecretrdquo)

You then can add the cookie to the http response using addCookie method of the

HTTPServletResponse interfaceResponseaddCookie(c1)

Program for Add cookies

import javaio

importjavaxservlet

importjavaxservlethttp

public class AddCookieServlet extends HttpServlet

public void doPost(HttpServletRequest requestHttpServletResponse response)

throwsServletException IOException

Get parameter from HTTP request

String data = requestgetParameter(data)

Create cookie

Cookie cookie = new Cookie(MyCookie data)

Add cookie to HTTP response

responseaddCookie(cookie)

Write output to browser

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgtMyCookie has been set to)

pwprintln(data)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 19 of 38

pwclose()

OR

Program for Get Cookies

import javaio

importjavaxservlet

importjavaxservlethttp

public class GetCookiesServlet extends HttpServlet

public void doGet(HttpServletRequest requestHttpServletResponse response)

throwsServletException IOException

Get cookies from header of HTTP request

Cookie[] cookies = requestgetCookies()

Display these cookies

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgt)

for(inti = 0 iltcookieslength i++)

String name = cookies[i]getName()

String value = cookies[i]getValue()

pwprintln(name = + name +

value = + value)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 20 of 38

pwclose()

d) Give steps to create simple servlet with example 4

(Steps- 2 Marks Any one Example ndash 2 Marks)

Ans Steps 1) Write a java servet code

Steps 2) Compile Servet by setting classpath with servlet-api library

Step 3) Copy the class servlet file in web apps classpath directory

Steps 4) Open the webxml open it and add servlet tag and sevlet mapping tag

Steps 5) Start web server(apche tomcat)

Steps 6) Browse servlet using java compatible browser like IE

Example shows to start create a file named WelcomeServletjava that contains the following

program

import javaio

importjavaxservlet

public class WelcomeServletDemo extends GenericServlet

public void service(ServletRequestrequestServletResponse response) throws

ServletExceptionIOException

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgtWelcome to Servlet)

pwclose()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 21 of 38

B) Attempt any one of the following Marks 6

a) Describe the two ndashtier and three ndashtier database design of JDBC API with neat diagram

(Explanation of Two-tier-2 Marks and Three-tier-2 Marks Diagram ndash 1 Mark each)

Ans Two Tier Architecture

In a two tier model a java application is designed to interact directly with the database

Application functionality is divided into these two layers

1) Application Layer Including the JDBC driver business logic and user interface

2) Database Layer including RDBMS

The interface to the database is handled by the Java Database Connectivity(JDBC) Driver

appropriate to the particularly database management system being accessed The JDBC Driver

passes SQL statements to the database and returns the results of those statements to the

application

A clientserver configuration is the special case of the two tier model where the database is

located on another machine referred to as the server The application runs on the client machine

which is connected to the server over a network Commonly the network is an Intranet using

dedicated database servers to support multiple clients but it can just as easily be the internet

Three Tier Architecture-

In the three tier model the client typically sends requests to an application server forming the

middle tier The application server interprets these requests and formats the necessary SQL

statement to fulfill

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 22 of 38

These requests and sends them to the database The database process the SQL statements and

sends result back to the application server which then sends them to the client

Following are some advantages of Three-tier architecture

1 Performance can be improved by separating the application server and database server

2 Business logic is clearly separated from the database

3 Client application can use a simple protocol such as CGI to access services

The three-tier model show in following fig is a common in web application In this scenario the

client tier is frequently implemented in a browse on a client machine the middle tier is

implemented in a web server with a Servlet engine and the database management system runs on

a dedicated database server

Following are the main components of three tier architecture

1 Client Tier - Typically this is thin presentation layer that may be implemented using a web

browser

2 Middle Tier - This tier handles the business or application logic This may be implemented

using a Servlet engine such as Tomcat or an application server such as JBOSS The JDBC

driver also resides in this layer

3 Data source layer This component includes the RDBMS

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 23 of 38

b) Write servlet which shows how many times user has visited the page in session

(Any Correct Logic ndash4 Marks Syntax ndash 2 Marks)

Ans import javaio

import javaxservlet

import javaxservlethttp

public class Session Travker extends HttpServlet

public void doGet(HttpServletRequest req HttpServletResponse res) throws ServletException

IOException

ressetContentType(ldquotexthtmlrdquo)

PrintWriter out = resgetWriter()

HttpSession session = reqgetSession(true)

Integer count= (Integer)sessiongetValue(ldquotrackercountrdquo)

if(count== null) count=new Interger(1)

else count = new Interger(count intValue() +1)

sessionputValue(ldquotrackercountrdquocount)

outprintln(ldquoltHTMLgtltHEADgtltTITLEgtSession TrackerltTITLEgtltHEADgtrdquo)

outprintln(ldquoltBODYgtltH1gtSession Tracking DemoltH1gtrdquo)

outprintln(ldquoYou have visited this pagerdquo +count +((countintValue() == 1)rdquotimerdquo

ldquotimesrdquo))outprinln(ltPgtrdquo)

outprintln(ldquoltH2gtSesssion dataltH2gtrdquo)

String[] names = sessiongetValueNames()

for(int i=0 ilt nameslength i++)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 24 of 38

outprintln(names[i] + ldquo rdquo + sessiongetvalue(names[i])+ ldquoltBRgtrdquo)

outprintln(ldquoltBODYgtltHTMLgtrdquo)

5 Attempt any two of the following Marks 16

a) Write a program to display all records from Employee table from database using

JDBC

(Assume suitable data for table- Load driver create connection execute Query - 1 Mark

each Display data- 3 Marks Syntax ndash 2 Marks)

Ans import javasql

import javasqlStatement

import javaapplet

import javaawt

public class DisplayTable

public static void main( String args[])

RsultSet rs

Connection conn

try

String s1

ClassforName(sun jdbcodbcJdbcOdbcDriver)

Systemoutprintln(Connecting to a selected database)

String url=rdquojdbcodbcabcrdquo

conn = DriverManagergetConnection(DB_URL USER PASS)

Systemoutprintln(Connected database successfully)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 25 of 38

Systemoutprintln(Creating statement)

stmt = conncreateStatement()

sql = SELECT FROM Employee

ResultSet rs = stmtexecuteQuery(sql)

Tables fields assumed are id first last age

while(rsnext())

int id = rsgetInt(id)

int age = rsgetInt(age)

String first = rsgetString(first)

String last = rsgetString(last)

Systemoutprint(ID + id)

Systemoutprint( Age + age)

Systemoutprint( First + first)

Systemoutprintln( Last + last)

rsclose()

catch(SQLException se)

Handle errors for JDBC

seprintStackTrace()

catch(Exception e)

Handle errors for ClassforName

eprintStackTrace()

finally

finally block used to close resources

try

if(stmt=null)

connclose()

catch(SQLException se)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 26 of 38

b) Define the term

i) Reserved socket ii) proxy server

iii) Datagram iv) URL connection 4

(Each term- 2 Marks)

Ans i) Reserved socket

A socket is one end-point of a two-way communication link between two programs running on

the network Socket classes are used to represent the connection between a client program and a

server program

Reserved socket The socket which are reserved for specific protocols for communication

purpose are known as reseved sockets

TCPIP uses or reserves the lower 1024 ports for specific protocols

Example port number 23 is for Telnet 25 is for smtp 21 is for ftp 13 for daytime 110 for pop3

and so on Protocol decides how a client should interact with the port

ii) Proxy server

A proxy server is a computer that offers a computer network service to allow clients to make

indirect network connections to other network services A client connects to the proxy server

then requests a connection file or other resource available on a different server The proxy

provides the resource either by connecting to the specified server or by serving it from a cache In

some cases the proxy may alter the clients request or the servers response for various purposes

Purposes of the proxy servers

To keep machines behind it anonymous mainly for security

To speed up access to resources (using caching) Web proxies are commonly used to

cache web pages from a web server

To prevent downloading the same content multiple times (and save bandwidth)

To log audit usage eg to provide company employee Internet usage reporting

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 27 of 38

To scan transmitted content for malware before delivery

To scan outbound content eg for data loss prevention

iii) Datagram

Datagrams are bundles of information passed between machines They are somewhat like a hard

throw from a well-trained but blindfolded catcher to the third baseman Once the datagram has

been released to its intended target there is no assurance that it will arrive or even that

someone will be there to catch it Likewise when the datagram is received there is no

assurance that it hasnrsquot been damaged in transit or that whoever sent it is still there to receive a

response

Java implements datagrams on top of the UDP protocol by using two classes

The DatagramPacket object is the data container while the DatagramSocket is the mechanism

used to send or receive the DatagramPackets

iv) URL connection

URLConnection is a general-purpose class for accessing the attributes of a remote resource

Once you make a connection to a remote server you can use URLConnection to inspect the

Properties of the remote object before actually transporting it locally These attributes are

exposed by the HTTP protocol specification and as such only make sense for URL objects

that are using the HTTP protocol

URLConnection defines several methods

int getContentLength( )

String getContentType( )

long getDate( )

long getExpiration( )

String getHeaderField(int idx)

long getLastModified( )

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 28 of 38

c) Write a program to display three text fields and a button below to all an Applet Insert

the integer valuer from three text fields After pressing the button the background colour

of applet will be changed as per the RGB combination of the values given in the text field

(Correct logic - 6 Marks Syntax - 2 Marks)

4

Ans import javaawt

import javaawtevent

import javaapplet

ltapplet code=rdquoClrclassrdquo width=250 heigth=250gtltappletgt

public class Clrextends Applet implements ActionListener

int r g b

TextField t1t2t3

Button b1

Color c1

public void init()

t1= new TextField(5)

t2= new TextField(8)

t3= new TextField(11)

b1 = new Button(ldquo Set Colorrdquo)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 29 of 38

add(t1)

add(t2)

add(t3)

add(b1)

b1addActionListener(this)

public void void paint( )

setBackground(c1)

public void actionPerformed(ActionEvent ae)

r=IntegerparseInt(t1getText())

g=IntegerparseInt(t2getText())

b=IntegerparseInt(t3getText())

c1= new Color(rgb)

repaint()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 30 of 38

6) Attempt any four of the following Marks 16

a) How to check how many fonts are available in the computer system 4

Explain with example

(Explanation -2 Marks Example-2 Marks)

Ans When working with fonts often you need to know which fonts are available on your machine To

ontain this information you can use the getAvailableFontFamilyNames() method defined by the

GraphicsEnvironment classIt is shown here

String[ ] getAvailableFontFamilyNames( )

This method returns an array of string that contains the names of the available font families

Since this methods is members of GraphicsEnvironment you need a GraphicsEnvironment

reference to call itYou can obtain this reference by using the getlocalGrahicsEnvironmet() static

method which is derfined by GraphicsEnvironmentIt is shown here

static GraphicsEnvironment getLocalGraphicsEnvironment( )

Here is an applet that shown how to obtain the names of the available font families

ltapplet code=rdquoAllFontsrdquo width=500 height=100gt

ltappletgt

import javaapplet

import javaawt

public class AllFonts extends Applet

public void paint(Graphics g)

string fonts= ldquo rdquo

stirng allFontsList[]

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 31 of 38

GraphicsEnvironment t = GraphicsEnvironmentgetLocalGraphicsEnvironment()

allFontList = tgetAvailableFontFamilyNames()

for(int i= 0 ilt allFontsListlength i++)

fonts= fonts + allFontList[i] + ldquo rdquo

gdrawString(msg416)

b) Explain following check box class methods with appropriate example 4

i) Void setLable (String str) ii) Boolean getState ( )

(Explanation of each method-1 Marks Example-2 Marks)

Ans

i) void setLable(String str)

This method is used to set the label of check box

ii) Boolean getState()

This method is used to retrieve the current state of a check box It returns the value either true or

false depends on check box is selected or not

Example

Demonstrate check boxes

import javaawt

import javaawtevent

import javaapplet

ltapplet code=CheckboxDemo width=250 height=200gt

ltappletgt

public class CheckboxDemo extends Applet implements ItemListener

String msg =

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 32 of 38

Checkbox winXP winVista solaris mac

public void init()

winXP = new Checkbox(Windows XP null true)

mac = new Checkbox()

macsetLable(ldquoMac OSrdquo)

add(winXP)

add(mac)

winXPaddItemListener(this)

macaddItemListener(this)

public void itemStateChanged(ItemEvent ie)

repaint()

Display current state of the check boxes

public void paint(Graphics g)

msg = Current state

gdrawString(msg 6 80)

msg = Windows XP + winXPgetState()

gdrawString(msg 6 100)

msg = Mac OS + macgetState()

gdrawString(msg 6 120)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 33 of 38

c) Explain the techniques of session tracking management

(Any four techniques with explanation- 1 Mark each)

Ans Session tracking Techniques

1 User Authorization

Users can be authorized to use the web application in different ways Basic concept is that the

user will provide username and password to login to the application Based on that the user can

be identified and the session can be maintained

2 Hidden Fields

ltINPUT TYPE=rdquohiddenrdquo NAME=rdquotechnologyrdquo VALUE=rdquoservletrdquogt

Hidden fields like the above can be inserted in the webpages and information can be sent to the

server for session tracking These fields are not visible directly to the user but can be viewed

using view source option from the browsers This type doesnrsquot need any special configuration

from the browser of server and by default available to use for session tracking This cannot be

used for session tracking when the conversation included static resources lik html pages

3 URL Rewriting

Original URL httpserverportservletServletName

ewritten URL httpserverportservletServletNamesessionid=7456

When a request is made additional parameter is appended with the url In general added

additional parameter will be sessionid or sometimes the userid It will suffice to track the

session This type of session tracking doesnrsquot need any special support from the browser

Disadvantage is implementing this type of session tracking is tedious We need to keep track of

the parameter as a chain link until the conversation completes and also should make sure that

the parameter doesnrsquot clash with other application parameters

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 34 of 38

4 Cookies

Cookies are the mostly used technology for session tracking Cookie is a key value pair of

information sent by the server to the browser This should be saved by the browser in its space

in the client computer Whenever the browser sends a request to that server it sends the cookie

along with it Then the server can identify the client using the cookie

In java following is the source code snippet to create a cookie

Cookie cookie = new Cookie (ldquouserIDrdquo ldquo7456Prime)

resaddCookie(cookie)

5 Session tracking API

Session tracking API is built on top of the first four methods This is inorder to help the

developer to minimize the overhead of session tracking This type of session tracking is

provided by the underlying technology Lets take the java servlet example Then the servlet

container manages the session tracking task and the user need not do it explicitly using the java

servlets This is the best of all methods because all the management and errors related to

session tracking will be taken care of by the container itself

d) Give sequential steps for JTree in swing with example

(Steps- 2 Marks any small Example- 2 Marks)

Ans Steps for JTree

Atree is a component that presents a hierarchical view of data The user has the ability to

expand or collapse individual subtrees in this display Trees are implemented in Swing by

the JTree class

Here are the steps to follow to use a tree

1 Create an instance of JTree

2 Create a JScrollPane and specify the tree as the object to be scrolled

3 Add the tree to the scroll pane

4 Add the scroll pane to the content pane

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 35 of 38

Example

Demonstrate JTree

import javaawt

import javaxswingevent

import javaxswing

import javaxswingtree

ltapplet code=JTreeDemo width=400 height=200gt

ltappletgt

public class JTreeDemo extends JApplet

JTree tree

JLabel jlab

public void init()

try

SwingUtilitiesinvokeAndWait(

new Runnable()

public void run()

makeGUI()

)

catch (Exception exc)

Systemoutprintln(Cant create because of + exc)

private void makeGUI()

Create top node of tree

DefaultMutableTreeNode top = new DefaultMutableTreeNode(Options)

Create subtree of A

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 36 of 38

DefaultMutableTreeNode a = new DefaultMutableTreeNode(A)

topadd(a)

DefaultMutableTreeNode a1 = new DefaultMutableTreeNode(A1)

aadd(a1)

DefaultMutableTreeNode a2 = new DefaultMutableTreeNode(A2)

aadd(a2)

Create subtree of B

DefaultMutableTreeNode b = new DefaultMutableTreeNode(B)

topadd(b)

DefaultMutableTreeNode b1 = new DefaultMutableTreeNode(B1)

badd(b1)

DefaultMutableTreeNode b2 = new DefaultMutableTreeNode(B2)

badd(b2)

DefaultMutableTreeNode b3 = new DefaultMutableTreeNode(B3)

badd(b3)

Create the tree

tree = new JTree(top)

Add the tree to a scroll pane

JScrollPane jsp = new JScrollPane(tree)

Add the scroll pane to the content pane

add(jsp)

Add the label to the content pane

jlab = new JLabel()

add(jlab BorderLayoutSOUTH)

Handle tree selection events

treeaddTreeSelectionListener(new TreeSelectionListener()

public void valueChanged(TreeSelectionEvent tse)

jlabsetText(Selection is + tsegetPath())

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 37 of 38

e) Draw and explain the life cycle of servlet

(Explanation ndash 3 Marks Diagram -1 Marks)

Ans Three methods are central to the life cycle of a servlet

These are init( ) service( ) and destroy( )

They are implemented by every servlet and are invoked at specific times by the server Let

us consider a typical user scenario to understand when these methods are called

First assume that a user enters a Uniform Resource Locator (URL) to a web browser

The browser then generates an HTTP request for this URL This request is then sent to the

appropriate server

Second this HTTP request is received by the web server The server maps this request to

a particular servlet The servlet is dynamically retrieved and loaded into the address space

of the server

Third the server invokes the init( ) method of the servlet This method is invoked only

when the servlet is first loaded into memory It is possible to pass initialization parameters

to the servlet so it may configure itself

Fourth the server invokes the service( ) method of the servlet This method is called to

process the HTTP request You will see that it is possible for the servlet to read data that has

been provided in the HTTP request It may also formulate an HTTP response for the client

The servlet remains in the serverrsquos address space and is available to process any other

HTTP requests received from clients The service( ) method is called for each HTTP request

Finally the server may decide to unload the servlet from its memory The algorithms by

which this determination is made are specific to each server The server calls the destroy( )

method to relinquish any resources such as file handles that are allocated for the servlet

Important data may be saved to a persistent store The memory allocated for the servlet and

its objects can then be garbage collected

A servlet life cycle can be defined as the entire process from its creation till the destruction The

following are the paths followed by a servlet

The servlet is initialized by calling the init () method

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 38 of 38

The servlet calls service() method to process a clients request

The servlet is terminated by calling the destroy() method

Finally servlet is garbage collected by the garbage collector of the JVM

Initialization

(Load Resources)

Services

(Accept Requests)

Destruction

(Unload Resources)

Servlet

Request

Response

Page 16: AJP

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 16 of 38

e) Give the use of URL class along with syntax of constructors of URL class 4

(Use - 2 Marks Any two Constructor - 1 Mark each)

Ans The URL provides a reasonably intelligible form to uniquely identify or address information on the

Internet URLs are ubiquitous every browser uses them to identify information on the Web In

fact the Web is really just that same old Internet with all of its resources addressed as URLs plus

HTML

Javas URL class has several constructors One commonly used form specifies the URL with a

string that is identical to what you see displayed in a browser

1 URL(String urlSpecifier)

The next two forms of the constructor allow you to break up the URL into its componentparts

2 URL(String protocolName String hostName intport String path)

3 URL(String protocolName String hostName String path)

Another frequently used constructor allows you to use an existing URL as a referencecontext and

then create a new URL from that context Although this sounds a littlecontorted its really quite

easy and useful

4 URL(URL urlObj String urlSpecifier)

4 A) Attempt any three of the following Marks 12

a) Give the use of following methods of statement interface 4

i) executeQuery( ) ii) execute Update ( )

(Each method ndash 2 Marks)

Ans i) executeQuery()

The executeQuery() method of the statement object enables you to send SQL select statement to

the database and to receive result from the database Executing a query in effect sends a SQL

select statement to the database and returns the appropriate results back in the Resultset object

The executeQuery() method takes a SQL select statement as a parameter and returns a ResultSet

object that contains all the records that match the select statements criteria

ii) executeUpdate()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 17 of 38

The executeUpdate() method of the Statement object enables you to execute SQL update

statements such as delete insert and update The method takes a String containing the SQL update

statement and returns an integers that determines how many records were affected by the SQL

statement

b) Define Layout Manager Describe the use of GridLayout Manager 4

(Layout manager- 2 Marks Use-2 Marks)

Ans Each Container object has a layout manager associated with it A layout manager

is an instance of any class that implements the LayoutManagerinterface The layout

manager is set by the setLayout( ) method If no call to setLayout( ) is made then the

default layout manager is used Whenever a container is resized (or sized for the first

time) the layout manager is used to position each of the components within it

The setLayout( ) method has the following general form

voidsetLayout(LayoutManagerlayoutObj)

GridLayoutManager

GridLayout lays out components in a two-dimensional grid When you instantiate

a GridLayout you define the number of rows and columns The constructors

supported by GridLayoutare shown here

GridLayout( )

GridLayout(intnumRows intnumColumns)

GridLayout(intnumRows intnumColumns inthorz intvert)

c) Explain the use of cookies with example 4

(Explanation - 2 Marks Example - 2 Marks any one)

Ans Cookie is a small piece of information that is passed back and forth in the HTTP request and

response Even though a cookie can be created on the client side using some scripting language

such as JavaScript it is usually created by the server resource such as a Servlet The Cookies sent

by the server when the client requests another page from the same application In Servlet

programming a cookie is represented by a Cookie class in the javaxservlethttp package You can

create a cookie by calling the Cookie class constructor and passing two string objects the name

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 18 of 38

and value of the cookie For instance the following code creates a cookie object called c1The

cookie has the name ldquomyCookierdquo and value of rdquosecretrdquo

Cookie c1=new Cookie(ldquomyCookierdquordquosecretrdquo)

You then can add the cookie to the http response using addCookie method of the

HTTPServletResponse interfaceResponseaddCookie(c1)

Program for Add cookies

import javaio

importjavaxservlet

importjavaxservlethttp

public class AddCookieServlet extends HttpServlet

public void doPost(HttpServletRequest requestHttpServletResponse response)

throwsServletException IOException

Get parameter from HTTP request

String data = requestgetParameter(data)

Create cookie

Cookie cookie = new Cookie(MyCookie data)

Add cookie to HTTP response

responseaddCookie(cookie)

Write output to browser

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgtMyCookie has been set to)

pwprintln(data)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 19 of 38

pwclose()

OR

Program for Get Cookies

import javaio

importjavaxservlet

importjavaxservlethttp

public class GetCookiesServlet extends HttpServlet

public void doGet(HttpServletRequest requestHttpServletResponse response)

throwsServletException IOException

Get cookies from header of HTTP request

Cookie[] cookies = requestgetCookies()

Display these cookies

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgt)

for(inti = 0 iltcookieslength i++)

String name = cookies[i]getName()

String value = cookies[i]getValue()

pwprintln(name = + name +

value = + value)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 20 of 38

pwclose()

d) Give steps to create simple servlet with example 4

(Steps- 2 Marks Any one Example ndash 2 Marks)

Ans Steps 1) Write a java servet code

Steps 2) Compile Servet by setting classpath with servlet-api library

Step 3) Copy the class servlet file in web apps classpath directory

Steps 4) Open the webxml open it and add servlet tag and sevlet mapping tag

Steps 5) Start web server(apche tomcat)

Steps 6) Browse servlet using java compatible browser like IE

Example shows to start create a file named WelcomeServletjava that contains the following

program

import javaio

importjavaxservlet

public class WelcomeServletDemo extends GenericServlet

public void service(ServletRequestrequestServletResponse response) throws

ServletExceptionIOException

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgtWelcome to Servlet)

pwclose()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 21 of 38

B) Attempt any one of the following Marks 6

a) Describe the two ndashtier and three ndashtier database design of JDBC API with neat diagram

(Explanation of Two-tier-2 Marks and Three-tier-2 Marks Diagram ndash 1 Mark each)

Ans Two Tier Architecture

In a two tier model a java application is designed to interact directly with the database

Application functionality is divided into these two layers

1) Application Layer Including the JDBC driver business logic and user interface

2) Database Layer including RDBMS

The interface to the database is handled by the Java Database Connectivity(JDBC) Driver

appropriate to the particularly database management system being accessed The JDBC Driver

passes SQL statements to the database and returns the results of those statements to the

application

A clientserver configuration is the special case of the two tier model where the database is

located on another machine referred to as the server The application runs on the client machine

which is connected to the server over a network Commonly the network is an Intranet using

dedicated database servers to support multiple clients but it can just as easily be the internet

Three Tier Architecture-

In the three tier model the client typically sends requests to an application server forming the

middle tier The application server interprets these requests and formats the necessary SQL

statement to fulfill

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 22 of 38

These requests and sends them to the database The database process the SQL statements and

sends result back to the application server which then sends them to the client

Following are some advantages of Three-tier architecture

1 Performance can be improved by separating the application server and database server

2 Business logic is clearly separated from the database

3 Client application can use a simple protocol such as CGI to access services

The three-tier model show in following fig is a common in web application In this scenario the

client tier is frequently implemented in a browse on a client machine the middle tier is

implemented in a web server with a Servlet engine and the database management system runs on

a dedicated database server

Following are the main components of three tier architecture

1 Client Tier - Typically this is thin presentation layer that may be implemented using a web

browser

2 Middle Tier - This tier handles the business or application logic This may be implemented

using a Servlet engine such as Tomcat or an application server such as JBOSS The JDBC

driver also resides in this layer

3 Data source layer This component includes the RDBMS

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 23 of 38

b) Write servlet which shows how many times user has visited the page in session

(Any Correct Logic ndash4 Marks Syntax ndash 2 Marks)

Ans import javaio

import javaxservlet

import javaxservlethttp

public class Session Travker extends HttpServlet

public void doGet(HttpServletRequest req HttpServletResponse res) throws ServletException

IOException

ressetContentType(ldquotexthtmlrdquo)

PrintWriter out = resgetWriter()

HttpSession session = reqgetSession(true)

Integer count= (Integer)sessiongetValue(ldquotrackercountrdquo)

if(count== null) count=new Interger(1)

else count = new Interger(count intValue() +1)

sessionputValue(ldquotrackercountrdquocount)

outprintln(ldquoltHTMLgtltHEADgtltTITLEgtSession TrackerltTITLEgtltHEADgtrdquo)

outprintln(ldquoltBODYgtltH1gtSession Tracking DemoltH1gtrdquo)

outprintln(ldquoYou have visited this pagerdquo +count +((countintValue() == 1)rdquotimerdquo

ldquotimesrdquo))outprinln(ltPgtrdquo)

outprintln(ldquoltH2gtSesssion dataltH2gtrdquo)

String[] names = sessiongetValueNames()

for(int i=0 ilt nameslength i++)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 24 of 38

outprintln(names[i] + ldquo rdquo + sessiongetvalue(names[i])+ ldquoltBRgtrdquo)

outprintln(ldquoltBODYgtltHTMLgtrdquo)

5 Attempt any two of the following Marks 16

a) Write a program to display all records from Employee table from database using

JDBC

(Assume suitable data for table- Load driver create connection execute Query - 1 Mark

each Display data- 3 Marks Syntax ndash 2 Marks)

Ans import javasql

import javasqlStatement

import javaapplet

import javaawt

public class DisplayTable

public static void main( String args[])

RsultSet rs

Connection conn

try

String s1

ClassforName(sun jdbcodbcJdbcOdbcDriver)

Systemoutprintln(Connecting to a selected database)

String url=rdquojdbcodbcabcrdquo

conn = DriverManagergetConnection(DB_URL USER PASS)

Systemoutprintln(Connected database successfully)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 25 of 38

Systemoutprintln(Creating statement)

stmt = conncreateStatement()

sql = SELECT FROM Employee

ResultSet rs = stmtexecuteQuery(sql)

Tables fields assumed are id first last age

while(rsnext())

int id = rsgetInt(id)

int age = rsgetInt(age)

String first = rsgetString(first)

String last = rsgetString(last)

Systemoutprint(ID + id)

Systemoutprint( Age + age)

Systemoutprint( First + first)

Systemoutprintln( Last + last)

rsclose()

catch(SQLException se)

Handle errors for JDBC

seprintStackTrace()

catch(Exception e)

Handle errors for ClassforName

eprintStackTrace()

finally

finally block used to close resources

try

if(stmt=null)

connclose()

catch(SQLException se)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 26 of 38

b) Define the term

i) Reserved socket ii) proxy server

iii) Datagram iv) URL connection 4

(Each term- 2 Marks)

Ans i) Reserved socket

A socket is one end-point of a two-way communication link between two programs running on

the network Socket classes are used to represent the connection between a client program and a

server program

Reserved socket The socket which are reserved for specific protocols for communication

purpose are known as reseved sockets

TCPIP uses or reserves the lower 1024 ports for specific protocols

Example port number 23 is for Telnet 25 is for smtp 21 is for ftp 13 for daytime 110 for pop3

and so on Protocol decides how a client should interact with the port

ii) Proxy server

A proxy server is a computer that offers a computer network service to allow clients to make

indirect network connections to other network services A client connects to the proxy server

then requests a connection file or other resource available on a different server The proxy

provides the resource either by connecting to the specified server or by serving it from a cache In

some cases the proxy may alter the clients request or the servers response for various purposes

Purposes of the proxy servers

To keep machines behind it anonymous mainly for security

To speed up access to resources (using caching) Web proxies are commonly used to

cache web pages from a web server

To prevent downloading the same content multiple times (and save bandwidth)

To log audit usage eg to provide company employee Internet usage reporting

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 27 of 38

To scan transmitted content for malware before delivery

To scan outbound content eg for data loss prevention

iii) Datagram

Datagrams are bundles of information passed between machines They are somewhat like a hard

throw from a well-trained but blindfolded catcher to the third baseman Once the datagram has

been released to its intended target there is no assurance that it will arrive or even that

someone will be there to catch it Likewise when the datagram is received there is no

assurance that it hasnrsquot been damaged in transit or that whoever sent it is still there to receive a

response

Java implements datagrams on top of the UDP protocol by using two classes

The DatagramPacket object is the data container while the DatagramSocket is the mechanism

used to send or receive the DatagramPackets

iv) URL connection

URLConnection is a general-purpose class for accessing the attributes of a remote resource

Once you make a connection to a remote server you can use URLConnection to inspect the

Properties of the remote object before actually transporting it locally These attributes are

exposed by the HTTP protocol specification and as such only make sense for URL objects

that are using the HTTP protocol

URLConnection defines several methods

int getContentLength( )

String getContentType( )

long getDate( )

long getExpiration( )

String getHeaderField(int idx)

long getLastModified( )

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 28 of 38

c) Write a program to display three text fields and a button below to all an Applet Insert

the integer valuer from three text fields After pressing the button the background colour

of applet will be changed as per the RGB combination of the values given in the text field

(Correct logic - 6 Marks Syntax - 2 Marks)

4

Ans import javaawt

import javaawtevent

import javaapplet

ltapplet code=rdquoClrclassrdquo width=250 heigth=250gtltappletgt

public class Clrextends Applet implements ActionListener

int r g b

TextField t1t2t3

Button b1

Color c1

public void init()

t1= new TextField(5)

t2= new TextField(8)

t3= new TextField(11)

b1 = new Button(ldquo Set Colorrdquo)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 29 of 38

add(t1)

add(t2)

add(t3)

add(b1)

b1addActionListener(this)

public void void paint( )

setBackground(c1)

public void actionPerformed(ActionEvent ae)

r=IntegerparseInt(t1getText())

g=IntegerparseInt(t2getText())

b=IntegerparseInt(t3getText())

c1= new Color(rgb)

repaint()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 30 of 38

6) Attempt any four of the following Marks 16

a) How to check how many fonts are available in the computer system 4

Explain with example

(Explanation -2 Marks Example-2 Marks)

Ans When working with fonts often you need to know which fonts are available on your machine To

ontain this information you can use the getAvailableFontFamilyNames() method defined by the

GraphicsEnvironment classIt is shown here

String[ ] getAvailableFontFamilyNames( )

This method returns an array of string that contains the names of the available font families

Since this methods is members of GraphicsEnvironment you need a GraphicsEnvironment

reference to call itYou can obtain this reference by using the getlocalGrahicsEnvironmet() static

method which is derfined by GraphicsEnvironmentIt is shown here

static GraphicsEnvironment getLocalGraphicsEnvironment( )

Here is an applet that shown how to obtain the names of the available font families

ltapplet code=rdquoAllFontsrdquo width=500 height=100gt

ltappletgt

import javaapplet

import javaawt

public class AllFonts extends Applet

public void paint(Graphics g)

string fonts= ldquo rdquo

stirng allFontsList[]

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 31 of 38

GraphicsEnvironment t = GraphicsEnvironmentgetLocalGraphicsEnvironment()

allFontList = tgetAvailableFontFamilyNames()

for(int i= 0 ilt allFontsListlength i++)

fonts= fonts + allFontList[i] + ldquo rdquo

gdrawString(msg416)

b) Explain following check box class methods with appropriate example 4

i) Void setLable (String str) ii) Boolean getState ( )

(Explanation of each method-1 Marks Example-2 Marks)

Ans

i) void setLable(String str)

This method is used to set the label of check box

ii) Boolean getState()

This method is used to retrieve the current state of a check box It returns the value either true or

false depends on check box is selected or not

Example

Demonstrate check boxes

import javaawt

import javaawtevent

import javaapplet

ltapplet code=CheckboxDemo width=250 height=200gt

ltappletgt

public class CheckboxDemo extends Applet implements ItemListener

String msg =

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 32 of 38

Checkbox winXP winVista solaris mac

public void init()

winXP = new Checkbox(Windows XP null true)

mac = new Checkbox()

macsetLable(ldquoMac OSrdquo)

add(winXP)

add(mac)

winXPaddItemListener(this)

macaddItemListener(this)

public void itemStateChanged(ItemEvent ie)

repaint()

Display current state of the check boxes

public void paint(Graphics g)

msg = Current state

gdrawString(msg 6 80)

msg = Windows XP + winXPgetState()

gdrawString(msg 6 100)

msg = Mac OS + macgetState()

gdrawString(msg 6 120)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 33 of 38

c) Explain the techniques of session tracking management

(Any four techniques with explanation- 1 Mark each)

Ans Session tracking Techniques

1 User Authorization

Users can be authorized to use the web application in different ways Basic concept is that the

user will provide username and password to login to the application Based on that the user can

be identified and the session can be maintained

2 Hidden Fields

ltINPUT TYPE=rdquohiddenrdquo NAME=rdquotechnologyrdquo VALUE=rdquoservletrdquogt

Hidden fields like the above can be inserted in the webpages and information can be sent to the

server for session tracking These fields are not visible directly to the user but can be viewed

using view source option from the browsers This type doesnrsquot need any special configuration

from the browser of server and by default available to use for session tracking This cannot be

used for session tracking when the conversation included static resources lik html pages

3 URL Rewriting

Original URL httpserverportservletServletName

ewritten URL httpserverportservletServletNamesessionid=7456

When a request is made additional parameter is appended with the url In general added

additional parameter will be sessionid or sometimes the userid It will suffice to track the

session This type of session tracking doesnrsquot need any special support from the browser

Disadvantage is implementing this type of session tracking is tedious We need to keep track of

the parameter as a chain link until the conversation completes and also should make sure that

the parameter doesnrsquot clash with other application parameters

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 34 of 38

4 Cookies

Cookies are the mostly used technology for session tracking Cookie is a key value pair of

information sent by the server to the browser This should be saved by the browser in its space

in the client computer Whenever the browser sends a request to that server it sends the cookie

along with it Then the server can identify the client using the cookie

In java following is the source code snippet to create a cookie

Cookie cookie = new Cookie (ldquouserIDrdquo ldquo7456Prime)

resaddCookie(cookie)

5 Session tracking API

Session tracking API is built on top of the first four methods This is inorder to help the

developer to minimize the overhead of session tracking This type of session tracking is

provided by the underlying technology Lets take the java servlet example Then the servlet

container manages the session tracking task and the user need not do it explicitly using the java

servlets This is the best of all methods because all the management and errors related to

session tracking will be taken care of by the container itself

d) Give sequential steps for JTree in swing with example

(Steps- 2 Marks any small Example- 2 Marks)

Ans Steps for JTree

Atree is a component that presents a hierarchical view of data The user has the ability to

expand or collapse individual subtrees in this display Trees are implemented in Swing by

the JTree class

Here are the steps to follow to use a tree

1 Create an instance of JTree

2 Create a JScrollPane and specify the tree as the object to be scrolled

3 Add the tree to the scroll pane

4 Add the scroll pane to the content pane

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 35 of 38

Example

Demonstrate JTree

import javaawt

import javaxswingevent

import javaxswing

import javaxswingtree

ltapplet code=JTreeDemo width=400 height=200gt

ltappletgt

public class JTreeDemo extends JApplet

JTree tree

JLabel jlab

public void init()

try

SwingUtilitiesinvokeAndWait(

new Runnable()

public void run()

makeGUI()

)

catch (Exception exc)

Systemoutprintln(Cant create because of + exc)

private void makeGUI()

Create top node of tree

DefaultMutableTreeNode top = new DefaultMutableTreeNode(Options)

Create subtree of A

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 36 of 38

DefaultMutableTreeNode a = new DefaultMutableTreeNode(A)

topadd(a)

DefaultMutableTreeNode a1 = new DefaultMutableTreeNode(A1)

aadd(a1)

DefaultMutableTreeNode a2 = new DefaultMutableTreeNode(A2)

aadd(a2)

Create subtree of B

DefaultMutableTreeNode b = new DefaultMutableTreeNode(B)

topadd(b)

DefaultMutableTreeNode b1 = new DefaultMutableTreeNode(B1)

badd(b1)

DefaultMutableTreeNode b2 = new DefaultMutableTreeNode(B2)

badd(b2)

DefaultMutableTreeNode b3 = new DefaultMutableTreeNode(B3)

badd(b3)

Create the tree

tree = new JTree(top)

Add the tree to a scroll pane

JScrollPane jsp = new JScrollPane(tree)

Add the scroll pane to the content pane

add(jsp)

Add the label to the content pane

jlab = new JLabel()

add(jlab BorderLayoutSOUTH)

Handle tree selection events

treeaddTreeSelectionListener(new TreeSelectionListener()

public void valueChanged(TreeSelectionEvent tse)

jlabsetText(Selection is + tsegetPath())

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 37 of 38

e) Draw and explain the life cycle of servlet

(Explanation ndash 3 Marks Diagram -1 Marks)

Ans Three methods are central to the life cycle of a servlet

These are init( ) service( ) and destroy( )

They are implemented by every servlet and are invoked at specific times by the server Let

us consider a typical user scenario to understand when these methods are called

First assume that a user enters a Uniform Resource Locator (URL) to a web browser

The browser then generates an HTTP request for this URL This request is then sent to the

appropriate server

Second this HTTP request is received by the web server The server maps this request to

a particular servlet The servlet is dynamically retrieved and loaded into the address space

of the server

Third the server invokes the init( ) method of the servlet This method is invoked only

when the servlet is first loaded into memory It is possible to pass initialization parameters

to the servlet so it may configure itself

Fourth the server invokes the service( ) method of the servlet This method is called to

process the HTTP request You will see that it is possible for the servlet to read data that has

been provided in the HTTP request It may also formulate an HTTP response for the client

The servlet remains in the serverrsquos address space and is available to process any other

HTTP requests received from clients The service( ) method is called for each HTTP request

Finally the server may decide to unload the servlet from its memory The algorithms by

which this determination is made are specific to each server The server calls the destroy( )

method to relinquish any resources such as file handles that are allocated for the servlet

Important data may be saved to a persistent store The memory allocated for the servlet and

its objects can then be garbage collected

A servlet life cycle can be defined as the entire process from its creation till the destruction The

following are the paths followed by a servlet

The servlet is initialized by calling the init () method

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 38 of 38

The servlet calls service() method to process a clients request

The servlet is terminated by calling the destroy() method

Finally servlet is garbage collected by the garbage collector of the JVM

Initialization

(Load Resources)

Services

(Accept Requests)

Destruction

(Unload Resources)

Servlet

Request

Response

Page 17: AJP

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 17 of 38

The executeUpdate() method of the Statement object enables you to execute SQL update

statements such as delete insert and update The method takes a String containing the SQL update

statement and returns an integers that determines how many records were affected by the SQL

statement

b) Define Layout Manager Describe the use of GridLayout Manager 4

(Layout manager- 2 Marks Use-2 Marks)

Ans Each Container object has a layout manager associated with it A layout manager

is an instance of any class that implements the LayoutManagerinterface The layout

manager is set by the setLayout( ) method If no call to setLayout( ) is made then the

default layout manager is used Whenever a container is resized (or sized for the first

time) the layout manager is used to position each of the components within it

The setLayout( ) method has the following general form

voidsetLayout(LayoutManagerlayoutObj)

GridLayoutManager

GridLayout lays out components in a two-dimensional grid When you instantiate

a GridLayout you define the number of rows and columns The constructors

supported by GridLayoutare shown here

GridLayout( )

GridLayout(intnumRows intnumColumns)

GridLayout(intnumRows intnumColumns inthorz intvert)

c) Explain the use of cookies with example 4

(Explanation - 2 Marks Example - 2 Marks any one)

Ans Cookie is a small piece of information that is passed back and forth in the HTTP request and

response Even though a cookie can be created on the client side using some scripting language

such as JavaScript it is usually created by the server resource such as a Servlet The Cookies sent

by the server when the client requests another page from the same application In Servlet

programming a cookie is represented by a Cookie class in the javaxservlethttp package You can

create a cookie by calling the Cookie class constructor and passing two string objects the name

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 18 of 38

and value of the cookie For instance the following code creates a cookie object called c1The

cookie has the name ldquomyCookierdquo and value of rdquosecretrdquo

Cookie c1=new Cookie(ldquomyCookierdquordquosecretrdquo)

You then can add the cookie to the http response using addCookie method of the

HTTPServletResponse interfaceResponseaddCookie(c1)

Program for Add cookies

import javaio

importjavaxservlet

importjavaxservlethttp

public class AddCookieServlet extends HttpServlet

public void doPost(HttpServletRequest requestHttpServletResponse response)

throwsServletException IOException

Get parameter from HTTP request

String data = requestgetParameter(data)

Create cookie

Cookie cookie = new Cookie(MyCookie data)

Add cookie to HTTP response

responseaddCookie(cookie)

Write output to browser

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgtMyCookie has been set to)

pwprintln(data)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 19 of 38

pwclose()

OR

Program for Get Cookies

import javaio

importjavaxservlet

importjavaxservlethttp

public class GetCookiesServlet extends HttpServlet

public void doGet(HttpServletRequest requestHttpServletResponse response)

throwsServletException IOException

Get cookies from header of HTTP request

Cookie[] cookies = requestgetCookies()

Display these cookies

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgt)

for(inti = 0 iltcookieslength i++)

String name = cookies[i]getName()

String value = cookies[i]getValue()

pwprintln(name = + name +

value = + value)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 20 of 38

pwclose()

d) Give steps to create simple servlet with example 4

(Steps- 2 Marks Any one Example ndash 2 Marks)

Ans Steps 1) Write a java servet code

Steps 2) Compile Servet by setting classpath with servlet-api library

Step 3) Copy the class servlet file in web apps classpath directory

Steps 4) Open the webxml open it and add servlet tag and sevlet mapping tag

Steps 5) Start web server(apche tomcat)

Steps 6) Browse servlet using java compatible browser like IE

Example shows to start create a file named WelcomeServletjava that contains the following

program

import javaio

importjavaxservlet

public class WelcomeServletDemo extends GenericServlet

public void service(ServletRequestrequestServletResponse response) throws

ServletExceptionIOException

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgtWelcome to Servlet)

pwclose()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 21 of 38

B) Attempt any one of the following Marks 6

a) Describe the two ndashtier and three ndashtier database design of JDBC API with neat diagram

(Explanation of Two-tier-2 Marks and Three-tier-2 Marks Diagram ndash 1 Mark each)

Ans Two Tier Architecture

In a two tier model a java application is designed to interact directly with the database

Application functionality is divided into these two layers

1) Application Layer Including the JDBC driver business logic and user interface

2) Database Layer including RDBMS

The interface to the database is handled by the Java Database Connectivity(JDBC) Driver

appropriate to the particularly database management system being accessed The JDBC Driver

passes SQL statements to the database and returns the results of those statements to the

application

A clientserver configuration is the special case of the two tier model where the database is

located on another machine referred to as the server The application runs on the client machine

which is connected to the server over a network Commonly the network is an Intranet using

dedicated database servers to support multiple clients but it can just as easily be the internet

Three Tier Architecture-

In the three tier model the client typically sends requests to an application server forming the

middle tier The application server interprets these requests and formats the necessary SQL

statement to fulfill

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 22 of 38

These requests and sends them to the database The database process the SQL statements and

sends result back to the application server which then sends them to the client

Following are some advantages of Three-tier architecture

1 Performance can be improved by separating the application server and database server

2 Business logic is clearly separated from the database

3 Client application can use a simple protocol such as CGI to access services

The three-tier model show in following fig is a common in web application In this scenario the

client tier is frequently implemented in a browse on a client machine the middle tier is

implemented in a web server with a Servlet engine and the database management system runs on

a dedicated database server

Following are the main components of three tier architecture

1 Client Tier - Typically this is thin presentation layer that may be implemented using a web

browser

2 Middle Tier - This tier handles the business or application logic This may be implemented

using a Servlet engine such as Tomcat or an application server such as JBOSS The JDBC

driver also resides in this layer

3 Data source layer This component includes the RDBMS

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 23 of 38

b) Write servlet which shows how many times user has visited the page in session

(Any Correct Logic ndash4 Marks Syntax ndash 2 Marks)

Ans import javaio

import javaxservlet

import javaxservlethttp

public class Session Travker extends HttpServlet

public void doGet(HttpServletRequest req HttpServletResponse res) throws ServletException

IOException

ressetContentType(ldquotexthtmlrdquo)

PrintWriter out = resgetWriter()

HttpSession session = reqgetSession(true)

Integer count= (Integer)sessiongetValue(ldquotrackercountrdquo)

if(count== null) count=new Interger(1)

else count = new Interger(count intValue() +1)

sessionputValue(ldquotrackercountrdquocount)

outprintln(ldquoltHTMLgtltHEADgtltTITLEgtSession TrackerltTITLEgtltHEADgtrdquo)

outprintln(ldquoltBODYgtltH1gtSession Tracking DemoltH1gtrdquo)

outprintln(ldquoYou have visited this pagerdquo +count +((countintValue() == 1)rdquotimerdquo

ldquotimesrdquo))outprinln(ltPgtrdquo)

outprintln(ldquoltH2gtSesssion dataltH2gtrdquo)

String[] names = sessiongetValueNames()

for(int i=0 ilt nameslength i++)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 24 of 38

outprintln(names[i] + ldquo rdquo + sessiongetvalue(names[i])+ ldquoltBRgtrdquo)

outprintln(ldquoltBODYgtltHTMLgtrdquo)

5 Attempt any two of the following Marks 16

a) Write a program to display all records from Employee table from database using

JDBC

(Assume suitable data for table- Load driver create connection execute Query - 1 Mark

each Display data- 3 Marks Syntax ndash 2 Marks)

Ans import javasql

import javasqlStatement

import javaapplet

import javaawt

public class DisplayTable

public static void main( String args[])

RsultSet rs

Connection conn

try

String s1

ClassforName(sun jdbcodbcJdbcOdbcDriver)

Systemoutprintln(Connecting to a selected database)

String url=rdquojdbcodbcabcrdquo

conn = DriverManagergetConnection(DB_URL USER PASS)

Systemoutprintln(Connected database successfully)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 25 of 38

Systemoutprintln(Creating statement)

stmt = conncreateStatement()

sql = SELECT FROM Employee

ResultSet rs = stmtexecuteQuery(sql)

Tables fields assumed are id first last age

while(rsnext())

int id = rsgetInt(id)

int age = rsgetInt(age)

String first = rsgetString(first)

String last = rsgetString(last)

Systemoutprint(ID + id)

Systemoutprint( Age + age)

Systemoutprint( First + first)

Systemoutprintln( Last + last)

rsclose()

catch(SQLException se)

Handle errors for JDBC

seprintStackTrace()

catch(Exception e)

Handle errors for ClassforName

eprintStackTrace()

finally

finally block used to close resources

try

if(stmt=null)

connclose()

catch(SQLException se)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 26 of 38

b) Define the term

i) Reserved socket ii) proxy server

iii) Datagram iv) URL connection 4

(Each term- 2 Marks)

Ans i) Reserved socket

A socket is one end-point of a two-way communication link between two programs running on

the network Socket classes are used to represent the connection between a client program and a

server program

Reserved socket The socket which are reserved for specific protocols for communication

purpose are known as reseved sockets

TCPIP uses or reserves the lower 1024 ports for specific protocols

Example port number 23 is for Telnet 25 is for smtp 21 is for ftp 13 for daytime 110 for pop3

and so on Protocol decides how a client should interact with the port

ii) Proxy server

A proxy server is a computer that offers a computer network service to allow clients to make

indirect network connections to other network services A client connects to the proxy server

then requests a connection file or other resource available on a different server The proxy

provides the resource either by connecting to the specified server or by serving it from a cache In

some cases the proxy may alter the clients request or the servers response for various purposes

Purposes of the proxy servers

To keep machines behind it anonymous mainly for security

To speed up access to resources (using caching) Web proxies are commonly used to

cache web pages from a web server

To prevent downloading the same content multiple times (and save bandwidth)

To log audit usage eg to provide company employee Internet usage reporting

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 27 of 38

To scan transmitted content for malware before delivery

To scan outbound content eg for data loss prevention

iii) Datagram

Datagrams are bundles of information passed between machines They are somewhat like a hard

throw from a well-trained but blindfolded catcher to the third baseman Once the datagram has

been released to its intended target there is no assurance that it will arrive or even that

someone will be there to catch it Likewise when the datagram is received there is no

assurance that it hasnrsquot been damaged in transit or that whoever sent it is still there to receive a

response

Java implements datagrams on top of the UDP protocol by using two classes

The DatagramPacket object is the data container while the DatagramSocket is the mechanism

used to send or receive the DatagramPackets

iv) URL connection

URLConnection is a general-purpose class for accessing the attributes of a remote resource

Once you make a connection to a remote server you can use URLConnection to inspect the

Properties of the remote object before actually transporting it locally These attributes are

exposed by the HTTP protocol specification and as such only make sense for URL objects

that are using the HTTP protocol

URLConnection defines several methods

int getContentLength( )

String getContentType( )

long getDate( )

long getExpiration( )

String getHeaderField(int idx)

long getLastModified( )

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 28 of 38

c) Write a program to display three text fields and a button below to all an Applet Insert

the integer valuer from three text fields After pressing the button the background colour

of applet will be changed as per the RGB combination of the values given in the text field

(Correct logic - 6 Marks Syntax - 2 Marks)

4

Ans import javaawt

import javaawtevent

import javaapplet

ltapplet code=rdquoClrclassrdquo width=250 heigth=250gtltappletgt

public class Clrextends Applet implements ActionListener

int r g b

TextField t1t2t3

Button b1

Color c1

public void init()

t1= new TextField(5)

t2= new TextField(8)

t3= new TextField(11)

b1 = new Button(ldquo Set Colorrdquo)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 29 of 38

add(t1)

add(t2)

add(t3)

add(b1)

b1addActionListener(this)

public void void paint( )

setBackground(c1)

public void actionPerformed(ActionEvent ae)

r=IntegerparseInt(t1getText())

g=IntegerparseInt(t2getText())

b=IntegerparseInt(t3getText())

c1= new Color(rgb)

repaint()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 30 of 38

6) Attempt any four of the following Marks 16

a) How to check how many fonts are available in the computer system 4

Explain with example

(Explanation -2 Marks Example-2 Marks)

Ans When working with fonts often you need to know which fonts are available on your machine To

ontain this information you can use the getAvailableFontFamilyNames() method defined by the

GraphicsEnvironment classIt is shown here

String[ ] getAvailableFontFamilyNames( )

This method returns an array of string that contains the names of the available font families

Since this methods is members of GraphicsEnvironment you need a GraphicsEnvironment

reference to call itYou can obtain this reference by using the getlocalGrahicsEnvironmet() static

method which is derfined by GraphicsEnvironmentIt is shown here

static GraphicsEnvironment getLocalGraphicsEnvironment( )

Here is an applet that shown how to obtain the names of the available font families

ltapplet code=rdquoAllFontsrdquo width=500 height=100gt

ltappletgt

import javaapplet

import javaawt

public class AllFonts extends Applet

public void paint(Graphics g)

string fonts= ldquo rdquo

stirng allFontsList[]

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 31 of 38

GraphicsEnvironment t = GraphicsEnvironmentgetLocalGraphicsEnvironment()

allFontList = tgetAvailableFontFamilyNames()

for(int i= 0 ilt allFontsListlength i++)

fonts= fonts + allFontList[i] + ldquo rdquo

gdrawString(msg416)

b) Explain following check box class methods with appropriate example 4

i) Void setLable (String str) ii) Boolean getState ( )

(Explanation of each method-1 Marks Example-2 Marks)

Ans

i) void setLable(String str)

This method is used to set the label of check box

ii) Boolean getState()

This method is used to retrieve the current state of a check box It returns the value either true or

false depends on check box is selected or not

Example

Demonstrate check boxes

import javaawt

import javaawtevent

import javaapplet

ltapplet code=CheckboxDemo width=250 height=200gt

ltappletgt

public class CheckboxDemo extends Applet implements ItemListener

String msg =

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 32 of 38

Checkbox winXP winVista solaris mac

public void init()

winXP = new Checkbox(Windows XP null true)

mac = new Checkbox()

macsetLable(ldquoMac OSrdquo)

add(winXP)

add(mac)

winXPaddItemListener(this)

macaddItemListener(this)

public void itemStateChanged(ItemEvent ie)

repaint()

Display current state of the check boxes

public void paint(Graphics g)

msg = Current state

gdrawString(msg 6 80)

msg = Windows XP + winXPgetState()

gdrawString(msg 6 100)

msg = Mac OS + macgetState()

gdrawString(msg 6 120)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 33 of 38

c) Explain the techniques of session tracking management

(Any four techniques with explanation- 1 Mark each)

Ans Session tracking Techniques

1 User Authorization

Users can be authorized to use the web application in different ways Basic concept is that the

user will provide username and password to login to the application Based on that the user can

be identified and the session can be maintained

2 Hidden Fields

ltINPUT TYPE=rdquohiddenrdquo NAME=rdquotechnologyrdquo VALUE=rdquoservletrdquogt

Hidden fields like the above can be inserted in the webpages and information can be sent to the

server for session tracking These fields are not visible directly to the user but can be viewed

using view source option from the browsers This type doesnrsquot need any special configuration

from the browser of server and by default available to use for session tracking This cannot be

used for session tracking when the conversation included static resources lik html pages

3 URL Rewriting

Original URL httpserverportservletServletName

ewritten URL httpserverportservletServletNamesessionid=7456

When a request is made additional parameter is appended with the url In general added

additional parameter will be sessionid or sometimes the userid It will suffice to track the

session This type of session tracking doesnrsquot need any special support from the browser

Disadvantage is implementing this type of session tracking is tedious We need to keep track of

the parameter as a chain link until the conversation completes and also should make sure that

the parameter doesnrsquot clash with other application parameters

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 34 of 38

4 Cookies

Cookies are the mostly used technology for session tracking Cookie is a key value pair of

information sent by the server to the browser This should be saved by the browser in its space

in the client computer Whenever the browser sends a request to that server it sends the cookie

along with it Then the server can identify the client using the cookie

In java following is the source code snippet to create a cookie

Cookie cookie = new Cookie (ldquouserIDrdquo ldquo7456Prime)

resaddCookie(cookie)

5 Session tracking API

Session tracking API is built on top of the first four methods This is inorder to help the

developer to minimize the overhead of session tracking This type of session tracking is

provided by the underlying technology Lets take the java servlet example Then the servlet

container manages the session tracking task and the user need not do it explicitly using the java

servlets This is the best of all methods because all the management and errors related to

session tracking will be taken care of by the container itself

d) Give sequential steps for JTree in swing with example

(Steps- 2 Marks any small Example- 2 Marks)

Ans Steps for JTree

Atree is a component that presents a hierarchical view of data The user has the ability to

expand or collapse individual subtrees in this display Trees are implemented in Swing by

the JTree class

Here are the steps to follow to use a tree

1 Create an instance of JTree

2 Create a JScrollPane and specify the tree as the object to be scrolled

3 Add the tree to the scroll pane

4 Add the scroll pane to the content pane

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 35 of 38

Example

Demonstrate JTree

import javaawt

import javaxswingevent

import javaxswing

import javaxswingtree

ltapplet code=JTreeDemo width=400 height=200gt

ltappletgt

public class JTreeDemo extends JApplet

JTree tree

JLabel jlab

public void init()

try

SwingUtilitiesinvokeAndWait(

new Runnable()

public void run()

makeGUI()

)

catch (Exception exc)

Systemoutprintln(Cant create because of + exc)

private void makeGUI()

Create top node of tree

DefaultMutableTreeNode top = new DefaultMutableTreeNode(Options)

Create subtree of A

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 36 of 38

DefaultMutableTreeNode a = new DefaultMutableTreeNode(A)

topadd(a)

DefaultMutableTreeNode a1 = new DefaultMutableTreeNode(A1)

aadd(a1)

DefaultMutableTreeNode a2 = new DefaultMutableTreeNode(A2)

aadd(a2)

Create subtree of B

DefaultMutableTreeNode b = new DefaultMutableTreeNode(B)

topadd(b)

DefaultMutableTreeNode b1 = new DefaultMutableTreeNode(B1)

badd(b1)

DefaultMutableTreeNode b2 = new DefaultMutableTreeNode(B2)

badd(b2)

DefaultMutableTreeNode b3 = new DefaultMutableTreeNode(B3)

badd(b3)

Create the tree

tree = new JTree(top)

Add the tree to a scroll pane

JScrollPane jsp = new JScrollPane(tree)

Add the scroll pane to the content pane

add(jsp)

Add the label to the content pane

jlab = new JLabel()

add(jlab BorderLayoutSOUTH)

Handle tree selection events

treeaddTreeSelectionListener(new TreeSelectionListener()

public void valueChanged(TreeSelectionEvent tse)

jlabsetText(Selection is + tsegetPath())

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 37 of 38

e) Draw and explain the life cycle of servlet

(Explanation ndash 3 Marks Diagram -1 Marks)

Ans Three methods are central to the life cycle of a servlet

These are init( ) service( ) and destroy( )

They are implemented by every servlet and are invoked at specific times by the server Let

us consider a typical user scenario to understand when these methods are called

First assume that a user enters a Uniform Resource Locator (URL) to a web browser

The browser then generates an HTTP request for this URL This request is then sent to the

appropriate server

Second this HTTP request is received by the web server The server maps this request to

a particular servlet The servlet is dynamically retrieved and loaded into the address space

of the server

Third the server invokes the init( ) method of the servlet This method is invoked only

when the servlet is first loaded into memory It is possible to pass initialization parameters

to the servlet so it may configure itself

Fourth the server invokes the service( ) method of the servlet This method is called to

process the HTTP request You will see that it is possible for the servlet to read data that has

been provided in the HTTP request It may also formulate an HTTP response for the client

The servlet remains in the serverrsquos address space and is available to process any other

HTTP requests received from clients The service( ) method is called for each HTTP request

Finally the server may decide to unload the servlet from its memory The algorithms by

which this determination is made are specific to each server The server calls the destroy( )

method to relinquish any resources such as file handles that are allocated for the servlet

Important data may be saved to a persistent store The memory allocated for the servlet and

its objects can then be garbage collected

A servlet life cycle can be defined as the entire process from its creation till the destruction The

following are the paths followed by a servlet

The servlet is initialized by calling the init () method

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 38 of 38

The servlet calls service() method to process a clients request

The servlet is terminated by calling the destroy() method

Finally servlet is garbage collected by the garbage collector of the JVM

Initialization

(Load Resources)

Services

(Accept Requests)

Destruction

(Unload Resources)

Servlet

Request

Response

Page 18: AJP

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 18 of 38

and value of the cookie For instance the following code creates a cookie object called c1The

cookie has the name ldquomyCookierdquo and value of rdquosecretrdquo

Cookie c1=new Cookie(ldquomyCookierdquordquosecretrdquo)

You then can add the cookie to the http response using addCookie method of the

HTTPServletResponse interfaceResponseaddCookie(c1)

Program for Add cookies

import javaio

importjavaxservlet

importjavaxservlethttp

public class AddCookieServlet extends HttpServlet

public void doPost(HttpServletRequest requestHttpServletResponse response)

throwsServletException IOException

Get parameter from HTTP request

String data = requestgetParameter(data)

Create cookie

Cookie cookie = new Cookie(MyCookie data)

Add cookie to HTTP response

responseaddCookie(cookie)

Write output to browser

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgtMyCookie has been set to)

pwprintln(data)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 19 of 38

pwclose()

OR

Program for Get Cookies

import javaio

importjavaxservlet

importjavaxservlethttp

public class GetCookiesServlet extends HttpServlet

public void doGet(HttpServletRequest requestHttpServletResponse response)

throwsServletException IOException

Get cookies from header of HTTP request

Cookie[] cookies = requestgetCookies()

Display these cookies

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgt)

for(inti = 0 iltcookieslength i++)

String name = cookies[i]getName()

String value = cookies[i]getValue()

pwprintln(name = + name +

value = + value)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 20 of 38

pwclose()

d) Give steps to create simple servlet with example 4

(Steps- 2 Marks Any one Example ndash 2 Marks)

Ans Steps 1) Write a java servet code

Steps 2) Compile Servet by setting classpath with servlet-api library

Step 3) Copy the class servlet file in web apps classpath directory

Steps 4) Open the webxml open it and add servlet tag and sevlet mapping tag

Steps 5) Start web server(apche tomcat)

Steps 6) Browse servlet using java compatible browser like IE

Example shows to start create a file named WelcomeServletjava that contains the following

program

import javaio

importjavaxservlet

public class WelcomeServletDemo extends GenericServlet

public void service(ServletRequestrequestServletResponse response) throws

ServletExceptionIOException

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgtWelcome to Servlet)

pwclose()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 21 of 38

B) Attempt any one of the following Marks 6

a) Describe the two ndashtier and three ndashtier database design of JDBC API with neat diagram

(Explanation of Two-tier-2 Marks and Three-tier-2 Marks Diagram ndash 1 Mark each)

Ans Two Tier Architecture

In a two tier model a java application is designed to interact directly with the database

Application functionality is divided into these two layers

1) Application Layer Including the JDBC driver business logic and user interface

2) Database Layer including RDBMS

The interface to the database is handled by the Java Database Connectivity(JDBC) Driver

appropriate to the particularly database management system being accessed The JDBC Driver

passes SQL statements to the database and returns the results of those statements to the

application

A clientserver configuration is the special case of the two tier model where the database is

located on another machine referred to as the server The application runs on the client machine

which is connected to the server over a network Commonly the network is an Intranet using

dedicated database servers to support multiple clients but it can just as easily be the internet

Three Tier Architecture-

In the three tier model the client typically sends requests to an application server forming the

middle tier The application server interprets these requests and formats the necessary SQL

statement to fulfill

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 22 of 38

These requests and sends them to the database The database process the SQL statements and

sends result back to the application server which then sends them to the client

Following are some advantages of Three-tier architecture

1 Performance can be improved by separating the application server and database server

2 Business logic is clearly separated from the database

3 Client application can use a simple protocol such as CGI to access services

The three-tier model show in following fig is a common in web application In this scenario the

client tier is frequently implemented in a browse on a client machine the middle tier is

implemented in a web server with a Servlet engine and the database management system runs on

a dedicated database server

Following are the main components of three tier architecture

1 Client Tier - Typically this is thin presentation layer that may be implemented using a web

browser

2 Middle Tier - This tier handles the business or application logic This may be implemented

using a Servlet engine such as Tomcat or an application server such as JBOSS The JDBC

driver also resides in this layer

3 Data source layer This component includes the RDBMS

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 23 of 38

b) Write servlet which shows how many times user has visited the page in session

(Any Correct Logic ndash4 Marks Syntax ndash 2 Marks)

Ans import javaio

import javaxservlet

import javaxservlethttp

public class Session Travker extends HttpServlet

public void doGet(HttpServletRequest req HttpServletResponse res) throws ServletException

IOException

ressetContentType(ldquotexthtmlrdquo)

PrintWriter out = resgetWriter()

HttpSession session = reqgetSession(true)

Integer count= (Integer)sessiongetValue(ldquotrackercountrdquo)

if(count== null) count=new Interger(1)

else count = new Interger(count intValue() +1)

sessionputValue(ldquotrackercountrdquocount)

outprintln(ldquoltHTMLgtltHEADgtltTITLEgtSession TrackerltTITLEgtltHEADgtrdquo)

outprintln(ldquoltBODYgtltH1gtSession Tracking DemoltH1gtrdquo)

outprintln(ldquoYou have visited this pagerdquo +count +((countintValue() == 1)rdquotimerdquo

ldquotimesrdquo))outprinln(ltPgtrdquo)

outprintln(ldquoltH2gtSesssion dataltH2gtrdquo)

String[] names = sessiongetValueNames()

for(int i=0 ilt nameslength i++)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 24 of 38

outprintln(names[i] + ldquo rdquo + sessiongetvalue(names[i])+ ldquoltBRgtrdquo)

outprintln(ldquoltBODYgtltHTMLgtrdquo)

5 Attempt any two of the following Marks 16

a) Write a program to display all records from Employee table from database using

JDBC

(Assume suitable data for table- Load driver create connection execute Query - 1 Mark

each Display data- 3 Marks Syntax ndash 2 Marks)

Ans import javasql

import javasqlStatement

import javaapplet

import javaawt

public class DisplayTable

public static void main( String args[])

RsultSet rs

Connection conn

try

String s1

ClassforName(sun jdbcodbcJdbcOdbcDriver)

Systemoutprintln(Connecting to a selected database)

String url=rdquojdbcodbcabcrdquo

conn = DriverManagergetConnection(DB_URL USER PASS)

Systemoutprintln(Connected database successfully)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 25 of 38

Systemoutprintln(Creating statement)

stmt = conncreateStatement()

sql = SELECT FROM Employee

ResultSet rs = stmtexecuteQuery(sql)

Tables fields assumed are id first last age

while(rsnext())

int id = rsgetInt(id)

int age = rsgetInt(age)

String first = rsgetString(first)

String last = rsgetString(last)

Systemoutprint(ID + id)

Systemoutprint( Age + age)

Systemoutprint( First + first)

Systemoutprintln( Last + last)

rsclose()

catch(SQLException se)

Handle errors for JDBC

seprintStackTrace()

catch(Exception e)

Handle errors for ClassforName

eprintStackTrace()

finally

finally block used to close resources

try

if(stmt=null)

connclose()

catch(SQLException se)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 26 of 38

b) Define the term

i) Reserved socket ii) proxy server

iii) Datagram iv) URL connection 4

(Each term- 2 Marks)

Ans i) Reserved socket

A socket is one end-point of a two-way communication link between two programs running on

the network Socket classes are used to represent the connection between a client program and a

server program

Reserved socket The socket which are reserved for specific protocols for communication

purpose are known as reseved sockets

TCPIP uses or reserves the lower 1024 ports for specific protocols

Example port number 23 is for Telnet 25 is for smtp 21 is for ftp 13 for daytime 110 for pop3

and so on Protocol decides how a client should interact with the port

ii) Proxy server

A proxy server is a computer that offers a computer network service to allow clients to make

indirect network connections to other network services A client connects to the proxy server

then requests a connection file or other resource available on a different server The proxy

provides the resource either by connecting to the specified server or by serving it from a cache In

some cases the proxy may alter the clients request or the servers response for various purposes

Purposes of the proxy servers

To keep machines behind it anonymous mainly for security

To speed up access to resources (using caching) Web proxies are commonly used to

cache web pages from a web server

To prevent downloading the same content multiple times (and save bandwidth)

To log audit usage eg to provide company employee Internet usage reporting

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 27 of 38

To scan transmitted content for malware before delivery

To scan outbound content eg for data loss prevention

iii) Datagram

Datagrams are bundles of information passed between machines They are somewhat like a hard

throw from a well-trained but blindfolded catcher to the third baseman Once the datagram has

been released to its intended target there is no assurance that it will arrive or even that

someone will be there to catch it Likewise when the datagram is received there is no

assurance that it hasnrsquot been damaged in transit or that whoever sent it is still there to receive a

response

Java implements datagrams on top of the UDP protocol by using two classes

The DatagramPacket object is the data container while the DatagramSocket is the mechanism

used to send or receive the DatagramPackets

iv) URL connection

URLConnection is a general-purpose class for accessing the attributes of a remote resource

Once you make a connection to a remote server you can use URLConnection to inspect the

Properties of the remote object before actually transporting it locally These attributes are

exposed by the HTTP protocol specification and as such only make sense for URL objects

that are using the HTTP protocol

URLConnection defines several methods

int getContentLength( )

String getContentType( )

long getDate( )

long getExpiration( )

String getHeaderField(int idx)

long getLastModified( )

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 28 of 38

c) Write a program to display three text fields and a button below to all an Applet Insert

the integer valuer from three text fields After pressing the button the background colour

of applet will be changed as per the RGB combination of the values given in the text field

(Correct logic - 6 Marks Syntax - 2 Marks)

4

Ans import javaawt

import javaawtevent

import javaapplet

ltapplet code=rdquoClrclassrdquo width=250 heigth=250gtltappletgt

public class Clrextends Applet implements ActionListener

int r g b

TextField t1t2t3

Button b1

Color c1

public void init()

t1= new TextField(5)

t2= new TextField(8)

t3= new TextField(11)

b1 = new Button(ldquo Set Colorrdquo)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 29 of 38

add(t1)

add(t2)

add(t3)

add(b1)

b1addActionListener(this)

public void void paint( )

setBackground(c1)

public void actionPerformed(ActionEvent ae)

r=IntegerparseInt(t1getText())

g=IntegerparseInt(t2getText())

b=IntegerparseInt(t3getText())

c1= new Color(rgb)

repaint()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 30 of 38

6) Attempt any four of the following Marks 16

a) How to check how many fonts are available in the computer system 4

Explain with example

(Explanation -2 Marks Example-2 Marks)

Ans When working with fonts often you need to know which fonts are available on your machine To

ontain this information you can use the getAvailableFontFamilyNames() method defined by the

GraphicsEnvironment classIt is shown here

String[ ] getAvailableFontFamilyNames( )

This method returns an array of string that contains the names of the available font families

Since this methods is members of GraphicsEnvironment you need a GraphicsEnvironment

reference to call itYou can obtain this reference by using the getlocalGrahicsEnvironmet() static

method which is derfined by GraphicsEnvironmentIt is shown here

static GraphicsEnvironment getLocalGraphicsEnvironment( )

Here is an applet that shown how to obtain the names of the available font families

ltapplet code=rdquoAllFontsrdquo width=500 height=100gt

ltappletgt

import javaapplet

import javaawt

public class AllFonts extends Applet

public void paint(Graphics g)

string fonts= ldquo rdquo

stirng allFontsList[]

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 31 of 38

GraphicsEnvironment t = GraphicsEnvironmentgetLocalGraphicsEnvironment()

allFontList = tgetAvailableFontFamilyNames()

for(int i= 0 ilt allFontsListlength i++)

fonts= fonts + allFontList[i] + ldquo rdquo

gdrawString(msg416)

b) Explain following check box class methods with appropriate example 4

i) Void setLable (String str) ii) Boolean getState ( )

(Explanation of each method-1 Marks Example-2 Marks)

Ans

i) void setLable(String str)

This method is used to set the label of check box

ii) Boolean getState()

This method is used to retrieve the current state of a check box It returns the value either true or

false depends on check box is selected or not

Example

Demonstrate check boxes

import javaawt

import javaawtevent

import javaapplet

ltapplet code=CheckboxDemo width=250 height=200gt

ltappletgt

public class CheckboxDemo extends Applet implements ItemListener

String msg =

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 32 of 38

Checkbox winXP winVista solaris mac

public void init()

winXP = new Checkbox(Windows XP null true)

mac = new Checkbox()

macsetLable(ldquoMac OSrdquo)

add(winXP)

add(mac)

winXPaddItemListener(this)

macaddItemListener(this)

public void itemStateChanged(ItemEvent ie)

repaint()

Display current state of the check boxes

public void paint(Graphics g)

msg = Current state

gdrawString(msg 6 80)

msg = Windows XP + winXPgetState()

gdrawString(msg 6 100)

msg = Mac OS + macgetState()

gdrawString(msg 6 120)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 33 of 38

c) Explain the techniques of session tracking management

(Any four techniques with explanation- 1 Mark each)

Ans Session tracking Techniques

1 User Authorization

Users can be authorized to use the web application in different ways Basic concept is that the

user will provide username and password to login to the application Based on that the user can

be identified and the session can be maintained

2 Hidden Fields

ltINPUT TYPE=rdquohiddenrdquo NAME=rdquotechnologyrdquo VALUE=rdquoservletrdquogt

Hidden fields like the above can be inserted in the webpages and information can be sent to the

server for session tracking These fields are not visible directly to the user but can be viewed

using view source option from the browsers This type doesnrsquot need any special configuration

from the browser of server and by default available to use for session tracking This cannot be

used for session tracking when the conversation included static resources lik html pages

3 URL Rewriting

Original URL httpserverportservletServletName

ewritten URL httpserverportservletServletNamesessionid=7456

When a request is made additional parameter is appended with the url In general added

additional parameter will be sessionid or sometimes the userid It will suffice to track the

session This type of session tracking doesnrsquot need any special support from the browser

Disadvantage is implementing this type of session tracking is tedious We need to keep track of

the parameter as a chain link until the conversation completes and also should make sure that

the parameter doesnrsquot clash with other application parameters

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 34 of 38

4 Cookies

Cookies are the mostly used technology for session tracking Cookie is a key value pair of

information sent by the server to the browser This should be saved by the browser in its space

in the client computer Whenever the browser sends a request to that server it sends the cookie

along with it Then the server can identify the client using the cookie

In java following is the source code snippet to create a cookie

Cookie cookie = new Cookie (ldquouserIDrdquo ldquo7456Prime)

resaddCookie(cookie)

5 Session tracking API

Session tracking API is built on top of the first four methods This is inorder to help the

developer to minimize the overhead of session tracking This type of session tracking is

provided by the underlying technology Lets take the java servlet example Then the servlet

container manages the session tracking task and the user need not do it explicitly using the java

servlets This is the best of all methods because all the management and errors related to

session tracking will be taken care of by the container itself

d) Give sequential steps for JTree in swing with example

(Steps- 2 Marks any small Example- 2 Marks)

Ans Steps for JTree

Atree is a component that presents a hierarchical view of data The user has the ability to

expand or collapse individual subtrees in this display Trees are implemented in Swing by

the JTree class

Here are the steps to follow to use a tree

1 Create an instance of JTree

2 Create a JScrollPane and specify the tree as the object to be scrolled

3 Add the tree to the scroll pane

4 Add the scroll pane to the content pane

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 35 of 38

Example

Demonstrate JTree

import javaawt

import javaxswingevent

import javaxswing

import javaxswingtree

ltapplet code=JTreeDemo width=400 height=200gt

ltappletgt

public class JTreeDemo extends JApplet

JTree tree

JLabel jlab

public void init()

try

SwingUtilitiesinvokeAndWait(

new Runnable()

public void run()

makeGUI()

)

catch (Exception exc)

Systemoutprintln(Cant create because of + exc)

private void makeGUI()

Create top node of tree

DefaultMutableTreeNode top = new DefaultMutableTreeNode(Options)

Create subtree of A

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 36 of 38

DefaultMutableTreeNode a = new DefaultMutableTreeNode(A)

topadd(a)

DefaultMutableTreeNode a1 = new DefaultMutableTreeNode(A1)

aadd(a1)

DefaultMutableTreeNode a2 = new DefaultMutableTreeNode(A2)

aadd(a2)

Create subtree of B

DefaultMutableTreeNode b = new DefaultMutableTreeNode(B)

topadd(b)

DefaultMutableTreeNode b1 = new DefaultMutableTreeNode(B1)

badd(b1)

DefaultMutableTreeNode b2 = new DefaultMutableTreeNode(B2)

badd(b2)

DefaultMutableTreeNode b3 = new DefaultMutableTreeNode(B3)

badd(b3)

Create the tree

tree = new JTree(top)

Add the tree to a scroll pane

JScrollPane jsp = new JScrollPane(tree)

Add the scroll pane to the content pane

add(jsp)

Add the label to the content pane

jlab = new JLabel()

add(jlab BorderLayoutSOUTH)

Handle tree selection events

treeaddTreeSelectionListener(new TreeSelectionListener()

public void valueChanged(TreeSelectionEvent tse)

jlabsetText(Selection is + tsegetPath())

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 37 of 38

e) Draw and explain the life cycle of servlet

(Explanation ndash 3 Marks Diagram -1 Marks)

Ans Three methods are central to the life cycle of a servlet

These are init( ) service( ) and destroy( )

They are implemented by every servlet and are invoked at specific times by the server Let

us consider a typical user scenario to understand when these methods are called

First assume that a user enters a Uniform Resource Locator (URL) to a web browser

The browser then generates an HTTP request for this URL This request is then sent to the

appropriate server

Second this HTTP request is received by the web server The server maps this request to

a particular servlet The servlet is dynamically retrieved and loaded into the address space

of the server

Third the server invokes the init( ) method of the servlet This method is invoked only

when the servlet is first loaded into memory It is possible to pass initialization parameters

to the servlet so it may configure itself

Fourth the server invokes the service( ) method of the servlet This method is called to

process the HTTP request You will see that it is possible for the servlet to read data that has

been provided in the HTTP request It may also formulate an HTTP response for the client

The servlet remains in the serverrsquos address space and is available to process any other

HTTP requests received from clients The service( ) method is called for each HTTP request

Finally the server may decide to unload the servlet from its memory The algorithms by

which this determination is made are specific to each server The server calls the destroy( )

method to relinquish any resources such as file handles that are allocated for the servlet

Important data may be saved to a persistent store The memory allocated for the servlet and

its objects can then be garbage collected

A servlet life cycle can be defined as the entire process from its creation till the destruction The

following are the paths followed by a servlet

The servlet is initialized by calling the init () method

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 38 of 38

The servlet calls service() method to process a clients request

The servlet is terminated by calling the destroy() method

Finally servlet is garbage collected by the garbage collector of the JVM

Initialization

(Load Resources)

Services

(Accept Requests)

Destruction

(Unload Resources)

Servlet

Request

Response

Page 19: AJP

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 19 of 38

pwclose()

OR

Program for Get Cookies

import javaio

importjavaxservlet

importjavaxservlethttp

public class GetCookiesServlet extends HttpServlet

public void doGet(HttpServletRequest requestHttpServletResponse response)

throwsServletException IOException

Get cookies from header of HTTP request

Cookie[] cookies = requestgetCookies()

Display these cookies

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgt)

for(inti = 0 iltcookieslength i++)

String name = cookies[i]getName()

String value = cookies[i]getValue()

pwprintln(name = + name +

value = + value)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 20 of 38

pwclose()

d) Give steps to create simple servlet with example 4

(Steps- 2 Marks Any one Example ndash 2 Marks)

Ans Steps 1) Write a java servet code

Steps 2) Compile Servet by setting classpath with servlet-api library

Step 3) Copy the class servlet file in web apps classpath directory

Steps 4) Open the webxml open it and add servlet tag and sevlet mapping tag

Steps 5) Start web server(apche tomcat)

Steps 6) Browse servlet using java compatible browser like IE

Example shows to start create a file named WelcomeServletjava that contains the following

program

import javaio

importjavaxservlet

public class WelcomeServletDemo extends GenericServlet

public void service(ServletRequestrequestServletResponse response) throws

ServletExceptionIOException

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgtWelcome to Servlet)

pwclose()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 21 of 38

B) Attempt any one of the following Marks 6

a) Describe the two ndashtier and three ndashtier database design of JDBC API with neat diagram

(Explanation of Two-tier-2 Marks and Three-tier-2 Marks Diagram ndash 1 Mark each)

Ans Two Tier Architecture

In a two tier model a java application is designed to interact directly with the database

Application functionality is divided into these two layers

1) Application Layer Including the JDBC driver business logic and user interface

2) Database Layer including RDBMS

The interface to the database is handled by the Java Database Connectivity(JDBC) Driver

appropriate to the particularly database management system being accessed The JDBC Driver

passes SQL statements to the database and returns the results of those statements to the

application

A clientserver configuration is the special case of the two tier model where the database is

located on another machine referred to as the server The application runs on the client machine

which is connected to the server over a network Commonly the network is an Intranet using

dedicated database servers to support multiple clients but it can just as easily be the internet

Three Tier Architecture-

In the three tier model the client typically sends requests to an application server forming the

middle tier The application server interprets these requests and formats the necessary SQL

statement to fulfill

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 22 of 38

These requests and sends them to the database The database process the SQL statements and

sends result back to the application server which then sends them to the client

Following are some advantages of Three-tier architecture

1 Performance can be improved by separating the application server and database server

2 Business logic is clearly separated from the database

3 Client application can use a simple protocol such as CGI to access services

The three-tier model show in following fig is a common in web application In this scenario the

client tier is frequently implemented in a browse on a client machine the middle tier is

implemented in a web server with a Servlet engine and the database management system runs on

a dedicated database server

Following are the main components of three tier architecture

1 Client Tier - Typically this is thin presentation layer that may be implemented using a web

browser

2 Middle Tier - This tier handles the business or application logic This may be implemented

using a Servlet engine such as Tomcat or an application server such as JBOSS The JDBC

driver also resides in this layer

3 Data source layer This component includes the RDBMS

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 23 of 38

b) Write servlet which shows how many times user has visited the page in session

(Any Correct Logic ndash4 Marks Syntax ndash 2 Marks)

Ans import javaio

import javaxservlet

import javaxservlethttp

public class Session Travker extends HttpServlet

public void doGet(HttpServletRequest req HttpServletResponse res) throws ServletException

IOException

ressetContentType(ldquotexthtmlrdquo)

PrintWriter out = resgetWriter()

HttpSession session = reqgetSession(true)

Integer count= (Integer)sessiongetValue(ldquotrackercountrdquo)

if(count== null) count=new Interger(1)

else count = new Interger(count intValue() +1)

sessionputValue(ldquotrackercountrdquocount)

outprintln(ldquoltHTMLgtltHEADgtltTITLEgtSession TrackerltTITLEgtltHEADgtrdquo)

outprintln(ldquoltBODYgtltH1gtSession Tracking DemoltH1gtrdquo)

outprintln(ldquoYou have visited this pagerdquo +count +((countintValue() == 1)rdquotimerdquo

ldquotimesrdquo))outprinln(ltPgtrdquo)

outprintln(ldquoltH2gtSesssion dataltH2gtrdquo)

String[] names = sessiongetValueNames()

for(int i=0 ilt nameslength i++)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 24 of 38

outprintln(names[i] + ldquo rdquo + sessiongetvalue(names[i])+ ldquoltBRgtrdquo)

outprintln(ldquoltBODYgtltHTMLgtrdquo)

5 Attempt any two of the following Marks 16

a) Write a program to display all records from Employee table from database using

JDBC

(Assume suitable data for table- Load driver create connection execute Query - 1 Mark

each Display data- 3 Marks Syntax ndash 2 Marks)

Ans import javasql

import javasqlStatement

import javaapplet

import javaawt

public class DisplayTable

public static void main( String args[])

RsultSet rs

Connection conn

try

String s1

ClassforName(sun jdbcodbcJdbcOdbcDriver)

Systemoutprintln(Connecting to a selected database)

String url=rdquojdbcodbcabcrdquo

conn = DriverManagergetConnection(DB_URL USER PASS)

Systemoutprintln(Connected database successfully)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 25 of 38

Systemoutprintln(Creating statement)

stmt = conncreateStatement()

sql = SELECT FROM Employee

ResultSet rs = stmtexecuteQuery(sql)

Tables fields assumed are id first last age

while(rsnext())

int id = rsgetInt(id)

int age = rsgetInt(age)

String first = rsgetString(first)

String last = rsgetString(last)

Systemoutprint(ID + id)

Systemoutprint( Age + age)

Systemoutprint( First + first)

Systemoutprintln( Last + last)

rsclose()

catch(SQLException se)

Handle errors for JDBC

seprintStackTrace()

catch(Exception e)

Handle errors for ClassforName

eprintStackTrace()

finally

finally block used to close resources

try

if(stmt=null)

connclose()

catch(SQLException se)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 26 of 38

b) Define the term

i) Reserved socket ii) proxy server

iii) Datagram iv) URL connection 4

(Each term- 2 Marks)

Ans i) Reserved socket

A socket is one end-point of a two-way communication link between two programs running on

the network Socket classes are used to represent the connection between a client program and a

server program

Reserved socket The socket which are reserved for specific protocols for communication

purpose are known as reseved sockets

TCPIP uses or reserves the lower 1024 ports for specific protocols

Example port number 23 is for Telnet 25 is for smtp 21 is for ftp 13 for daytime 110 for pop3

and so on Protocol decides how a client should interact with the port

ii) Proxy server

A proxy server is a computer that offers a computer network service to allow clients to make

indirect network connections to other network services A client connects to the proxy server

then requests a connection file or other resource available on a different server The proxy

provides the resource either by connecting to the specified server or by serving it from a cache In

some cases the proxy may alter the clients request or the servers response for various purposes

Purposes of the proxy servers

To keep machines behind it anonymous mainly for security

To speed up access to resources (using caching) Web proxies are commonly used to

cache web pages from a web server

To prevent downloading the same content multiple times (and save bandwidth)

To log audit usage eg to provide company employee Internet usage reporting

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 27 of 38

To scan transmitted content for malware before delivery

To scan outbound content eg for data loss prevention

iii) Datagram

Datagrams are bundles of information passed between machines They are somewhat like a hard

throw from a well-trained but blindfolded catcher to the third baseman Once the datagram has

been released to its intended target there is no assurance that it will arrive or even that

someone will be there to catch it Likewise when the datagram is received there is no

assurance that it hasnrsquot been damaged in transit or that whoever sent it is still there to receive a

response

Java implements datagrams on top of the UDP protocol by using two classes

The DatagramPacket object is the data container while the DatagramSocket is the mechanism

used to send or receive the DatagramPackets

iv) URL connection

URLConnection is a general-purpose class for accessing the attributes of a remote resource

Once you make a connection to a remote server you can use URLConnection to inspect the

Properties of the remote object before actually transporting it locally These attributes are

exposed by the HTTP protocol specification and as such only make sense for URL objects

that are using the HTTP protocol

URLConnection defines several methods

int getContentLength( )

String getContentType( )

long getDate( )

long getExpiration( )

String getHeaderField(int idx)

long getLastModified( )

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 28 of 38

c) Write a program to display three text fields and a button below to all an Applet Insert

the integer valuer from three text fields After pressing the button the background colour

of applet will be changed as per the RGB combination of the values given in the text field

(Correct logic - 6 Marks Syntax - 2 Marks)

4

Ans import javaawt

import javaawtevent

import javaapplet

ltapplet code=rdquoClrclassrdquo width=250 heigth=250gtltappletgt

public class Clrextends Applet implements ActionListener

int r g b

TextField t1t2t3

Button b1

Color c1

public void init()

t1= new TextField(5)

t2= new TextField(8)

t3= new TextField(11)

b1 = new Button(ldquo Set Colorrdquo)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 29 of 38

add(t1)

add(t2)

add(t3)

add(b1)

b1addActionListener(this)

public void void paint( )

setBackground(c1)

public void actionPerformed(ActionEvent ae)

r=IntegerparseInt(t1getText())

g=IntegerparseInt(t2getText())

b=IntegerparseInt(t3getText())

c1= new Color(rgb)

repaint()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 30 of 38

6) Attempt any four of the following Marks 16

a) How to check how many fonts are available in the computer system 4

Explain with example

(Explanation -2 Marks Example-2 Marks)

Ans When working with fonts often you need to know which fonts are available on your machine To

ontain this information you can use the getAvailableFontFamilyNames() method defined by the

GraphicsEnvironment classIt is shown here

String[ ] getAvailableFontFamilyNames( )

This method returns an array of string that contains the names of the available font families

Since this methods is members of GraphicsEnvironment you need a GraphicsEnvironment

reference to call itYou can obtain this reference by using the getlocalGrahicsEnvironmet() static

method which is derfined by GraphicsEnvironmentIt is shown here

static GraphicsEnvironment getLocalGraphicsEnvironment( )

Here is an applet that shown how to obtain the names of the available font families

ltapplet code=rdquoAllFontsrdquo width=500 height=100gt

ltappletgt

import javaapplet

import javaawt

public class AllFonts extends Applet

public void paint(Graphics g)

string fonts= ldquo rdquo

stirng allFontsList[]

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 31 of 38

GraphicsEnvironment t = GraphicsEnvironmentgetLocalGraphicsEnvironment()

allFontList = tgetAvailableFontFamilyNames()

for(int i= 0 ilt allFontsListlength i++)

fonts= fonts + allFontList[i] + ldquo rdquo

gdrawString(msg416)

b) Explain following check box class methods with appropriate example 4

i) Void setLable (String str) ii) Boolean getState ( )

(Explanation of each method-1 Marks Example-2 Marks)

Ans

i) void setLable(String str)

This method is used to set the label of check box

ii) Boolean getState()

This method is used to retrieve the current state of a check box It returns the value either true or

false depends on check box is selected or not

Example

Demonstrate check boxes

import javaawt

import javaawtevent

import javaapplet

ltapplet code=CheckboxDemo width=250 height=200gt

ltappletgt

public class CheckboxDemo extends Applet implements ItemListener

String msg =

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 32 of 38

Checkbox winXP winVista solaris mac

public void init()

winXP = new Checkbox(Windows XP null true)

mac = new Checkbox()

macsetLable(ldquoMac OSrdquo)

add(winXP)

add(mac)

winXPaddItemListener(this)

macaddItemListener(this)

public void itemStateChanged(ItemEvent ie)

repaint()

Display current state of the check boxes

public void paint(Graphics g)

msg = Current state

gdrawString(msg 6 80)

msg = Windows XP + winXPgetState()

gdrawString(msg 6 100)

msg = Mac OS + macgetState()

gdrawString(msg 6 120)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 33 of 38

c) Explain the techniques of session tracking management

(Any four techniques with explanation- 1 Mark each)

Ans Session tracking Techniques

1 User Authorization

Users can be authorized to use the web application in different ways Basic concept is that the

user will provide username and password to login to the application Based on that the user can

be identified and the session can be maintained

2 Hidden Fields

ltINPUT TYPE=rdquohiddenrdquo NAME=rdquotechnologyrdquo VALUE=rdquoservletrdquogt

Hidden fields like the above can be inserted in the webpages and information can be sent to the

server for session tracking These fields are not visible directly to the user but can be viewed

using view source option from the browsers This type doesnrsquot need any special configuration

from the browser of server and by default available to use for session tracking This cannot be

used for session tracking when the conversation included static resources lik html pages

3 URL Rewriting

Original URL httpserverportservletServletName

ewritten URL httpserverportservletServletNamesessionid=7456

When a request is made additional parameter is appended with the url In general added

additional parameter will be sessionid or sometimes the userid It will suffice to track the

session This type of session tracking doesnrsquot need any special support from the browser

Disadvantage is implementing this type of session tracking is tedious We need to keep track of

the parameter as a chain link until the conversation completes and also should make sure that

the parameter doesnrsquot clash with other application parameters

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 34 of 38

4 Cookies

Cookies are the mostly used technology for session tracking Cookie is a key value pair of

information sent by the server to the browser This should be saved by the browser in its space

in the client computer Whenever the browser sends a request to that server it sends the cookie

along with it Then the server can identify the client using the cookie

In java following is the source code snippet to create a cookie

Cookie cookie = new Cookie (ldquouserIDrdquo ldquo7456Prime)

resaddCookie(cookie)

5 Session tracking API

Session tracking API is built on top of the first four methods This is inorder to help the

developer to minimize the overhead of session tracking This type of session tracking is

provided by the underlying technology Lets take the java servlet example Then the servlet

container manages the session tracking task and the user need not do it explicitly using the java

servlets This is the best of all methods because all the management and errors related to

session tracking will be taken care of by the container itself

d) Give sequential steps for JTree in swing with example

(Steps- 2 Marks any small Example- 2 Marks)

Ans Steps for JTree

Atree is a component that presents a hierarchical view of data The user has the ability to

expand or collapse individual subtrees in this display Trees are implemented in Swing by

the JTree class

Here are the steps to follow to use a tree

1 Create an instance of JTree

2 Create a JScrollPane and specify the tree as the object to be scrolled

3 Add the tree to the scroll pane

4 Add the scroll pane to the content pane

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 35 of 38

Example

Demonstrate JTree

import javaawt

import javaxswingevent

import javaxswing

import javaxswingtree

ltapplet code=JTreeDemo width=400 height=200gt

ltappletgt

public class JTreeDemo extends JApplet

JTree tree

JLabel jlab

public void init()

try

SwingUtilitiesinvokeAndWait(

new Runnable()

public void run()

makeGUI()

)

catch (Exception exc)

Systemoutprintln(Cant create because of + exc)

private void makeGUI()

Create top node of tree

DefaultMutableTreeNode top = new DefaultMutableTreeNode(Options)

Create subtree of A

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 36 of 38

DefaultMutableTreeNode a = new DefaultMutableTreeNode(A)

topadd(a)

DefaultMutableTreeNode a1 = new DefaultMutableTreeNode(A1)

aadd(a1)

DefaultMutableTreeNode a2 = new DefaultMutableTreeNode(A2)

aadd(a2)

Create subtree of B

DefaultMutableTreeNode b = new DefaultMutableTreeNode(B)

topadd(b)

DefaultMutableTreeNode b1 = new DefaultMutableTreeNode(B1)

badd(b1)

DefaultMutableTreeNode b2 = new DefaultMutableTreeNode(B2)

badd(b2)

DefaultMutableTreeNode b3 = new DefaultMutableTreeNode(B3)

badd(b3)

Create the tree

tree = new JTree(top)

Add the tree to a scroll pane

JScrollPane jsp = new JScrollPane(tree)

Add the scroll pane to the content pane

add(jsp)

Add the label to the content pane

jlab = new JLabel()

add(jlab BorderLayoutSOUTH)

Handle tree selection events

treeaddTreeSelectionListener(new TreeSelectionListener()

public void valueChanged(TreeSelectionEvent tse)

jlabsetText(Selection is + tsegetPath())

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 37 of 38

e) Draw and explain the life cycle of servlet

(Explanation ndash 3 Marks Diagram -1 Marks)

Ans Three methods are central to the life cycle of a servlet

These are init( ) service( ) and destroy( )

They are implemented by every servlet and are invoked at specific times by the server Let

us consider a typical user scenario to understand when these methods are called

First assume that a user enters a Uniform Resource Locator (URL) to a web browser

The browser then generates an HTTP request for this URL This request is then sent to the

appropriate server

Second this HTTP request is received by the web server The server maps this request to

a particular servlet The servlet is dynamically retrieved and loaded into the address space

of the server

Third the server invokes the init( ) method of the servlet This method is invoked only

when the servlet is first loaded into memory It is possible to pass initialization parameters

to the servlet so it may configure itself

Fourth the server invokes the service( ) method of the servlet This method is called to

process the HTTP request You will see that it is possible for the servlet to read data that has

been provided in the HTTP request It may also formulate an HTTP response for the client

The servlet remains in the serverrsquos address space and is available to process any other

HTTP requests received from clients The service( ) method is called for each HTTP request

Finally the server may decide to unload the servlet from its memory The algorithms by

which this determination is made are specific to each server The server calls the destroy( )

method to relinquish any resources such as file handles that are allocated for the servlet

Important data may be saved to a persistent store The memory allocated for the servlet and

its objects can then be garbage collected

A servlet life cycle can be defined as the entire process from its creation till the destruction The

following are the paths followed by a servlet

The servlet is initialized by calling the init () method

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 38 of 38

The servlet calls service() method to process a clients request

The servlet is terminated by calling the destroy() method

Finally servlet is garbage collected by the garbage collector of the JVM

Initialization

(Load Resources)

Services

(Accept Requests)

Destruction

(Unload Resources)

Servlet

Request

Response

Page 20: AJP

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 20 of 38

pwclose()

d) Give steps to create simple servlet with example 4

(Steps- 2 Marks Any one Example ndash 2 Marks)

Ans Steps 1) Write a java servet code

Steps 2) Compile Servet by setting classpath with servlet-api library

Step 3) Copy the class servlet file in web apps classpath directory

Steps 4) Open the webxml open it and add servlet tag and sevlet mapping tag

Steps 5) Start web server(apche tomcat)

Steps 6) Browse servlet using java compatible browser like IE

Example shows to start create a file named WelcomeServletjava that contains the following

program

import javaio

importjavaxservlet

public class WelcomeServletDemo extends GenericServlet

public void service(ServletRequestrequestServletResponse response) throws

ServletExceptionIOException

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgtWelcome to Servlet)

pwclose()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 21 of 38

B) Attempt any one of the following Marks 6

a) Describe the two ndashtier and three ndashtier database design of JDBC API with neat diagram

(Explanation of Two-tier-2 Marks and Three-tier-2 Marks Diagram ndash 1 Mark each)

Ans Two Tier Architecture

In a two tier model a java application is designed to interact directly with the database

Application functionality is divided into these two layers

1) Application Layer Including the JDBC driver business logic and user interface

2) Database Layer including RDBMS

The interface to the database is handled by the Java Database Connectivity(JDBC) Driver

appropriate to the particularly database management system being accessed The JDBC Driver

passes SQL statements to the database and returns the results of those statements to the

application

A clientserver configuration is the special case of the two tier model where the database is

located on another machine referred to as the server The application runs on the client machine

which is connected to the server over a network Commonly the network is an Intranet using

dedicated database servers to support multiple clients but it can just as easily be the internet

Three Tier Architecture-

In the three tier model the client typically sends requests to an application server forming the

middle tier The application server interprets these requests and formats the necessary SQL

statement to fulfill

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 22 of 38

These requests and sends them to the database The database process the SQL statements and

sends result back to the application server which then sends them to the client

Following are some advantages of Three-tier architecture

1 Performance can be improved by separating the application server and database server

2 Business logic is clearly separated from the database

3 Client application can use a simple protocol such as CGI to access services

The three-tier model show in following fig is a common in web application In this scenario the

client tier is frequently implemented in a browse on a client machine the middle tier is

implemented in a web server with a Servlet engine and the database management system runs on

a dedicated database server

Following are the main components of three tier architecture

1 Client Tier - Typically this is thin presentation layer that may be implemented using a web

browser

2 Middle Tier - This tier handles the business or application logic This may be implemented

using a Servlet engine such as Tomcat or an application server such as JBOSS The JDBC

driver also resides in this layer

3 Data source layer This component includes the RDBMS

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 23 of 38

b) Write servlet which shows how many times user has visited the page in session

(Any Correct Logic ndash4 Marks Syntax ndash 2 Marks)

Ans import javaio

import javaxservlet

import javaxservlethttp

public class Session Travker extends HttpServlet

public void doGet(HttpServletRequest req HttpServletResponse res) throws ServletException

IOException

ressetContentType(ldquotexthtmlrdquo)

PrintWriter out = resgetWriter()

HttpSession session = reqgetSession(true)

Integer count= (Integer)sessiongetValue(ldquotrackercountrdquo)

if(count== null) count=new Interger(1)

else count = new Interger(count intValue() +1)

sessionputValue(ldquotrackercountrdquocount)

outprintln(ldquoltHTMLgtltHEADgtltTITLEgtSession TrackerltTITLEgtltHEADgtrdquo)

outprintln(ldquoltBODYgtltH1gtSession Tracking DemoltH1gtrdquo)

outprintln(ldquoYou have visited this pagerdquo +count +((countintValue() == 1)rdquotimerdquo

ldquotimesrdquo))outprinln(ltPgtrdquo)

outprintln(ldquoltH2gtSesssion dataltH2gtrdquo)

String[] names = sessiongetValueNames()

for(int i=0 ilt nameslength i++)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 24 of 38

outprintln(names[i] + ldquo rdquo + sessiongetvalue(names[i])+ ldquoltBRgtrdquo)

outprintln(ldquoltBODYgtltHTMLgtrdquo)

5 Attempt any two of the following Marks 16

a) Write a program to display all records from Employee table from database using

JDBC

(Assume suitable data for table- Load driver create connection execute Query - 1 Mark

each Display data- 3 Marks Syntax ndash 2 Marks)

Ans import javasql

import javasqlStatement

import javaapplet

import javaawt

public class DisplayTable

public static void main( String args[])

RsultSet rs

Connection conn

try

String s1

ClassforName(sun jdbcodbcJdbcOdbcDriver)

Systemoutprintln(Connecting to a selected database)

String url=rdquojdbcodbcabcrdquo

conn = DriverManagergetConnection(DB_URL USER PASS)

Systemoutprintln(Connected database successfully)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 25 of 38

Systemoutprintln(Creating statement)

stmt = conncreateStatement()

sql = SELECT FROM Employee

ResultSet rs = stmtexecuteQuery(sql)

Tables fields assumed are id first last age

while(rsnext())

int id = rsgetInt(id)

int age = rsgetInt(age)

String first = rsgetString(first)

String last = rsgetString(last)

Systemoutprint(ID + id)

Systemoutprint( Age + age)

Systemoutprint( First + first)

Systemoutprintln( Last + last)

rsclose()

catch(SQLException se)

Handle errors for JDBC

seprintStackTrace()

catch(Exception e)

Handle errors for ClassforName

eprintStackTrace()

finally

finally block used to close resources

try

if(stmt=null)

connclose()

catch(SQLException se)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 26 of 38

b) Define the term

i) Reserved socket ii) proxy server

iii) Datagram iv) URL connection 4

(Each term- 2 Marks)

Ans i) Reserved socket

A socket is one end-point of a two-way communication link between two programs running on

the network Socket classes are used to represent the connection between a client program and a

server program

Reserved socket The socket which are reserved for specific protocols for communication

purpose are known as reseved sockets

TCPIP uses or reserves the lower 1024 ports for specific protocols

Example port number 23 is for Telnet 25 is for smtp 21 is for ftp 13 for daytime 110 for pop3

and so on Protocol decides how a client should interact with the port

ii) Proxy server

A proxy server is a computer that offers a computer network service to allow clients to make

indirect network connections to other network services A client connects to the proxy server

then requests a connection file or other resource available on a different server The proxy

provides the resource either by connecting to the specified server or by serving it from a cache In

some cases the proxy may alter the clients request or the servers response for various purposes

Purposes of the proxy servers

To keep machines behind it anonymous mainly for security

To speed up access to resources (using caching) Web proxies are commonly used to

cache web pages from a web server

To prevent downloading the same content multiple times (and save bandwidth)

To log audit usage eg to provide company employee Internet usage reporting

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 27 of 38

To scan transmitted content for malware before delivery

To scan outbound content eg for data loss prevention

iii) Datagram

Datagrams are bundles of information passed between machines They are somewhat like a hard

throw from a well-trained but blindfolded catcher to the third baseman Once the datagram has

been released to its intended target there is no assurance that it will arrive or even that

someone will be there to catch it Likewise when the datagram is received there is no

assurance that it hasnrsquot been damaged in transit or that whoever sent it is still there to receive a

response

Java implements datagrams on top of the UDP protocol by using two classes

The DatagramPacket object is the data container while the DatagramSocket is the mechanism

used to send or receive the DatagramPackets

iv) URL connection

URLConnection is a general-purpose class for accessing the attributes of a remote resource

Once you make a connection to a remote server you can use URLConnection to inspect the

Properties of the remote object before actually transporting it locally These attributes are

exposed by the HTTP protocol specification and as such only make sense for URL objects

that are using the HTTP protocol

URLConnection defines several methods

int getContentLength( )

String getContentType( )

long getDate( )

long getExpiration( )

String getHeaderField(int idx)

long getLastModified( )

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 28 of 38

c) Write a program to display three text fields and a button below to all an Applet Insert

the integer valuer from three text fields After pressing the button the background colour

of applet will be changed as per the RGB combination of the values given in the text field

(Correct logic - 6 Marks Syntax - 2 Marks)

4

Ans import javaawt

import javaawtevent

import javaapplet

ltapplet code=rdquoClrclassrdquo width=250 heigth=250gtltappletgt

public class Clrextends Applet implements ActionListener

int r g b

TextField t1t2t3

Button b1

Color c1

public void init()

t1= new TextField(5)

t2= new TextField(8)

t3= new TextField(11)

b1 = new Button(ldquo Set Colorrdquo)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 29 of 38

add(t1)

add(t2)

add(t3)

add(b1)

b1addActionListener(this)

public void void paint( )

setBackground(c1)

public void actionPerformed(ActionEvent ae)

r=IntegerparseInt(t1getText())

g=IntegerparseInt(t2getText())

b=IntegerparseInt(t3getText())

c1= new Color(rgb)

repaint()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 30 of 38

6) Attempt any four of the following Marks 16

a) How to check how many fonts are available in the computer system 4

Explain with example

(Explanation -2 Marks Example-2 Marks)

Ans When working with fonts often you need to know which fonts are available on your machine To

ontain this information you can use the getAvailableFontFamilyNames() method defined by the

GraphicsEnvironment classIt is shown here

String[ ] getAvailableFontFamilyNames( )

This method returns an array of string that contains the names of the available font families

Since this methods is members of GraphicsEnvironment you need a GraphicsEnvironment

reference to call itYou can obtain this reference by using the getlocalGrahicsEnvironmet() static

method which is derfined by GraphicsEnvironmentIt is shown here

static GraphicsEnvironment getLocalGraphicsEnvironment( )

Here is an applet that shown how to obtain the names of the available font families

ltapplet code=rdquoAllFontsrdquo width=500 height=100gt

ltappletgt

import javaapplet

import javaawt

public class AllFonts extends Applet

public void paint(Graphics g)

string fonts= ldquo rdquo

stirng allFontsList[]

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 31 of 38

GraphicsEnvironment t = GraphicsEnvironmentgetLocalGraphicsEnvironment()

allFontList = tgetAvailableFontFamilyNames()

for(int i= 0 ilt allFontsListlength i++)

fonts= fonts + allFontList[i] + ldquo rdquo

gdrawString(msg416)

b) Explain following check box class methods with appropriate example 4

i) Void setLable (String str) ii) Boolean getState ( )

(Explanation of each method-1 Marks Example-2 Marks)

Ans

i) void setLable(String str)

This method is used to set the label of check box

ii) Boolean getState()

This method is used to retrieve the current state of a check box It returns the value either true or

false depends on check box is selected or not

Example

Demonstrate check boxes

import javaawt

import javaawtevent

import javaapplet

ltapplet code=CheckboxDemo width=250 height=200gt

ltappletgt

public class CheckboxDemo extends Applet implements ItemListener

String msg =

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 32 of 38

Checkbox winXP winVista solaris mac

public void init()

winXP = new Checkbox(Windows XP null true)

mac = new Checkbox()

macsetLable(ldquoMac OSrdquo)

add(winXP)

add(mac)

winXPaddItemListener(this)

macaddItemListener(this)

public void itemStateChanged(ItemEvent ie)

repaint()

Display current state of the check boxes

public void paint(Graphics g)

msg = Current state

gdrawString(msg 6 80)

msg = Windows XP + winXPgetState()

gdrawString(msg 6 100)

msg = Mac OS + macgetState()

gdrawString(msg 6 120)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 33 of 38

c) Explain the techniques of session tracking management

(Any four techniques with explanation- 1 Mark each)

Ans Session tracking Techniques

1 User Authorization

Users can be authorized to use the web application in different ways Basic concept is that the

user will provide username and password to login to the application Based on that the user can

be identified and the session can be maintained

2 Hidden Fields

ltINPUT TYPE=rdquohiddenrdquo NAME=rdquotechnologyrdquo VALUE=rdquoservletrdquogt

Hidden fields like the above can be inserted in the webpages and information can be sent to the

server for session tracking These fields are not visible directly to the user but can be viewed

using view source option from the browsers This type doesnrsquot need any special configuration

from the browser of server and by default available to use for session tracking This cannot be

used for session tracking when the conversation included static resources lik html pages

3 URL Rewriting

Original URL httpserverportservletServletName

ewritten URL httpserverportservletServletNamesessionid=7456

When a request is made additional parameter is appended with the url In general added

additional parameter will be sessionid or sometimes the userid It will suffice to track the

session This type of session tracking doesnrsquot need any special support from the browser

Disadvantage is implementing this type of session tracking is tedious We need to keep track of

the parameter as a chain link until the conversation completes and also should make sure that

the parameter doesnrsquot clash with other application parameters

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 34 of 38

4 Cookies

Cookies are the mostly used technology for session tracking Cookie is a key value pair of

information sent by the server to the browser This should be saved by the browser in its space

in the client computer Whenever the browser sends a request to that server it sends the cookie

along with it Then the server can identify the client using the cookie

In java following is the source code snippet to create a cookie

Cookie cookie = new Cookie (ldquouserIDrdquo ldquo7456Prime)

resaddCookie(cookie)

5 Session tracking API

Session tracking API is built on top of the first four methods This is inorder to help the

developer to minimize the overhead of session tracking This type of session tracking is

provided by the underlying technology Lets take the java servlet example Then the servlet

container manages the session tracking task and the user need not do it explicitly using the java

servlets This is the best of all methods because all the management and errors related to

session tracking will be taken care of by the container itself

d) Give sequential steps for JTree in swing with example

(Steps- 2 Marks any small Example- 2 Marks)

Ans Steps for JTree

Atree is a component that presents a hierarchical view of data The user has the ability to

expand or collapse individual subtrees in this display Trees are implemented in Swing by

the JTree class

Here are the steps to follow to use a tree

1 Create an instance of JTree

2 Create a JScrollPane and specify the tree as the object to be scrolled

3 Add the tree to the scroll pane

4 Add the scroll pane to the content pane

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 35 of 38

Example

Demonstrate JTree

import javaawt

import javaxswingevent

import javaxswing

import javaxswingtree

ltapplet code=JTreeDemo width=400 height=200gt

ltappletgt

public class JTreeDemo extends JApplet

JTree tree

JLabel jlab

public void init()

try

SwingUtilitiesinvokeAndWait(

new Runnable()

public void run()

makeGUI()

)

catch (Exception exc)

Systemoutprintln(Cant create because of + exc)

private void makeGUI()

Create top node of tree

DefaultMutableTreeNode top = new DefaultMutableTreeNode(Options)

Create subtree of A

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 36 of 38

DefaultMutableTreeNode a = new DefaultMutableTreeNode(A)

topadd(a)

DefaultMutableTreeNode a1 = new DefaultMutableTreeNode(A1)

aadd(a1)

DefaultMutableTreeNode a2 = new DefaultMutableTreeNode(A2)

aadd(a2)

Create subtree of B

DefaultMutableTreeNode b = new DefaultMutableTreeNode(B)

topadd(b)

DefaultMutableTreeNode b1 = new DefaultMutableTreeNode(B1)

badd(b1)

DefaultMutableTreeNode b2 = new DefaultMutableTreeNode(B2)

badd(b2)

DefaultMutableTreeNode b3 = new DefaultMutableTreeNode(B3)

badd(b3)

Create the tree

tree = new JTree(top)

Add the tree to a scroll pane

JScrollPane jsp = new JScrollPane(tree)

Add the scroll pane to the content pane

add(jsp)

Add the label to the content pane

jlab = new JLabel()

add(jlab BorderLayoutSOUTH)

Handle tree selection events

treeaddTreeSelectionListener(new TreeSelectionListener()

public void valueChanged(TreeSelectionEvent tse)

jlabsetText(Selection is + tsegetPath())

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 37 of 38

e) Draw and explain the life cycle of servlet

(Explanation ndash 3 Marks Diagram -1 Marks)

Ans Three methods are central to the life cycle of a servlet

These are init( ) service( ) and destroy( )

They are implemented by every servlet and are invoked at specific times by the server Let

us consider a typical user scenario to understand when these methods are called

First assume that a user enters a Uniform Resource Locator (URL) to a web browser

The browser then generates an HTTP request for this URL This request is then sent to the

appropriate server

Second this HTTP request is received by the web server The server maps this request to

a particular servlet The servlet is dynamically retrieved and loaded into the address space

of the server

Third the server invokes the init( ) method of the servlet This method is invoked only

when the servlet is first loaded into memory It is possible to pass initialization parameters

to the servlet so it may configure itself

Fourth the server invokes the service( ) method of the servlet This method is called to

process the HTTP request You will see that it is possible for the servlet to read data that has

been provided in the HTTP request It may also formulate an HTTP response for the client

The servlet remains in the serverrsquos address space and is available to process any other

HTTP requests received from clients The service( ) method is called for each HTTP request

Finally the server may decide to unload the servlet from its memory The algorithms by

which this determination is made are specific to each server The server calls the destroy( )

method to relinquish any resources such as file handles that are allocated for the servlet

Important data may be saved to a persistent store The memory allocated for the servlet and

its objects can then be garbage collected

A servlet life cycle can be defined as the entire process from its creation till the destruction The

following are the paths followed by a servlet

The servlet is initialized by calling the init () method

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 38 of 38

The servlet calls service() method to process a clients request

The servlet is terminated by calling the destroy() method

Finally servlet is garbage collected by the garbage collector of the JVM

Initialization

(Load Resources)

Services

(Accept Requests)

Destruction

(Unload Resources)

Servlet

Request

Response

Page 21: AJP

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 21 of 38

B) Attempt any one of the following Marks 6

a) Describe the two ndashtier and three ndashtier database design of JDBC API with neat diagram

(Explanation of Two-tier-2 Marks and Three-tier-2 Marks Diagram ndash 1 Mark each)

Ans Two Tier Architecture

In a two tier model a java application is designed to interact directly with the database

Application functionality is divided into these two layers

1) Application Layer Including the JDBC driver business logic and user interface

2) Database Layer including RDBMS

The interface to the database is handled by the Java Database Connectivity(JDBC) Driver

appropriate to the particularly database management system being accessed The JDBC Driver

passes SQL statements to the database and returns the results of those statements to the

application

A clientserver configuration is the special case of the two tier model where the database is

located on another machine referred to as the server The application runs on the client machine

which is connected to the server over a network Commonly the network is an Intranet using

dedicated database servers to support multiple clients but it can just as easily be the internet

Three Tier Architecture-

In the three tier model the client typically sends requests to an application server forming the

middle tier The application server interprets these requests and formats the necessary SQL

statement to fulfill

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 22 of 38

These requests and sends them to the database The database process the SQL statements and

sends result back to the application server which then sends them to the client

Following are some advantages of Three-tier architecture

1 Performance can be improved by separating the application server and database server

2 Business logic is clearly separated from the database

3 Client application can use a simple protocol such as CGI to access services

The three-tier model show in following fig is a common in web application In this scenario the

client tier is frequently implemented in a browse on a client machine the middle tier is

implemented in a web server with a Servlet engine and the database management system runs on

a dedicated database server

Following are the main components of three tier architecture

1 Client Tier - Typically this is thin presentation layer that may be implemented using a web

browser

2 Middle Tier - This tier handles the business or application logic This may be implemented

using a Servlet engine such as Tomcat or an application server such as JBOSS The JDBC

driver also resides in this layer

3 Data source layer This component includes the RDBMS

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 23 of 38

b) Write servlet which shows how many times user has visited the page in session

(Any Correct Logic ndash4 Marks Syntax ndash 2 Marks)

Ans import javaio

import javaxservlet

import javaxservlethttp

public class Session Travker extends HttpServlet

public void doGet(HttpServletRequest req HttpServletResponse res) throws ServletException

IOException

ressetContentType(ldquotexthtmlrdquo)

PrintWriter out = resgetWriter()

HttpSession session = reqgetSession(true)

Integer count= (Integer)sessiongetValue(ldquotrackercountrdquo)

if(count== null) count=new Interger(1)

else count = new Interger(count intValue() +1)

sessionputValue(ldquotrackercountrdquocount)

outprintln(ldquoltHTMLgtltHEADgtltTITLEgtSession TrackerltTITLEgtltHEADgtrdquo)

outprintln(ldquoltBODYgtltH1gtSession Tracking DemoltH1gtrdquo)

outprintln(ldquoYou have visited this pagerdquo +count +((countintValue() == 1)rdquotimerdquo

ldquotimesrdquo))outprinln(ltPgtrdquo)

outprintln(ldquoltH2gtSesssion dataltH2gtrdquo)

String[] names = sessiongetValueNames()

for(int i=0 ilt nameslength i++)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 24 of 38

outprintln(names[i] + ldquo rdquo + sessiongetvalue(names[i])+ ldquoltBRgtrdquo)

outprintln(ldquoltBODYgtltHTMLgtrdquo)

5 Attempt any two of the following Marks 16

a) Write a program to display all records from Employee table from database using

JDBC

(Assume suitable data for table- Load driver create connection execute Query - 1 Mark

each Display data- 3 Marks Syntax ndash 2 Marks)

Ans import javasql

import javasqlStatement

import javaapplet

import javaawt

public class DisplayTable

public static void main( String args[])

RsultSet rs

Connection conn

try

String s1

ClassforName(sun jdbcodbcJdbcOdbcDriver)

Systemoutprintln(Connecting to a selected database)

String url=rdquojdbcodbcabcrdquo

conn = DriverManagergetConnection(DB_URL USER PASS)

Systemoutprintln(Connected database successfully)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 25 of 38

Systemoutprintln(Creating statement)

stmt = conncreateStatement()

sql = SELECT FROM Employee

ResultSet rs = stmtexecuteQuery(sql)

Tables fields assumed are id first last age

while(rsnext())

int id = rsgetInt(id)

int age = rsgetInt(age)

String first = rsgetString(first)

String last = rsgetString(last)

Systemoutprint(ID + id)

Systemoutprint( Age + age)

Systemoutprint( First + first)

Systemoutprintln( Last + last)

rsclose()

catch(SQLException se)

Handle errors for JDBC

seprintStackTrace()

catch(Exception e)

Handle errors for ClassforName

eprintStackTrace()

finally

finally block used to close resources

try

if(stmt=null)

connclose()

catch(SQLException se)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 26 of 38

b) Define the term

i) Reserved socket ii) proxy server

iii) Datagram iv) URL connection 4

(Each term- 2 Marks)

Ans i) Reserved socket

A socket is one end-point of a two-way communication link between two programs running on

the network Socket classes are used to represent the connection between a client program and a

server program

Reserved socket The socket which are reserved for specific protocols for communication

purpose are known as reseved sockets

TCPIP uses or reserves the lower 1024 ports for specific protocols

Example port number 23 is for Telnet 25 is for smtp 21 is for ftp 13 for daytime 110 for pop3

and so on Protocol decides how a client should interact with the port

ii) Proxy server

A proxy server is a computer that offers a computer network service to allow clients to make

indirect network connections to other network services A client connects to the proxy server

then requests a connection file or other resource available on a different server The proxy

provides the resource either by connecting to the specified server or by serving it from a cache In

some cases the proxy may alter the clients request or the servers response for various purposes

Purposes of the proxy servers

To keep machines behind it anonymous mainly for security

To speed up access to resources (using caching) Web proxies are commonly used to

cache web pages from a web server

To prevent downloading the same content multiple times (and save bandwidth)

To log audit usage eg to provide company employee Internet usage reporting

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 27 of 38

To scan transmitted content for malware before delivery

To scan outbound content eg for data loss prevention

iii) Datagram

Datagrams are bundles of information passed between machines They are somewhat like a hard

throw from a well-trained but blindfolded catcher to the third baseman Once the datagram has

been released to its intended target there is no assurance that it will arrive or even that

someone will be there to catch it Likewise when the datagram is received there is no

assurance that it hasnrsquot been damaged in transit or that whoever sent it is still there to receive a

response

Java implements datagrams on top of the UDP protocol by using two classes

The DatagramPacket object is the data container while the DatagramSocket is the mechanism

used to send or receive the DatagramPackets

iv) URL connection

URLConnection is a general-purpose class for accessing the attributes of a remote resource

Once you make a connection to a remote server you can use URLConnection to inspect the

Properties of the remote object before actually transporting it locally These attributes are

exposed by the HTTP protocol specification and as such only make sense for URL objects

that are using the HTTP protocol

URLConnection defines several methods

int getContentLength( )

String getContentType( )

long getDate( )

long getExpiration( )

String getHeaderField(int idx)

long getLastModified( )

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 28 of 38

c) Write a program to display three text fields and a button below to all an Applet Insert

the integer valuer from three text fields After pressing the button the background colour

of applet will be changed as per the RGB combination of the values given in the text field

(Correct logic - 6 Marks Syntax - 2 Marks)

4

Ans import javaawt

import javaawtevent

import javaapplet

ltapplet code=rdquoClrclassrdquo width=250 heigth=250gtltappletgt

public class Clrextends Applet implements ActionListener

int r g b

TextField t1t2t3

Button b1

Color c1

public void init()

t1= new TextField(5)

t2= new TextField(8)

t3= new TextField(11)

b1 = new Button(ldquo Set Colorrdquo)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 29 of 38

add(t1)

add(t2)

add(t3)

add(b1)

b1addActionListener(this)

public void void paint( )

setBackground(c1)

public void actionPerformed(ActionEvent ae)

r=IntegerparseInt(t1getText())

g=IntegerparseInt(t2getText())

b=IntegerparseInt(t3getText())

c1= new Color(rgb)

repaint()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 30 of 38

6) Attempt any four of the following Marks 16

a) How to check how many fonts are available in the computer system 4

Explain with example

(Explanation -2 Marks Example-2 Marks)

Ans When working with fonts often you need to know which fonts are available on your machine To

ontain this information you can use the getAvailableFontFamilyNames() method defined by the

GraphicsEnvironment classIt is shown here

String[ ] getAvailableFontFamilyNames( )

This method returns an array of string that contains the names of the available font families

Since this methods is members of GraphicsEnvironment you need a GraphicsEnvironment

reference to call itYou can obtain this reference by using the getlocalGrahicsEnvironmet() static

method which is derfined by GraphicsEnvironmentIt is shown here

static GraphicsEnvironment getLocalGraphicsEnvironment( )

Here is an applet that shown how to obtain the names of the available font families

ltapplet code=rdquoAllFontsrdquo width=500 height=100gt

ltappletgt

import javaapplet

import javaawt

public class AllFonts extends Applet

public void paint(Graphics g)

string fonts= ldquo rdquo

stirng allFontsList[]

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 31 of 38

GraphicsEnvironment t = GraphicsEnvironmentgetLocalGraphicsEnvironment()

allFontList = tgetAvailableFontFamilyNames()

for(int i= 0 ilt allFontsListlength i++)

fonts= fonts + allFontList[i] + ldquo rdquo

gdrawString(msg416)

b) Explain following check box class methods with appropriate example 4

i) Void setLable (String str) ii) Boolean getState ( )

(Explanation of each method-1 Marks Example-2 Marks)

Ans

i) void setLable(String str)

This method is used to set the label of check box

ii) Boolean getState()

This method is used to retrieve the current state of a check box It returns the value either true or

false depends on check box is selected or not

Example

Demonstrate check boxes

import javaawt

import javaawtevent

import javaapplet

ltapplet code=CheckboxDemo width=250 height=200gt

ltappletgt

public class CheckboxDemo extends Applet implements ItemListener

String msg =

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 32 of 38

Checkbox winXP winVista solaris mac

public void init()

winXP = new Checkbox(Windows XP null true)

mac = new Checkbox()

macsetLable(ldquoMac OSrdquo)

add(winXP)

add(mac)

winXPaddItemListener(this)

macaddItemListener(this)

public void itemStateChanged(ItemEvent ie)

repaint()

Display current state of the check boxes

public void paint(Graphics g)

msg = Current state

gdrawString(msg 6 80)

msg = Windows XP + winXPgetState()

gdrawString(msg 6 100)

msg = Mac OS + macgetState()

gdrawString(msg 6 120)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 33 of 38

c) Explain the techniques of session tracking management

(Any four techniques with explanation- 1 Mark each)

Ans Session tracking Techniques

1 User Authorization

Users can be authorized to use the web application in different ways Basic concept is that the

user will provide username and password to login to the application Based on that the user can

be identified and the session can be maintained

2 Hidden Fields

ltINPUT TYPE=rdquohiddenrdquo NAME=rdquotechnologyrdquo VALUE=rdquoservletrdquogt

Hidden fields like the above can be inserted in the webpages and information can be sent to the

server for session tracking These fields are not visible directly to the user but can be viewed

using view source option from the browsers This type doesnrsquot need any special configuration

from the browser of server and by default available to use for session tracking This cannot be

used for session tracking when the conversation included static resources lik html pages

3 URL Rewriting

Original URL httpserverportservletServletName

ewritten URL httpserverportservletServletNamesessionid=7456

When a request is made additional parameter is appended with the url In general added

additional parameter will be sessionid or sometimes the userid It will suffice to track the

session This type of session tracking doesnrsquot need any special support from the browser

Disadvantage is implementing this type of session tracking is tedious We need to keep track of

the parameter as a chain link until the conversation completes and also should make sure that

the parameter doesnrsquot clash with other application parameters

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 34 of 38

4 Cookies

Cookies are the mostly used technology for session tracking Cookie is a key value pair of

information sent by the server to the browser This should be saved by the browser in its space

in the client computer Whenever the browser sends a request to that server it sends the cookie

along with it Then the server can identify the client using the cookie

In java following is the source code snippet to create a cookie

Cookie cookie = new Cookie (ldquouserIDrdquo ldquo7456Prime)

resaddCookie(cookie)

5 Session tracking API

Session tracking API is built on top of the first four methods This is inorder to help the

developer to minimize the overhead of session tracking This type of session tracking is

provided by the underlying technology Lets take the java servlet example Then the servlet

container manages the session tracking task and the user need not do it explicitly using the java

servlets This is the best of all methods because all the management and errors related to

session tracking will be taken care of by the container itself

d) Give sequential steps for JTree in swing with example

(Steps- 2 Marks any small Example- 2 Marks)

Ans Steps for JTree

Atree is a component that presents a hierarchical view of data The user has the ability to

expand or collapse individual subtrees in this display Trees are implemented in Swing by

the JTree class

Here are the steps to follow to use a tree

1 Create an instance of JTree

2 Create a JScrollPane and specify the tree as the object to be scrolled

3 Add the tree to the scroll pane

4 Add the scroll pane to the content pane

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 35 of 38

Example

Demonstrate JTree

import javaawt

import javaxswingevent

import javaxswing

import javaxswingtree

ltapplet code=JTreeDemo width=400 height=200gt

ltappletgt

public class JTreeDemo extends JApplet

JTree tree

JLabel jlab

public void init()

try

SwingUtilitiesinvokeAndWait(

new Runnable()

public void run()

makeGUI()

)

catch (Exception exc)

Systemoutprintln(Cant create because of + exc)

private void makeGUI()

Create top node of tree

DefaultMutableTreeNode top = new DefaultMutableTreeNode(Options)

Create subtree of A

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 36 of 38

DefaultMutableTreeNode a = new DefaultMutableTreeNode(A)

topadd(a)

DefaultMutableTreeNode a1 = new DefaultMutableTreeNode(A1)

aadd(a1)

DefaultMutableTreeNode a2 = new DefaultMutableTreeNode(A2)

aadd(a2)

Create subtree of B

DefaultMutableTreeNode b = new DefaultMutableTreeNode(B)

topadd(b)

DefaultMutableTreeNode b1 = new DefaultMutableTreeNode(B1)

badd(b1)

DefaultMutableTreeNode b2 = new DefaultMutableTreeNode(B2)

badd(b2)

DefaultMutableTreeNode b3 = new DefaultMutableTreeNode(B3)

badd(b3)

Create the tree

tree = new JTree(top)

Add the tree to a scroll pane

JScrollPane jsp = new JScrollPane(tree)

Add the scroll pane to the content pane

add(jsp)

Add the label to the content pane

jlab = new JLabel()

add(jlab BorderLayoutSOUTH)

Handle tree selection events

treeaddTreeSelectionListener(new TreeSelectionListener()

public void valueChanged(TreeSelectionEvent tse)

jlabsetText(Selection is + tsegetPath())

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 37 of 38

e) Draw and explain the life cycle of servlet

(Explanation ndash 3 Marks Diagram -1 Marks)

Ans Three methods are central to the life cycle of a servlet

These are init( ) service( ) and destroy( )

They are implemented by every servlet and are invoked at specific times by the server Let

us consider a typical user scenario to understand when these methods are called

First assume that a user enters a Uniform Resource Locator (URL) to a web browser

The browser then generates an HTTP request for this URL This request is then sent to the

appropriate server

Second this HTTP request is received by the web server The server maps this request to

a particular servlet The servlet is dynamically retrieved and loaded into the address space

of the server

Third the server invokes the init( ) method of the servlet This method is invoked only

when the servlet is first loaded into memory It is possible to pass initialization parameters

to the servlet so it may configure itself

Fourth the server invokes the service( ) method of the servlet This method is called to

process the HTTP request You will see that it is possible for the servlet to read data that has

been provided in the HTTP request It may also formulate an HTTP response for the client

The servlet remains in the serverrsquos address space and is available to process any other

HTTP requests received from clients The service( ) method is called for each HTTP request

Finally the server may decide to unload the servlet from its memory The algorithms by

which this determination is made are specific to each server The server calls the destroy( )

method to relinquish any resources such as file handles that are allocated for the servlet

Important data may be saved to a persistent store The memory allocated for the servlet and

its objects can then be garbage collected

A servlet life cycle can be defined as the entire process from its creation till the destruction The

following are the paths followed by a servlet

The servlet is initialized by calling the init () method

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 38 of 38

The servlet calls service() method to process a clients request

The servlet is terminated by calling the destroy() method

Finally servlet is garbage collected by the garbage collector of the JVM

Initialization

(Load Resources)

Services

(Accept Requests)

Destruction

(Unload Resources)

Servlet

Request

Response

Page 22: AJP

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 22 of 38

These requests and sends them to the database The database process the SQL statements and

sends result back to the application server which then sends them to the client

Following are some advantages of Three-tier architecture

1 Performance can be improved by separating the application server and database server

2 Business logic is clearly separated from the database

3 Client application can use a simple protocol such as CGI to access services

The three-tier model show in following fig is a common in web application In this scenario the

client tier is frequently implemented in a browse on a client machine the middle tier is

implemented in a web server with a Servlet engine and the database management system runs on

a dedicated database server

Following are the main components of three tier architecture

1 Client Tier - Typically this is thin presentation layer that may be implemented using a web

browser

2 Middle Tier - This tier handles the business or application logic This may be implemented

using a Servlet engine such as Tomcat or an application server such as JBOSS The JDBC

driver also resides in this layer

3 Data source layer This component includes the RDBMS

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 23 of 38

b) Write servlet which shows how many times user has visited the page in session

(Any Correct Logic ndash4 Marks Syntax ndash 2 Marks)

Ans import javaio

import javaxservlet

import javaxservlethttp

public class Session Travker extends HttpServlet

public void doGet(HttpServletRequest req HttpServletResponse res) throws ServletException

IOException

ressetContentType(ldquotexthtmlrdquo)

PrintWriter out = resgetWriter()

HttpSession session = reqgetSession(true)

Integer count= (Integer)sessiongetValue(ldquotrackercountrdquo)

if(count== null) count=new Interger(1)

else count = new Interger(count intValue() +1)

sessionputValue(ldquotrackercountrdquocount)

outprintln(ldquoltHTMLgtltHEADgtltTITLEgtSession TrackerltTITLEgtltHEADgtrdquo)

outprintln(ldquoltBODYgtltH1gtSession Tracking DemoltH1gtrdquo)

outprintln(ldquoYou have visited this pagerdquo +count +((countintValue() == 1)rdquotimerdquo

ldquotimesrdquo))outprinln(ltPgtrdquo)

outprintln(ldquoltH2gtSesssion dataltH2gtrdquo)

String[] names = sessiongetValueNames()

for(int i=0 ilt nameslength i++)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 24 of 38

outprintln(names[i] + ldquo rdquo + sessiongetvalue(names[i])+ ldquoltBRgtrdquo)

outprintln(ldquoltBODYgtltHTMLgtrdquo)

5 Attempt any two of the following Marks 16

a) Write a program to display all records from Employee table from database using

JDBC

(Assume suitable data for table- Load driver create connection execute Query - 1 Mark

each Display data- 3 Marks Syntax ndash 2 Marks)

Ans import javasql

import javasqlStatement

import javaapplet

import javaawt

public class DisplayTable

public static void main( String args[])

RsultSet rs

Connection conn

try

String s1

ClassforName(sun jdbcodbcJdbcOdbcDriver)

Systemoutprintln(Connecting to a selected database)

String url=rdquojdbcodbcabcrdquo

conn = DriverManagergetConnection(DB_URL USER PASS)

Systemoutprintln(Connected database successfully)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 25 of 38

Systemoutprintln(Creating statement)

stmt = conncreateStatement()

sql = SELECT FROM Employee

ResultSet rs = stmtexecuteQuery(sql)

Tables fields assumed are id first last age

while(rsnext())

int id = rsgetInt(id)

int age = rsgetInt(age)

String first = rsgetString(first)

String last = rsgetString(last)

Systemoutprint(ID + id)

Systemoutprint( Age + age)

Systemoutprint( First + first)

Systemoutprintln( Last + last)

rsclose()

catch(SQLException se)

Handle errors for JDBC

seprintStackTrace()

catch(Exception e)

Handle errors for ClassforName

eprintStackTrace()

finally

finally block used to close resources

try

if(stmt=null)

connclose()

catch(SQLException se)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 26 of 38

b) Define the term

i) Reserved socket ii) proxy server

iii) Datagram iv) URL connection 4

(Each term- 2 Marks)

Ans i) Reserved socket

A socket is one end-point of a two-way communication link between two programs running on

the network Socket classes are used to represent the connection between a client program and a

server program

Reserved socket The socket which are reserved for specific protocols for communication

purpose are known as reseved sockets

TCPIP uses or reserves the lower 1024 ports for specific protocols

Example port number 23 is for Telnet 25 is for smtp 21 is for ftp 13 for daytime 110 for pop3

and so on Protocol decides how a client should interact with the port

ii) Proxy server

A proxy server is a computer that offers a computer network service to allow clients to make

indirect network connections to other network services A client connects to the proxy server

then requests a connection file or other resource available on a different server The proxy

provides the resource either by connecting to the specified server or by serving it from a cache In

some cases the proxy may alter the clients request or the servers response for various purposes

Purposes of the proxy servers

To keep machines behind it anonymous mainly for security

To speed up access to resources (using caching) Web proxies are commonly used to

cache web pages from a web server

To prevent downloading the same content multiple times (and save bandwidth)

To log audit usage eg to provide company employee Internet usage reporting

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 27 of 38

To scan transmitted content for malware before delivery

To scan outbound content eg for data loss prevention

iii) Datagram

Datagrams are bundles of information passed between machines They are somewhat like a hard

throw from a well-trained but blindfolded catcher to the third baseman Once the datagram has

been released to its intended target there is no assurance that it will arrive or even that

someone will be there to catch it Likewise when the datagram is received there is no

assurance that it hasnrsquot been damaged in transit or that whoever sent it is still there to receive a

response

Java implements datagrams on top of the UDP protocol by using two classes

The DatagramPacket object is the data container while the DatagramSocket is the mechanism

used to send or receive the DatagramPackets

iv) URL connection

URLConnection is a general-purpose class for accessing the attributes of a remote resource

Once you make a connection to a remote server you can use URLConnection to inspect the

Properties of the remote object before actually transporting it locally These attributes are

exposed by the HTTP protocol specification and as such only make sense for URL objects

that are using the HTTP protocol

URLConnection defines several methods

int getContentLength( )

String getContentType( )

long getDate( )

long getExpiration( )

String getHeaderField(int idx)

long getLastModified( )

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 28 of 38

c) Write a program to display three text fields and a button below to all an Applet Insert

the integer valuer from three text fields After pressing the button the background colour

of applet will be changed as per the RGB combination of the values given in the text field

(Correct logic - 6 Marks Syntax - 2 Marks)

4

Ans import javaawt

import javaawtevent

import javaapplet

ltapplet code=rdquoClrclassrdquo width=250 heigth=250gtltappletgt

public class Clrextends Applet implements ActionListener

int r g b

TextField t1t2t3

Button b1

Color c1

public void init()

t1= new TextField(5)

t2= new TextField(8)

t3= new TextField(11)

b1 = new Button(ldquo Set Colorrdquo)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 29 of 38

add(t1)

add(t2)

add(t3)

add(b1)

b1addActionListener(this)

public void void paint( )

setBackground(c1)

public void actionPerformed(ActionEvent ae)

r=IntegerparseInt(t1getText())

g=IntegerparseInt(t2getText())

b=IntegerparseInt(t3getText())

c1= new Color(rgb)

repaint()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 30 of 38

6) Attempt any four of the following Marks 16

a) How to check how many fonts are available in the computer system 4

Explain with example

(Explanation -2 Marks Example-2 Marks)

Ans When working with fonts often you need to know which fonts are available on your machine To

ontain this information you can use the getAvailableFontFamilyNames() method defined by the

GraphicsEnvironment classIt is shown here

String[ ] getAvailableFontFamilyNames( )

This method returns an array of string that contains the names of the available font families

Since this methods is members of GraphicsEnvironment you need a GraphicsEnvironment

reference to call itYou can obtain this reference by using the getlocalGrahicsEnvironmet() static

method which is derfined by GraphicsEnvironmentIt is shown here

static GraphicsEnvironment getLocalGraphicsEnvironment( )

Here is an applet that shown how to obtain the names of the available font families

ltapplet code=rdquoAllFontsrdquo width=500 height=100gt

ltappletgt

import javaapplet

import javaawt

public class AllFonts extends Applet

public void paint(Graphics g)

string fonts= ldquo rdquo

stirng allFontsList[]

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 31 of 38

GraphicsEnvironment t = GraphicsEnvironmentgetLocalGraphicsEnvironment()

allFontList = tgetAvailableFontFamilyNames()

for(int i= 0 ilt allFontsListlength i++)

fonts= fonts + allFontList[i] + ldquo rdquo

gdrawString(msg416)

b) Explain following check box class methods with appropriate example 4

i) Void setLable (String str) ii) Boolean getState ( )

(Explanation of each method-1 Marks Example-2 Marks)

Ans

i) void setLable(String str)

This method is used to set the label of check box

ii) Boolean getState()

This method is used to retrieve the current state of a check box It returns the value either true or

false depends on check box is selected or not

Example

Demonstrate check boxes

import javaawt

import javaawtevent

import javaapplet

ltapplet code=CheckboxDemo width=250 height=200gt

ltappletgt

public class CheckboxDemo extends Applet implements ItemListener

String msg =

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 32 of 38

Checkbox winXP winVista solaris mac

public void init()

winXP = new Checkbox(Windows XP null true)

mac = new Checkbox()

macsetLable(ldquoMac OSrdquo)

add(winXP)

add(mac)

winXPaddItemListener(this)

macaddItemListener(this)

public void itemStateChanged(ItemEvent ie)

repaint()

Display current state of the check boxes

public void paint(Graphics g)

msg = Current state

gdrawString(msg 6 80)

msg = Windows XP + winXPgetState()

gdrawString(msg 6 100)

msg = Mac OS + macgetState()

gdrawString(msg 6 120)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 33 of 38

c) Explain the techniques of session tracking management

(Any four techniques with explanation- 1 Mark each)

Ans Session tracking Techniques

1 User Authorization

Users can be authorized to use the web application in different ways Basic concept is that the

user will provide username and password to login to the application Based on that the user can

be identified and the session can be maintained

2 Hidden Fields

ltINPUT TYPE=rdquohiddenrdquo NAME=rdquotechnologyrdquo VALUE=rdquoservletrdquogt

Hidden fields like the above can be inserted in the webpages and information can be sent to the

server for session tracking These fields are not visible directly to the user but can be viewed

using view source option from the browsers This type doesnrsquot need any special configuration

from the browser of server and by default available to use for session tracking This cannot be

used for session tracking when the conversation included static resources lik html pages

3 URL Rewriting

Original URL httpserverportservletServletName

ewritten URL httpserverportservletServletNamesessionid=7456

When a request is made additional parameter is appended with the url In general added

additional parameter will be sessionid or sometimes the userid It will suffice to track the

session This type of session tracking doesnrsquot need any special support from the browser

Disadvantage is implementing this type of session tracking is tedious We need to keep track of

the parameter as a chain link until the conversation completes and also should make sure that

the parameter doesnrsquot clash with other application parameters

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 34 of 38

4 Cookies

Cookies are the mostly used technology for session tracking Cookie is a key value pair of

information sent by the server to the browser This should be saved by the browser in its space

in the client computer Whenever the browser sends a request to that server it sends the cookie

along with it Then the server can identify the client using the cookie

In java following is the source code snippet to create a cookie

Cookie cookie = new Cookie (ldquouserIDrdquo ldquo7456Prime)

resaddCookie(cookie)

5 Session tracking API

Session tracking API is built on top of the first four methods This is inorder to help the

developer to minimize the overhead of session tracking This type of session tracking is

provided by the underlying technology Lets take the java servlet example Then the servlet

container manages the session tracking task and the user need not do it explicitly using the java

servlets This is the best of all methods because all the management and errors related to

session tracking will be taken care of by the container itself

d) Give sequential steps for JTree in swing with example

(Steps- 2 Marks any small Example- 2 Marks)

Ans Steps for JTree

Atree is a component that presents a hierarchical view of data The user has the ability to

expand or collapse individual subtrees in this display Trees are implemented in Swing by

the JTree class

Here are the steps to follow to use a tree

1 Create an instance of JTree

2 Create a JScrollPane and specify the tree as the object to be scrolled

3 Add the tree to the scroll pane

4 Add the scroll pane to the content pane

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 35 of 38

Example

Demonstrate JTree

import javaawt

import javaxswingevent

import javaxswing

import javaxswingtree

ltapplet code=JTreeDemo width=400 height=200gt

ltappletgt

public class JTreeDemo extends JApplet

JTree tree

JLabel jlab

public void init()

try

SwingUtilitiesinvokeAndWait(

new Runnable()

public void run()

makeGUI()

)

catch (Exception exc)

Systemoutprintln(Cant create because of + exc)

private void makeGUI()

Create top node of tree

DefaultMutableTreeNode top = new DefaultMutableTreeNode(Options)

Create subtree of A

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 36 of 38

DefaultMutableTreeNode a = new DefaultMutableTreeNode(A)

topadd(a)

DefaultMutableTreeNode a1 = new DefaultMutableTreeNode(A1)

aadd(a1)

DefaultMutableTreeNode a2 = new DefaultMutableTreeNode(A2)

aadd(a2)

Create subtree of B

DefaultMutableTreeNode b = new DefaultMutableTreeNode(B)

topadd(b)

DefaultMutableTreeNode b1 = new DefaultMutableTreeNode(B1)

badd(b1)

DefaultMutableTreeNode b2 = new DefaultMutableTreeNode(B2)

badd(b2)

DefaultMutableTreeNode b3 = new DefaultMutableTreeNode(B3)

badd(b3)

Create the tree

tree = new JTree(top)

Add the tree to a scroll pane

JScrollPane jsp = new JScrollPane(tree)

Add the scroll pane to the content pane

add(jsp)

Add the label to the content pane

jlab = new JLabel()

add(jlab BorderLayoutSOUTH)

Handle tree selection events

treeaddTreeSelectionListener(new TreeSelectionListener()

public void valueChanged(TreeSelectionEvent tse)

jlabsetText(Selection is + tsegetPath())

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 37 of 38

e) Draw and explain the life cycle of servlet

(Explanation ndash 3 Marks Diagram -1 Marks)

Ans Three methods are central to the life cycle of a servlet

These are init( ) service( ) and destroy( )

They are implemented by every servlet and are invoked at specific times by the server Let

us consider a typical user scenario to understand when these methods are called

First assume that a user enters a Uniform Resource Locator (URL) to a web browser

The browser then generates an HTTP request for this URL This request is then sent to the

appropriate server

Second this HTTP request is received by the web server The server maps this request to

a particular servlet The servlet is dynamically retrieved and loaded into the address space

of the server

Third the server invokes the init( ) method of the servlet This method is invoked only

when the servlet is first loaded into memory It is possible to pass initialization parameters

to the servlet so it may configure itself

Fourth the server invokes the service( ) method of the servlet This method is called to

process the HTTP request You will see that it is possible for the servlet to read data that has

been provided in the HTTP request It may also formulate an HTTP response for the client

The servlet remains in the serverrsquos address space and is available to process any other

HTTP requests received from clients The service( ) method is called for each HTTP request

Finally the server may decide to unload the servlet from its memory The algorithms by

which this determination is made are specific to each server The server calls the destroy( )

method to relinquish any resources such as file handles that are allocated for the servlet

Important data may be saved to a persistent store The memory allocated for the servlet and

its objects can then be garbage collected

A servlet life cycle can be defined as the entire process from its creation till the destruction The

following are the paths followed by a servlet

The servlet is initialized by calling the init () method

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 38 of 38

The servlet calls service() method to process a clients request

The servlet is terminated by calling the destroy() method

Finally servlet is garbage collected by the garbage collector of the JVM

Initialization

(Load Resources)

Services

(Accept Requests)

Destruction

(Unload Resources)

Servlet

Request

Response

Page 23: AJP

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 23 of 38

b) Write servlet which shows how many times user has visited the page in session

(Any Correct Logic ndash4 Marks Syntax ndash 2 Marks)

Ans import javaio

import javaxservlet

import javaxservlethttp

public class Session Travker extends HttpServlet

public void doGet(HttpServletRequest req HttpServletResponse res) throws ServletException

IOException

ressetContentType(ldquotexthtmlrdquo)

PrintWriter out = resgetWriter()

HttpSession session = reqgetSession(true)

Integer count= (Integer)sessiongetValue(ldquotrackercountrdquo)

if(count== null) count=new Interger(1)

else count = new Interger(count intValue() +1)

sessionputValue(ldquotrackercountrdquocount)

outprintln(ldquoltHTMLgtltHEADgtltTITLEgtSession TrackerltTITLEgtltHEADgtrdquo)

outprintln(ldquoltBODYgtltH1gtSession Tracking DemoltH1gtrdquo)

outprintln(ldquoYou have visited this pagerdquo +count +((countintValue() == 1)rdquotimerdquo

ldquotimesrdquo))outprinln(ltPgtrdquo)

outprintln(ldquoltH2gtSesssion dataltH2gtrdquo)

String[] names = sessiongetValueNames()

for(int i=0 ilt nameslength i++)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 24 of 38

outprintln(names[i] + ldquo rdquo + sessiongetvalue(names[i])+ ldquoltBRgtrdquo)

outprintln(ldquoltBODYgtltHTMLgtrdquo)

5 Attempt any two of the following Marks 16

a) Write a program to display all records from Employee table from database using

JDBC

(Assume suitable data for table- Load driver create connection execute Query - 1 Mark

each Display data- 3 Marks Syntax ndash 2 Marks)

Ans import javasql

import javasqlStatement

import javaapplet

import javaawt

public class DisplayTable

public static void main( String args[])

RsultSet rs

Connection conn

try

String s1

ClassforName(sun jdbcodbcJdbcOdbcDriver)

Systemoutprintln(Connecting to a selected database)

String url=rdquojdbcodbcabcrdquo

conn = DriverManagergetConnection(DB_URL USER PASS)

Systemoutprintln(Connected database successfully)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 25 of 38

Systemoutprintln(Creating statement)

stmt = conncreateStatement()

sql = SELECT FROM Employee

ResultSet rs = stmtexecuteQuery(sql)

Tables fields assumed are id first last age

while(rsnext())

int id = rsgetInt(id)

int age = rsgetInt(age)

String first = rsgetString(first)

String last = rsgetString(last)

Systemoutprint(ID + id)

Systemoutprint( Age + age)

Systemoutprint( First + first)

Systemoutprintln( Last + last)

rsclose()

catch(SQLException se)

Handle errors for JDBC

seprintStackTrace()

catch(Exception e)

Handle errors for ClassforName

eprintStackTrace()

finally

finally block used to close resources

try

if(stmt=null)

connclose()

catch(SQLException se)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 26 of 38

b) Define the term

i) Reserved socket ii) proxy server

iii) Datagram iv) URL connection 4

(Each term- 2 Marks)

Ans i) Reserved socket

A socket is one end-point of a two-way communication link between two programs running on

the network Socket classes are used to represent the connection between a client program and a

server program

Reserved socket The socket which are reserved for specific protocols for communication

purpose are known as reseved sockets

TCPIP uses or reserves the lower 1024 ports for specific protocols

Example port number 23 is for Telnet 25 is for smtp 21 is for ftp 13 for daytime 110 for pop3

and so on Protocol decides how a client should interact with the port

ii) Proxy server

A proxy server is a computer that offers a computer network service to allow clients to make

indirect network connections to other network services A client connects to the proxy server

then requests a connection file or other resource available on a different server The proxy

provides the resource either by connecting to the specified server or by serving it from a cache In

some cases the proxy may alter the clients request or the servers response for various purposes

Purposes of the proxy servers

To keep machines behind it anonymous mainly for security

To speed up access to resources (using caching) Web proxies are commonly used to

cache web pages from a web server

To prevent downloading the same content multiple times (and save bandwidth)

To log audit usage eg to provide company employee Internet usage reporting

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 27 of 38

To scan transmitted content for malware before delivery

To scan outbound content eg for data loss prevention

iii) Datagram

Datagrams are bundles of information passed between machines They are somewhat like a hard

throw from a well-trained but blindfolded catcher to the third baseman Once the datagram has

been released to its intended target there is no assurance that it will arrive or even that

someone will be there to catch it Likewise when the datagram is received there is no

assurance that it hasnrsquot been damaged in transit or that whoever sent it is still there to receive a

response

Java implements datagrams on top of the UDP protocol by using two classes

The DatagramPacket object is the data container while the DatagramSocket is the mechanism

used to send or receive the DatagramPackets

iv) URL connection

URLConnection is a general-purpose class for accessing the attributes of a remote resource

Once you make a connection to a remote server you can use URLConnection to inspect the

Properties of the remote object before actually transporting it locally These attributes are

exposed by the HTTP protocol specification and as such only make sense for URL objects

that are using the HTTP protocol

URLConnection defines several methods

int getContentLength( )

String getContentType( )

long getDate( )

long getExpiration( )

String getHeaderField(int idx)

long getLastModified( )

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 28 of 38

c) Write a program to display three text fields and a button below to all an Applet Insert

the integer valuer from three text fields After pressing the button the background colour

of applet will be changed as per the RGB combination of the values given in the text field

(Correct logic - 6 Marks Syntax - 2 Marks)

4

Ans import javaawt

import javaawtevent

import javaapplet

ltapplet code=rdquoClrclassrdquo width=250 heigth=250gtltappletgt

public class Clrextends Applet implements ActionListener

int r g b

TextField t1t2t3

Button b1

Color c1

public void init()

t1= new TextField(5)

t2= new TextField(8)

t3= new TextField(11)

b1 = new Button(ldquo Set Colorrdquo)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 29 of 38

add(t1)

add(t2)

add(t3)

add(b1)

b1addActionListener(this)

public void void paint( )

setBackground(c1)

public void actionPerformed(ActionEvent ae)

r=IntegerparseInt(t1getText())

g=IntegerparseInt(t2getText())

b=IntegerparseInt(t3getText())

c1= new Color(rgb)

repaint()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 30 of 38

6) Attempt any four of the following Marks 16

a) How to check how many fonts are available in the computer system 4

Explain with example

(Explanation -2 Marks Example-2 Marks)

Ans When working with fonts often you need to know which fonts are available on your machine To

ontain this information you can use the getAvailableFontFamilyNames() method defined by the

GraphicsEnvironment classIt is shown here

String[ ] getAvailableFontFamilyNames( )

This method returns an array of string that contains the names of the available font families

Since this methods is members of GraphicsEnvironment you need a GraphicsEnvironment

reference to call itYou can obtain this reference by using the getlocalGrahicsEnvironmet() static

method which is derfined by GraphicsEnvironmentIt is shown here

static GraphicsEnvironment getLocalGraphicsEnvironment( )

Here is an applet that shown how to obtain the names of the available font families

ltapplet code=rdquoAllFontsrdquo width=500 height=100gt

ltappletgt

import javaapplet

import javaawt

public class AllFonts extends Applet

public void paint(Graphics g)

string fonts= ldquo rdquo

stirng allFontsList[]

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 31 of 38

GraphicsEnvironment t = GraphicsEnvironmentgetLocalGraphicsEnvironment()

allFontList = tgetAvailableFontFamilyNames()

for(int i= 0 ilt allFontsListlength i++)

fonts= fonts + allFontList[i] + ldquo rdquo

gdrawString(msg416)

b) Explain following check box class methods with appropriate example 4

i) Void setLable (String str) ii) Boolean getState ( )

(Explanation of each method-1 Marks Example-2 Marks)

Ans

i) void setLable(String str)

This method is used to set the label of check box

ii) Boolean getState()

This method is used to retrieve the current state of a check box It returns the value either true or

false depends on check box is selected or not

Example

Demonstrate check boxes

import javaawt

import javaawtevent

import javaapplet

ltapplet code=CheckboxDemo width=250 height=200gt

ltappletgt

public class CheckboxDemo extends Applet implements ItemListener

String msg =

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 32 of 38

Checkbox winXP winVista solaris mac

public void init()

winXP = new Checkbox(Windows XP null true)

mac = new Checkbox()

macsetLable(ldquoMac OSrdquo)

add(winXP)

add(mac)

winXPaddItemListener(this)

macaddItemListener(this)

public void itemStateChanged(ItemEvent ie)

repaint()

Display current state of the check boxes

public void paint(Graphics g)

msg = Current state

gdrawString(msg 6 80)

msg = Windows XP + winXPgetState()

gdrawString(msg 6 100)

msg = Mac OS + macgetState()

gdrawString(msg 6 120)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 33 of 38

c) Explain the techniques of session tracking management

(Any four techniques with explanation- 1 Mark each)

Ans Session tracking Techniques

1 User Authorization

Users can be authorized to use the web application in different ways Basic concept is that the

user will provide username and password to login to the application Based on that the user can

be identified and the session can be maintained

2 Hidden Fields

ltINPUT TYPE=rdquohiddenrdquo NAME=rdquotechnologyrdquo VALUE=rdquoservletrdquogt

Hidden fields like the above can be inserted in the webpages and information can be sent to the

server for session tracking These fields are not visible directly to the user but can be viewed

using view source option from the browsers This type doesnrsquot need any special configuration

from the browser of server and by default available to use for session tracking This cannot be

used for session tracking when the conversation included static resources lik html pages

3 URL Rewriting

Original URL httpserverportservletServletName

ewritten URL httpserverportservletServletNamesessionid=7456

When a request is made additional parameter is appended with the url In general added

additional parameter will be sessionid or sometimes the userid It will suffice to track the

session This type of session tracking doesnrsquot need any special support from the browser

Disadvantage is implementing this type of session tracking is tedious We need to keep track of

the parameter as a chain link until the conversation completes and also should make sure that

the parameter doesnrsquot clash with other application parameters

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 34 of 38

4 Cookies

Cookies are the mostly used technology for session tracking Cookie is a key value pair of

information sent by the server to the browser This should be saved by the browser in its space

in the client computer Whenever the browser sends a request to that server it sends the cookie

along with it Then the server can identify the client using the cookie

In java following is the source code snippet to create a cookie

Cookie cookie = new Cookie (ldquouserIDrdquo ldquo7456Prime)

resaddCookie(cookie)

5 Session tracking API

Session tracking API is built on top of the first four methods This is inorder to help the

developer to minimize the overhead of session tracking This type of session tracking is

provided by the underlying technology Lets take the java servlet example Then the servlet

container manages the session tracking task and the user need not do it explicitly using the java

servlets This is the best of all methods because all the management and errors related to

session tracking will be taken care of by the container itself

d) Give sequential steps for JTree in swing with example

(Steps- 2 Marks any small Example- 2 Marks)

Ans Steps for JTree

Atree is a component that presents a hierarchical view of data The user has the ability to

expand or collapse individual subtrees in this display Trees are implemented in Swing by

the JTree class

Here are the steps to follow to use a tree

1 Create an instance of JTree

2 Create a JScrollPane and specify the tree as the object to be scrolled

3 Add the tree to the scroll pane

4 Add the scroll pane to the content pane

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 35 of 38

Example

Demonstrate JTree

import javaawt

import javaxswingevent

import javaxswing

import javaxswingtree

ltapplet code=JTreeDemo width=400 height=200gt

ltappletgt

public class JTreeDemo extends JApplet

JTree tree

JLabel jlab

public void init()

try

SwingUtilitiesinvokeAndWait(

new Runnable()

public void run()

makeGUI()

)

catch (Exception exc)

Systemoutprintln(Cant create because of + exc)

private void makeGUI()

Create top node of tree

DefaultMutableTreeNode top = new DefaultMutableTreeNode(Options)

Create subtree of A

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 36 of 38

DefaultMutableTreeNode a = new DefaultMutableTreeNode(A)

topadd(a)

DefaultMutableTreeNode a1 = new DefaultMutableTreeNode(A1)

aadd(a1)

DefaultMutableTreeNode a2 = new DefaultMutableTreeNode(A2)

aadd(a2)

Create subtree of B

DefaultMutableTreeNode b = new DefaultMutableTreeNode(B)

topadd(b)

DefaultMutableTreeNode b1 = new DefaultMutableTreeNode(B1)

badd(b1)

DefaultMutableTreeNode b2 = new DefaultMutableTreeNode(B2)

badd(b2)

DefaultMutableTreeNode b3 = new DefaultMutableTreeNode(B3)

badd(b3)

Create the tree

tree = new JTree(top)

Add the tree to a scroll pane

JScrollPane jsp = new JScrollPane(tree)

Add the scroll pane to the content pane

add(jsp)

Add the label to the content pane

jlab = new JLabel()

add(jlab BorderLayoutSOUTH)

Handle tree selection events

treeaddTreeSelectionListener(new TreeSelectionListener()

public void valueChanged(TreeSelectionEvent tse)

jlabsetText(Selection is + tsegetPath())

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 37 of 38

e) Draw and explain the life cycle of servlet

(Explanation ndash 3 Marks Diagram -1 Marks)

Ans Three methods are central to the life cycle of a servlet

These are init( ) service( ) and destroy( )

They are implemented by every servlet and are invoked at specific times by the server Let

us consider a typical user scenario to understand when these methods are called

First assume that a user enters a Uniform Resource Locator (URL) to a web browser

The browser then generates an HTTP request for this URL This request is then sent to the

appropriate server

Second this HTTP request is received by the web server The server maps this request to

a particular servlet The servlet is dynamically retrieved and loaded into the address space

of the server

Third the server invokes the init( ) method of the servlet This method is invoked only

when the servlet is first loaded into memory It is possible to pass initialization parameters

to the servlet so it may configure itself

Fourth the server invokes the service( ) method of the servlet This method is called to

process the HTTP request You will see that it is possible for the servlet to read data that has

been provided in the HTTP request It may also formulate an HTTP response for the client

The servlet remains in the serverrsquos address space and is available to process any other

HTTP requests received from clients The service( ) method is called for each HTTP request

Finally the server may decide to unload the servlet from its memory The algorithms by

which this determination is made are specific to each server The server calls the destroy( )

method to relinquish any resources such as file handles that are allocated for the servlet

Important data may be saved to a persistent store The memory allocated for the servlet and

its objects can then be garbage collected

A servlet life cycle can be defined as the entire process from its creation till the destruction The

following are the paths followed by a servlet

The servlet is initialized by calling the init () method

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 38 of 38

The servlet calls service() method to process a clients request

The servlet is terminated by calling the destroy() method

Finally servlet is garbage collected by the garbage collector of the JVM

Initialization

(Load Resources)

Services

(Accept Requests)

Destruction

(Unload Resources)

Servlet

Request

Response

Page 24: AJP

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 24 of 38

outprintln(names[i] + ldquo rdquo + sessiongetvalue(names[i])+ ldquoltBRgtrdquo)

outprintln(ldquoltBODYgtltHTMLgtrdquo)

5 Attempt any two of the following Marks 16

a) Write a program to display all records from Employee table from database using

JDBC

(Assume suitable data for table- Load driver create connection execute Query - 1 Mark

each Display data- 3 Marks Syntax ndash 2 Marks)

Ans import javasql

import javasqlStatement

import javaapplet

import javaawt

public class DisplayTable

public static void main( String args[])

RsultSet rs

Connection conn

try

String s1

ClassforName(sun jdbcodbcJdbcOdbcDriver)

Systemoutprintln(Connecting to a selected database)

String url=rdquojdbcodbcabcrdquo

conn = DriverManagergetConnection(DB_URL USER PASS)

Systemoutprintln(Connected database successfully)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 25 of 38

Systemoutprintln(Creating statement)

stmt = conncreateStatement()

sql = SELECT FROM Employee

ResultSet rs = stmtexecuteQuery(sql)

Tables fields assumed are id first last age

while(rsnext())

int id = rsgetInt(id)

int age = rsgetInt(age)

String first = rsgetString(first)

String last = rsgetString(last)

Systemoutprint(ID + id)

Systemoutprint( Age + age)

Systemoutprint( First + first)

Systemoutprintln( Last + last)

rsclose()

catch(SQLException se)

Handle errors for JDBC

seprintStackTrace()

catch(Exception e)

Handle errors for ClassforName

eprintStackTrace()

finally

finally block used to close resources

try

if(stmt=null)

connclose()

catch(SQLException se)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 26 of 38

b) Define the term

i) Reserved socket ii) proxy server

iii) Datagram iv) URL connection 4

(Each term- 2 Marks)

Ans i) Reserved socket

A socket is one end-point of a two-way communication link between two programs running on

the network Socket classes are used to represent the connection between a client program and a

server program

Reserved socket The socket which are reserved for specific protocols for communication

purpose are known as reseved sockets

TCPIP uses or reserves the lower 1024 ports for specific protocols

Example port number 23 is for Telnet 25 is for smtp 21 is for ftp 13 for daytime 110 for pop3

and so on Protocol decides how a client should interact with the port

ii) Proxy server

A proxy server is a computer that offers a computer network service to allow clients to make

indirect network connections to other network services A client connects to the proxy server

then requests a connection file or other resource available on a different server The proxy

provides the resource either by connecting to the specified server or by serving it from a cache In

some cases the proxy may alter the clients request or the servers response for various purposes

Purposes of the proxy servers

To keep machines behind it anonymous mainly for security

To speed up access to resources (using caching) Web proxies are commonly used to

cache web pages from a web server

To prevent downloading the same content multiple times (and save bandwidth)

To log audit usage eg to provide company employee Internet usage reporting

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 27 of 38

To scan transmitted content for malware before delivery

To scan outbound content eg for data loss prevention

iii) Datagram

Datagrams are bundles of information passed between machines They are somewhat like a hard

throw from a well-trained but blindfolded catcher to the third baseman Once the datagram has

been released to its intended target there is no assurance that it will arrive or even that

someone will be there to catch it Likewise when the datagram is received there is no

assurance that it hasnrsquot been damaged in transit or that whoever sent it is still there to receive a

response

Java implements datagrams on top of the UDP protocol by using two classes

The DatagramPacket object is the data container while the DatagramSocket is the mechanism

used to send or receive the DatagramPackets

iv) URL connection

URLConnection is a general-purpose class for accessing the attributes of a remote resource

Once you make a connection to a remote server you can use URLConnection to inspect the

Properties of the remote object before actually transporting it locally These attributes are

exposed by the HTTP protocol specification and as such only make sense for URL objects

that are using the HTTP protocol

URLConnection defines several methods

int getContentLength( )

String getContentType( )

long getDate( )

long getExpiration( )

String getHeaderField(int idx)

long getLastModified( )

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 28 of 38

c) Write a program to display three text fields and a button below to all an Applet Insert

the integer valuer from three text fields After pressing the button the background colour

of applet will be changed as per the RGB combination of the values given in the text field

(Correct logic - 6 Marks Syntax - 2 Marks)

4

Ans import javaawt

import javaawtevent

import javaapplet

ltapplet code=rdquoClrclassrdquo width=250 heigth=250gtltappletgt

public class Clrextends Applet implements ActionListener

int r g b

TextField t1t2t3

Button b1

Color c1

public void init()

t1= new TextField(5)

t2= new TextField(8)

t3= new TextField(11)

b1 = new Button(ldquo Set Colorrdquo)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 29 of 38

add(t1)

add(t2)

add(t3)

add(b1)

b1addActionListener(this)

public void void paint( )

setBackground(c1)

public void actionPerformed(ActionEvent ae)

r=IntegerparseInt(t1getText())

g=IntegerparseInt(t2getText())

b=IntegerparseInt(t3getText())

c1= new Color(rgb)

repaint()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 30 of 38

6) Attempt any four of the following Marks 16

a) How to check how many fonts are available in the computer system 4

Explain with example

(Explanation -2 Marks Example-2 Marks)

Ans When working with fonts often you need to know which fonts are available on your machine To

ontain this information you can use the getAvailableFontFamilyNames() method defined by the

GraphicsEnvironment classIt is shown here

String[ ] getAvailableFontFamilyNames( )

This method returns an array of string that contains the names of the available font families

Since this methods is members of GraphicsEnvironment you need a GraphicsEnvironment

reference to call itYou can obtain this reference by using the getlocalGrahicsEnvironmet() static

method which is derfined by GraphicsEnvironmentIt is shown here

static GraphicsEnvironment getLocalGraphicsEnvironment( )

Here is an applet that shown how to obtain the names of the available font families

ltapplet code=rdquoAllFontsrdquo width=500 height=100gt

ltappletgt

import javaapplet

import javaawt

public class AllFonts extends Applet

public void paint(Graphics g)

string fonts= ldquo rdquo

stirng allFontsList[]

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 31 of 38

GraphicsEnvironment t = GraphicsEnvironmentgetLocalGraphicsEnvironment()

allFontList = tgetAvailableFontFamilyNames()

for(int i= 0 ilt allFontsListlength i++)

fonts= fonts + allFontList[i] + ldquo rdquo

gdrawString(msg416)

b) Explain following check box class methods with appropriate example 4

i) Void setLable (String str) ii) Boolean getState ( )

(Explanation of each method-1 Marks Example-2 Marks)

Ans

i) void setLable(String str)

This method is used to set the label of check box

ii) Boolean getState()

This method is used to retrieve the current state of a check box It returns the value either true or

false depends on check box is selected or not

Example

Demonstrate check boxes

import javaawt

import javaawtevent

import javaapplet

ltapplet code=CheckboxDemo width=250 height=200gt

ltappletgt

public class CheckboxDemo extends Applet implements ItemListener

String msg =

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 32 of 38

Checkbox winXP winVista solaris mac

public void init()

winXP = new Checkbox(Windows XP null true)

mac = new Checkbox()

macsetLable(ldquoMac OSrdquo)

add(winXP)

add(mac)

winXPaddItemListener(this)

macaddItemListener(this)

public void itemStateChanged(ItemEvent ie)

repaint()

Display current state of the check boxes

public void paint(Graphics g)

msg = Current state

gdrawString(msg 6 80)

msg = Windows XP + winXPgetState()

gdrawString(msg 6 100)

msg = Mac OS + macgetState()

gdrawString(msg 6 120)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 33 of 38

c) Explain the techniques of session tracking management

(Any four techniques with explanation- 1 Mark each)

Ans Session tracking Techniques

1 User Authorization

Users can be authorized to use the web application in different ways Basic concept is that the

user will provide username and password to login to the application Based on that the user can

be identified and the session can be maintained

2 Hidden Fields

ltINPUT TYPE=rdquohiddenrdquo NAME=rdquotechnologyrdquo VALUE=rdquoservletrdquogt

Hidden fields like the above can be inserted in the webpages and information can be sent to the

server for session tracking These fields are not visible directly to the user but can be viewed

using view source option from the browsers This type doesnrsquot need any special configuration

from the browser of server and by default available to use for session tracking This cannot be

used for session tracking when the conversation included static resources lik html pages

3 URL Rewriting

Original URL httpserverportservletServletName

ewritten URL httpserverportservletServletNamesessionid=7456

When a request is made additional parameter is appended with the url In general added

additional parameter will be sessionid or sometimes the userid It will suffice to track the

session This type of session tracking doesnrsquot need any special support from the browser

Disadvantage is implementing this type of session tracking is tedious We need to keep track of

the parameter as a chain link until the conversation completes and also should make sure that

the parameter doesnrsquot clash with other application parameters

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 34 of 38

4 Cookies

Cookies are the mostly used technology for session tracking Cookie is a key value pair of

information sent by the server to the browser This should be saved by the browser in its space

in the client computer Whenever the browser sends a request to that server it sends the cookie

along with it Then the server can identify the client using the cookie

In java following is the source code snippet to create a cookie

Cookie cookie = new Cookie (ldquouserIDrdquo ldquo7456Prime)

resaddCookie(cookie)

5 Session tracking API

Session tracking API is built on top of the first four methods This is inorder to help the

developer to minimize the overhead of session tracking This type of session tracking is

provided by the underlying technology Lets take the java servlet example Then the servlet

container manages the session tracking task and the user need not do it explicitly using the java

servlets This is the best of all methods because all the management and errors related to

session tracking will be taken care of by the container itself

d) Give sequential steps for JTree in swing with example

(Steps- 2 Marks any small Example- 2 Marks)

Ans Steps for JTree

Atree is a component that presents a hierarchical view of data The user has the ability to

expand or collapse individual subtrees in this display Trees are implemented in Swing by

the JTree class

Here are the steps to follow to use a tree

1 Create an instance of JTree

2 Create a JScrollPane and specify the tree as the object to be scrolled

3 Add the tree to the scroll pane

4 Add the scroll pane to the content pane

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 35 of 38

Example

Demonstrate JTree

import javaawt

import javaxswingevent

import javaxswing

import javaxswingtree

ltapplet code=JTreeDemo width=400 height=200gt

ltappletgt

public class JTreeDemo extends JApplet

JTree tree

JLabel jlab

public void init()

try

SwingUtilitiesinvokeAndWait(

new Runnable()

public void run()

makeGUI()

)

catch (Exception exc)

Systemoutprintln(Cant create because of + exc)

private void makeGUI()

Create top node of tree

DefaultMutableTreeNode top = new DefaultMutableTreeNode(Options)

Create subtree of A

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 36 of 38

DefaultMutableTreeNode a = new DefaultMutableTreeNode(A)

topadd(a)

DefaultMutableTreeNode a1 = new DefaultMutableTreeNode(A1)

aadd(a1)

DefaultMutableTreeNode a2 = new DefaultMutableTreeNode(A2)

aadd(a2)

Create subtree of B

DefaultMutableTreeNode b = new DefaultMutableTreeNode(B)

topadd(b)

DefaultMutableTreeNode b1 = new DefaultMutableTreeNode(B1)

badd(b1)

DefaultMutableTreeNode b2 = new DefaultMutableTreeNode(B2)

badd(b2)

DefaultMutableTreeNode b3 = new DefaultMutableTreeNode(B3)

badd(b3)

Create the tree

tree = new JTree(top)

Add the tree to a scroll pane

JScrollPane jsp = new JScrollPane(tree)

Add the scroll pane to the content pane

add(jsp)

Add the label to the content pane

jlab = new JLabel()

add(jlab BorderLayoutSOUTH)

Handle tree selection events

treeaddTreeSelectionListener(new TreeSelectionListener()

public void valueChanged(TreeSelectionEvent tse)

jlabsetText(Selection is + tsegetPath())

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 37 of 38

e) Draw and explain the life cycle of servlet

(Explanation ndash 3 Marks Diagram -1 Marks)

Ans Three methods are central to the life cycle of a servlet

These are init( ) service( ) and destroy( )

They are implemented by every servlet and are invoked at specific times by the server Let

us consider a typical user scenario to understand when these methods are called

First assume that a user enters a Uniform Resource Locator (URL) to a web browser

The browser then generates an HTTP request for this URL This request is then sent to the

appropriate server

Second this HTTP request is received by the web server The server maps this request to

a particular servlet The servlet is dynamically retrieved and loaded into the address space

of the server

Third the server invokes the init( ) method of the servlet This method is invoked only

when the servlet is first loaded into memory It is possible to pass initialization parameters

to the servlet so it may configure itself

Fourth the server invokes the service( ) method of the servlet This method is called to

process the HTTP request You will see that it is possible for the servlet to read data that has

been provided in the HTTP request It may also formulate an HTTP response for the client

The servlet remains in the serverrsquos address space and is available to process any other

HTTP requests received from clients The service( ) method is called for each HTTP request

Finally the server may decide to unload the servlet from its memory The algorithms by

which this determination is made are specific to each server The server calls the destroy( )

method to relinquish any resources such as file handles that are allocated for the servlet

Important data may be saved to a persistent store The memory allocated for the servlet and

its objects can then be garbage collected

A servlet life cycle can be defined as the entire process from its creation till the destruction The

following are the paths followed by a servlet

The servlet is initialized by calling the init () method

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 38 of 38

The servlet calls service() method to process a clients request

The servlet is terminated by calling the destroy() method

Finally servlet is garbage collected by the garbage collector of the JVM

Initialization

(Load Resources)

Services

(Accept Requests)

Destruction

(Unload Resources)

Servlet

Request

Response

Page 25: AJP

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 25 of 38

Systemoutprintln(Creating statement)

stmt = conncreateStatement()

sql = SELECT FROM Employee

ResultSet rs = stmtexecuteQuery(sql)

Tables fields assumed are id first last age

while(rsnext())

int id = rsgetInt(id)

int age = rsgetInt(age)

String first = rsgetString(first)

String last = rsgetString(last)

Systemoutprint(ID + id)

Systemoutprint( Age + age)

Systemoutprint( First + first)

Systemoutprintln( Last + last)

rsclose()

catch(SQLException se)

Handle errors for JDBC

seprintStackTrace()

catch(Exception e)

Handle errors for ClassforName

eprintStackTrace()

finally

finally block used to close resources

try

if(stmt=null)

connclose()

catch(SQLException se)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 26 of 38

b) Define the term

i) Reserved socket ii) proxy server

iii) Datagram iv) URL connection 4

(Each term- 2 Marks)

Ans i) Reserved socket

A socket is one end-point of a two-way communication link between two programs running on

the network Socket classes are used to represent the connection between a client program and a

server program

Reserved socket The socket which are reserved for specific protocols for communication

purpose are known as reseved sockets

TCPIP uses or reserves the lower 1024 ports for specific protocols

Example port number 23 is for Telnet 25 is for smtp 21 is for ftp 13 for daytime 110 for pop3

and so on Protocol decides how a client should interact with the port

ii) Proxy server

A proxy server is a computer that offers a computer network service to allow clients to make

indirect network connections to other network services A client connects to the proxy server

then requests a connection file or other resource available on a different server The proxy

provides the resource either by connecting to the specified server or by serving it from a cache In

some cases the proxy may alter the clients request or the servers response for various purposes

Purposes of the proxy servers

To keep machines behind it anonymous mainly for security

To speed up access to resources (using caching) Web proxies are commonly used to

cache web pages from a web server

To prevent downloading the same content multiple times (and save bandwidth)

To log audit usage eg to provide company employee Internet usage reporting

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 27 of 38

To scan transmitted content for malware before delivery

To scan outbound content eg for data loss prevention

iii) Datagram

Datagrams are bundles of information passed between machines They are somewhat like a hard

throw from a well-trained but blindfolded catcher to the third baseman Once the datagram has

been released to its intended target there is no assurance that it will arrive or even that

someone will be there to catch it Likewise when the datagram is received there is no

assurance that it hasnrsquot been damaged in transit or that whoever sent it is still there to receive a

response

Java implements datagrams on top of the UDP protocol by using two classes

The DatagramPacket object is the data container while the DatagramSocket is the mechanism

used to send or receive the DatagramPackets

iv) URL connection

URLConnection is a general-purpose class for accessing the attributes of a remote resource

Once you make a connection to a remote server you can use URLConnection to inspect the

Properties of the remote object before actually transporting it locally These attributes are

exposed by the HTTP protocol specification and as such only make sense for URL objects

that are using the HTTP protocol

URLConnection defines several methods

int getContentLength( )

String getContentType( )

long getDate( )

long getExpiration( )

String getHeaderField(int idx)

long getLastModified( )

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 28 of 38

c) Write a program to display three text fields and a button below to all an Applet Insert

the integer valuer from three text fields After pressing the button the background colour

of applet will be changed as per the RGB combination of the values given in the text field

(Correct logic - 6 Marks Syntax - 2 Marks)

4

Ans import javaawt

import javaawtevent

import javaapplet

ltapplet code=rdquoClrclassrdquo width=250 heigth=250gtltappletgt

public class Clrextends Applet implements ActionListener

int r g b

TextField t1t2t3

Button b1

Color c1

public void init()

t1= new TextField(5)

t2= new TextField(8)

t3= new TextField(11)

b1 = new Button(ldquo Set Colorrdquo)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 29 of 38

add(t1)

add(t2)

add(t3)

add(b1)

b1addActionListener(this)

public void void paint( )

setBackground(c1)

public void actionPerformed(ActionEvent ae)

r=IntegerparseInt(t1getText())

g=IntegerparseInt(t2getText())

b=IntegerparseInt(t3getText())

c1= new Color(rgb)

repaint()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 30 of 38

6) Attempt any four of the following Marks 16

a) How to check how many fonts are available in the computer system 4

Explain with example

(Explanation -2 Marks Example-2 Marks)

Ans When working with fonts often you need to know which fonts are available on your machine To

ontain this information you can use the getAvailableFontFamilyNames() method defined by the

GraphicsEnvironment classIt is shown here

String[ ] getAvailableFontFamilyNames( )

This method returns an array of string that contains the names of the available font families

Since this methods is members of GraphicsEnvironment you need a GraphicsEnvironment

reference to call itYou can obtain this reference by using the getlocalGrahicsEnvironmet() static

method which is derfined by GraphicsEnvironmentIt is shown here

static GraphicsEnvironment getLocalGraphicsEnvironment( )

Here is an applet that shown how to obtain the names of the available font families

ltapplet code=rdquoAllFontsrdquo width=500 height=100gt

ltappletgt

import javaapplet

import javaawt

public class AllFonts extends Applet

public void paint(Graphics g)

string fonts= ldquo rdquo

stirng allFontsList[]

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 31 of 38

GraphicsEnvironment t = GraphicsEnvironmentgetLocalGraphicsEnvironment()

allFontList = tgetAvailableFontFamilyNames()

for(int i= 0 ilt allFontsListlength i++)

fonts= fonts + allFontList[i] + ldquo rdquo

gdrawString(msg416)

b) Explain following check box class methods with appropriate example 4

i) Void setLable (String str) ii) Boolean getState ( )

(Explanation of each method-1 Marks Example-2 Marks)

Ans

i) void setLable(String str)

This method is used to set the label of check box

ii) Boolean getState()

This method is used to retrieve the current state of a check box It returns the value either true or

false depends on check box is selected or not

Example

Demonstrate check boxes

import javaawt

import javaawtevent

import javaapplet

ltapplet code=CheckboxDemo width=250 height=200gt

ltappletgt

public class CheckboxDemo extends Applet implements ItemListener

String msg =

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 32 of 38

Checkbox winXP winVista solaris mac

public void init()

winXP = new Checkbox(Windows XP null true)

mac = new Checkbox()

macsetLable(ldquoMac OSrdquo)

add(winXP)

add(mac)

winXPaddItemListener(this)

macaddItemListener(this)

public void itemStateChanged(ItemEvent ie)

repaint()

Display current state of the check boxes

public void paint(Graphics g)

msg = Current state

gdrawString(msg 6 80)

msg = Windows XP + winXPgetState()

gdrawString(msg 6 100)

msg = Mac OS + macgetState()

gdrawString(msg 6 120)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 33 of 38

c) Explain the techniques of session tracking management

(Any four techniques with explanation- 1 Mark each)

Ans Session tracking Techniques

1 User Authorization

Users can be authorized to use the web application in different ways Basic concept is that the

user will provide username and password to login to the application Based on that the user can

be identified and the session can be maintained

2 Hidden Fields

ltINPUT TYPE=rdquohiddenrdquo NAME=rdquotechnologyrdquo VALUE=rdquoservletrdquogt

Hidden fields like the above can be inserted in the webpages and information can be sent to the

server for session tracking These fields are not visible directly to the user but can be viewed

using view source option from the browsers This type doesnrsquot need any special configuration

from the browser of server and by default available to use for session tracking This cannot be

used for session tracking when the conversation included static resources lik html pages

3 URL Rewriting

Original URL httpserverportservletServletName

ewritten URL httpserverportservletServletNamesessionid=7456

When a request is made additional parameter is appended with the url In general added

additional parameter will be sessionid or sometimes the userid It will suffice to track the

session This type of session tracking doesnrsquot need any special support from the browser

Disadvantage is implementing this type of session tracking is tedious We need to keep track of

the parameter as a chain link until the conversation completes and also should make sure that

the parameter doesnrsquot clash with other application parameters

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 34 of 38

4 Cookies

Cookies are the mostly used technology for session tracking Cookie is a key value pair of

information sent by the server to the browser This should be saved by the browser in its space

in the client computer Whenever the browser sends a request to that server it sends the cookie

along with it Then the server can identify the client using the cookie

In java following is the source code snippet to create a cookie

Cookie cookie = new Cookie (ldquouserIDrdquo ldquo7456Prime)

resaddCookie(cookie)

5 Session tracking API

Session tracking API is built on top of the first four methods This is inorder to help the

developer to minimize the overhead of session tracking This type of session tracking is

provided by the underlying technology Lets take the java servlet example Then the servlet

container manages the session tracking task and the user need not do it explicitly using the java

servlets This is the best of all methods because all the management and errors related to

session tracking will be taken care of by the container itself

d) Give sequential steps for JTree in swing with example

(Steps- 2 Marks any small Example- 2 Marks)

Ans Steps for JTree

Atree is a component that presents a hierarchical view of data The user has the ability to

expand or collapse individual subtrees in this display Trees are implemented in Swing by

the JTree class

Here are the steps to follow to use a tree

1 Create an instance of JTree

2 Create a JScrollPane and specify the tree as the object to be scrolled

3 Add the tree to the scroll pane

4 Add the scroll pane to the content pane

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 35 of 38

Example

Demonstrate JTree

import javaawt

import javaxswingevent

import javaxswing

import javaxswingtree

ltapplet code=JTreeDemo width=400 height=200gt

ltappletgt

public class JTreeDemo extends JApplet

JTree tree

JLabel jlab

public void init()

try

SwingUtilitiesinvokeAndWait(

new Runnable()

public void run()

makeGUI()

)

catch (Exception exc)

Systemoutprintln(Cant create because of + exc)

private void makeGUI()

Create top node of tree

DefaultMutableTreeNode top = new DefaultMutableTreeNode(Options)

Create subtree of A

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 36 of 38

DefaultMutableTreeNode a = new DefaultMutableTreeNode(A)

topadd(a)

DefaultMutableTreeNode a1 = new DefaultMutableTreeNode(A1)

aadd(a1)

DefaultMutableTreeNode a2 = new DefaultMutableTreeNode(A2)

aadd(a2)

Create subtree of B

DefaultMutableTreeNode b = new DefaultMutableTreeNode(B)

topadd(b)

DefaultMutableTreeNode b1 = new DefaultMutableTreeNode(B1)

badd(b1)

DefaultMutableTreeNode b2 = new DefaultMutableTreeNode(B2)

badd(b2)

DefaultMutableTreeNode b3 = new DefaultMutableTreeNode(B3)

badd(b3)

Create the tree

tree = new JTree(top)

Add the tree to a scroll pane

JScrollPane jsp = new JScrollPane(tree)

Add the scroll pane to the content pane

add(jsp)

Add the label to the content pane

jlab = new JLabel()

add(jlab BorderLayoutSOUTH)

Handle tree selection events

treeaddTreeSelectionListener(new TreeSelectionListener()

public void valueChanged(TreeSelectionEvent tse)

jlabsetText(Selection is + tsegetPath())

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 37 of 38

e) Draw and explain the life cycle of servlet

(Explanation ndash 3 Marks Diagram -1 Marks)

Ans Three methods are central to the life cycle of a servlet

These are init( ) service( ) and destroy( )

They are implemented by every servlet and are invoked at specific times by the server Let

us consider a typical user scenario to understand when these methods are called

First assume that a user enters a Uniform Resource Locator (URL) to a web browser

The browser then generates an HTTP request for this URL This request is then sent to the

appropriate server

Second this HTTP request is received by the web server The server maps this request to

a particular servlet The servlet is dynamically retrieved and loaded into the address space

of the server

Third the server invokes the init( ) method of the servlet This method is invoked only

when the servlet is first loaded into memory It is possible to pass initialization parameters

to the servlet so it may configure itself

Fourth the server invokes the service( ) method of the servlet This method is called to

process the HTTP request You will see that it is possible for the servlet to read data that has

been provided in the HTTP request It may also formulate an HTTP response for the client

The servlet remains in the serverrsquos address space and is available to process any other

HTTP requests received from clients The service( ) method is called for each HTTP request

Finally the server may decide to unload the servlet from its memory The algorithms by

which this determination is made are specific to each server The server calls the destroy( )

method to relinquish any resources such as file handles that are allocated for the servlet

Important data may be saved to a persistent store The memory allocated for the servlet and

its objects can then be garbage collected

A servlet life cycle can be defined as the entire process from its creation till the destruction The

following are the paths followed by a servlet

The servlet is initialized by calling the init () method

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 38 of 38

The servlet calls service() method to process a clients request

The servlet is terminated by calling the destroy() method

Finally servlet is garbage collected by the garbage collector of the JVM

Initialization

(Load Resources)

Services

(Accept Requests)

Destruction

(Unload Resources)

Servlet

Request

Response

Page 26: AJP

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 26 of 38

b) Define the term

i) Reserved socket ii) proxy server

iii) Datagram iv) URL connection 4

(Each term- 2 Marks)

Ans i) Reserved socket

A socket is one end-point of a two-way communication link between two programs running on

the network Socket classes are used to represent the connection between a client program and a

server program

Reserved socket The socket which are reserved for specific protocols for communication

purpose are known as reseved sockets

TCPIP uses or reserves the lower 1024 ports for specific protocols

Example port number 23 is for Telnet 25 is for smtp 21 is for ftp 13 for daytime 110 for pop3

and so on Protocol decides how a client should interact with the port

ii) Proxy server

A proxy server is a computer that offers a computer network service to allow clients to make

indirect network connections to other network services A client connects to the proxy server

then requests a connection file or other resource available on a different server The proxy

provides the resource either by connecting to the specified server or by serving it from a cache In

some cases the proxy may alter the clients request or the servers response for various purposes

Purposes of the proxy servers

To keep machines behind it anonymous mainly for security

To speed up access to resources (using caching) Web proxies are commonly used to

cache web pages from a web server

To prevent downloading the same content multiple times (and save bandwidth)

To log audit usage eg to provide company employee Internet usage reporting

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 27 of 38

To scan transmitted content for malware before delivery

To scan outbound content eg for data loss prevention

iii) Datagram

Datagrams are bundles of information passed between machines They are somewhat like a hard

throw from a well-trained but blindfolded catcher to the third baseman Once the datagram has

been released to its intended target there is no assurance that it will arrive or even that

someone will be there to catch it Likewise when the datagram is received there is no

assurance that it hasnrsquot been damaged in transit or that whoever sent it is still there to receive a

response

Java implements datagrams on top of the UDP protocol by using two classes

The DatagramPacket object is the data container while the DatagramSocket is the mechanism

used to send or receive the DatagramPackets

iv) URL connection

URLConnection is a general-purpose class for accessing the attributes of a remote resource

Once you make a connection to a remote server you can use URLConnection to inspect the

Properties of the remote object before actually transporting it locally These attributes are

exposed by the HTTP protocol specification and as such only make sense for URL objects

that are using the HTTP protocol

URLConnection defines several methods

int getContentLength( )

String getContentType( )

long getDate( )

long getExpiration( )

String getHeaderField(int idx)

long getLastModified( )

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 28 of 38

c) Write a program to display three text fields and a button below to all an Applet Insert

the integer valuer from three text fields After pressing the button the background colour

of applet will be changed as per the RGB combination of the values given in the text field

(Correct logic - 6 Marks Syntax - 2 Marks)

4

Ans import javaawt

import javaawtevent

import javaapplet

ltapplet code=rdquoClrclassrdquo width=250 heigth=250gtltappletgt

public class Clrextends Applet implements ActionListener

int r g b

TextField t1t2t3

Button b1

Color c1

public void init()

t1= new TextField(5)

t2= new TextField(8)

t3= new TextField(11)

b1 = new Button(ldquo Set Colorrdquo)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 29 of 38

add(t1)

add(t2)

add(t3)

add(b1)

b1addActionListener(this)

public void void paint( )

setBackground(c1)

public void actionPerformed(ActionEvent ae)

r=IntegerparseInt(t1getText())

g=IntegerparseInt(t2getText())

b=IntegerparseInt(t3getText())

c1= new Color(rgb)

repaint()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 30 of 38

6) Attempt any four of the following Marks 16

a) How to check how many fonts are available in the computer system 4

Explain with example

(Explanation -2 Marks Example-2 Marks)

Ans When working with fonts often you need to know which fonts are available on your machine To

ontain this information you can use the getAvailableFontFamilyNames() method defined by the

GraphicsEnvironment classIt is shown here

String[ ] getAvailableFontFamilyNames( )

This method returns an array of string that contains the names of the available font families

Since this methods is members of GraphicsEnvironment you need a GraphicsEnvironment

reference to call itYou can obtain this reference by using the getlocalGrahicsEnvironmet() static

method which is derfined by GraphicsEnvironmentIt is shown here

static GraphicsEnvironment getLocalGraphicsEnvironment( )

Here is an applet that shown how to obtain the names of the available font families

ltapplet code=rdquoAllFontsrdquo width=500 height=100gt

ltappletgt

import javaapplet

import javaawt

public class AllFonts extends Applet

public void paint(Graphics g)

string fonts= ldquo rdquo

stirng allFontsList[]

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 31 of 38

GraphicsEnvironment t = GraphicsEnvironmentgetLocalGraphicsEnvironment()

allFontList = tgetAvailableFontFamilyNames()

for(int i= 0 ilt allFontsListlength i++)

fonts= fonts + allFontList[i] + ldquo rdquo

gdrawString(msg416)

b) Explain following check box class methods with appropriate example 4

i) Void setLable (String str) ii) Boolean getState ( )

(Explanation of each method-1 Marks Example-2 Marks)

Ans

i) void setLable(String str)

This method is used to set the label of check box

ii) Boolean getState()

This method is used to retrieve the current state of a check box It returns the value either true or

false depends on check box is selected or not

Example

Demonstrate check boxes

import javaawt

import javaawtevent

import javaapplet

ltapplet code=CheckboxDemo width=250 height=200gt

ltappletgt

public class CheckboxDemo extends Applet implements ItemListener

String msg =

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 32 of 38

Checkbox winXP winVista solaris mac

public void init()

winXP = new Checkbox(Windows XP null true)

mac = new Checkbox()

macsetLable(ldquoMac OSrdquo)

add(winXP)

add(mac)

winXPaddItemListener(this)

macaddItemListener(this)

public void itemStateChanged(ItemEvent ie)

repaint()

Display current state of the check boxes

public void paint(Graphics g)

msg = Current state

gdrawString(msg 6 80)

msg = Windows XP + winXPgetState()

gdrawString(msg 6 100)

msg = Mac OS + macgetState()

gdrawString(msg 6 120)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 33 of 38

c) Explain the techniques of session tracking management

(Any four techniques with explanation- 1 Mark each)

Ans Session tracking Techniques

1 User Authorization

Users can be authorized to use the web application in different ways Basic concept is that the

user will provide username and password to login to the application Based on that the user can

be identified and the session can be maintained

2 Hidden Fields

ltINPUT TYPE=rdquohiddenrdquo NAME=rdquotechnologyrdquo VALUE=rdquoservletrdquogt

Hidden fields like the above can be inserted in the webpages and information can be sent to the

server for session tracking These fields are not visible directly to the user but can be viewed

using view source option from the browsers This type doesnrsquot need any special configuration

from the browser of server and by default available to use for session tracking This cannot be

used for session tracking when the conversation included static resources lik html pages

3 URL Rewriting

Original URL httpserverportservletServletName

ewritten URL httpserverportservletServletNamesessionid=7456

When a request is made additional parameter is appended with the url In general added

additional parameter will be sessionid or sometimes the userid It will suffice to track the

session This type of session tracking doesnrsquot need any special support from the browser

Disadvantage is implementing this type of session tracking is tedious We need to keep track of

the parameter as a chain link until the conversation completes and also should make sure that

the parameter doesnrsquot clash with other application parameters

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 34 of 38

4 Cookies

Cookies are the mostly used technology for session tracking Cookie is a key value pair of

information sent by the server to the browser This should be saved by the browser in its space

in the client computer Whenever the browser sends a request to that server it sends the cookie

along with it Then the server can identify the client using the cookie

In java following is the source code snippet to create a cookie

Cookie cookie = new Cookie (ldquouserIDrdquo ldquo7456Prime)

resaddCookie(cookie)

5 Session tracking API

Session tracking API is built on top of the first four methods This is inorder to help the

developer to minimize the overhead of session tracking This type of session tracking is

provided by the underlying technology Lets take the java servlet example Then the servlet

container manages the session tracking task and the user need not do it explicitly using the java

servlets This is the best of all methods because all the management and errors related to

session tracking will be taken care of by the container itself

d) Give sequential steps for JTree in swing with example

(Steps- 2 Marks any small Example- 2 Marks)

Ans Steps for JTree

Atree is a component that presents a hierarchical view of data The user has the ability to

expand or collapse individual subtrees in this display Trees are implemented in Swing by

the JTree class

Here are the steps to follow to use a tree

1 Create an instance of JTree

2 Create a JScrollPane and specify the tree as the object to be scrolled

3 Add the tree to the scroll pane

4 Add the scroll pane to the content pane

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 35 of 38

Example

Demonstrate JTree

import javaawt

import javaxswingevent

import javaxswing

import javaxswingtree

ltapplet code=JTreeDemo width=400 height=200gt

ltappletgt

public class JTreeDemo extends JApplet

JTree tree

JLabel jlab

public void init()

try

SwingUtilitiesinvokeAndWait(

new Runnable()

public void run()

makeGUI()

)

catch (Exception exc)

Systemoutprintln(Cant create because of + exc)

private void makeGUI()

Create top node of tree

DefaultMutableTreeNode top = new DefaultMutableTreeNode(Options)

Create subtree of A

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 36 of 38

DefaultMutableTreeNode a = new DefaultMutableTreeNode(A)

topadd(a)

DefaultMutableTreeNode a1 = new DefaultMutableTreeNode(A1)

aadd(a1)

DefaultMutableTreeNode a2 = new DefaultMutableTreeNode(A2)

aadd(a2)

Create subtree of B

DefaultMutableTreeNode b = new DefaultMutableTreeNode(B)

topadd(b)

DefaultMutableTreeNode b1 = new DefaultMutableTreeNode(B1)

badd(b1)

DefaultMutableTreeNode b2 = new DefaultMutableTreeNode(B2)

badd(b2)

DefaultMutableTreeNode b3 = new DefaultMutableTreeNode(B3)

badd(b3)

Create the tree

tree = new JTree(top)

Add the tree to a scroll pane

JScrollPane jsp = new JScrollPane(tree)

Add the scroll pane to the content pane

add(jsp)

Add the label to the content pane

jlab = new JLabel()

add(jlab BorderLayoutSOUTH)

Handle tree selection events

treeaddTreeSelectionListener(new TreeSelectionListener()

public void valueChanged(TreeSelectionEvent tse)

jlabsetText(Selection is + tsegetPath())

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 37 of 38

e) Draw and explain the life cycle of servlet

(Explanation ndash 3 Marks Diagram -1 Marks)

Ans Three methods are central to the life cycle of a servlet

These are init( ) service( ) and destroy( )

They are implemented by every servlet and are invoked at specific times by the server Let

us consider a typical user scenario to understand when these methods are called

First assume that a user enters a Uniform Resource Locator (URL) to a web browser

The browser then generates an HTTP request for this URL This request is then sent to the

appropriate server

Second this HTTP request is received by the web server The server maps this request to

a particular servlet The servlet is dynamically retrieved and loaded into the address space

of the server

Third the server invokes the init( ) method of the servlet This method is invoked only

when the servlet is first loaded into memory It is possible to pass initialization parameters

to the servlet so it may configure itself

Fourth the server invokes the service( ) method of the servlet This method is called to

process the HTTP request You will see that it is possible for the servlet to read data that has

been provided in the HTTP request It may also formulate an HTTP response for the client

The servlet remains in the serverrsquos address space and is available to process any other

HTTP requests received from clients The service( ) method is called for each HTTP request

Finally the server may decide to unload the servlet from its memory The algorithms by

which this determination is made are specific to each server The server calls the destroy( )

method to relinquish any resources such as file handles that are allocated for the servlet

Important data may be saved to a persistent store The memory allocated for the servlet and

its objects can then be garbage collected

A servlet life cycle can be defined as the entire process from its creation till the destruction The

following are the paths followed by a servlet

The servlet is initialized by calling the init () method

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 38 of 38

The servlet calls service() method to process a clients request

The servlet is terminated by calling the destroy() method

Finally servlet is garbage collected by the garbage collector of the JVM

Initialization

(Load Resources)

Services

(Accept Requests)

Destruction

(Unload Resources)

Servlet

Request

Response

Page 27: AJP

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 27 of 38

To scan transmitted content for malware before delivery

To scan outbound content eg for data loss prevention

iii) Datagram

Datagrams are bundles of information passed between machines They are somewhat like a hard

throw from a well-trained but blindfolded catcher to the third baseman Once the datagram has

been released to its intended target there is no assurance that it will arrive or even that

someone will be there to catch it Likewise when the datagram is received there is no

assurance that it hasnrsquot been damaged in transit or that whoever sent it is still there to receive a

response

Java implements datagrams on top of the UDP protocol by using two classes

The DatagramPacket object is the data container while the DatagramSocket is the mechanism

used to send or receive the DatagramPackets

iv) URL connection

URLConnection is a general-purpose class for accessing the attributes of a remote resource

Once you make a connection to a remote server you can use URLConnection to inspect the

Properties of the remote object before actually transporting it locally These attributes are

exposed by the HTTP protocol specification and as such only make sense for URL objects

that are using the HTTP protocol

URLConnection defines several methods

int getContentLength( )

String getContentType( )

long getDate( )

long getExpiration( )

String getHeaderField(int idx)

long getLastModified( )

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 28 of 38

c) Write a program to display three text fields and a button below to all an Applet Insert

the integer valuer from three text fields After pressing the button the background colour

of applet will be changed as per the RGB combination of the values given in the text field

(Correct logic - 6 Marks Syntax - 2 Marks)

4

Ans import javaawt

import javaawtevent

import javaapplet

ltapplet code=rdquoClrclassrdquo width=250 heigth=250gtltappletgt

public class Clrextends Applet implements ActionListener

int r g b

TextField t1t2t3

Button b1

Color c1

public void init()

t1= new TextField(5)

t2= new TextField(8)

t3= new TextField(11)

b1 = new Button(ldquo Set Colorrdquo)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 29 of 38

add(t1)

add(t2)

add(t3)

add(b1)

b1addActionListener(this)

public void void paint( )

setBackground(c1)

public void actionPerformed(ActionEvent ae)

r=IntegerparseInt(t1getText())

g=IntegerparseInt(t2getText())

b=IntegerparseInt(t3getText())

c1= new Color(rgb)

repaint()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 30 of 38

6) Attempt any four of the following Marks 16

a) How to check how many fonts are available in the computer system 4

Explain with example

(Explanation -2 Marks Example-2 Marks)

Ans When working with fonts often you need to know which fonts are available on your machine To

ontain this information you can use the getAvailableFontFamilyNames() method defined by the

GraphicsEnvironment classIt is shown here

String[ ] getAvailableFontFamilyNames( )

This method returns an array of string that contains the names of the available font families

Since this methods is members of GraphicsEnvironment you need a GraphicsEnvironment

reference to call itYou can obtain this reference by using the getlocalGrahicsEnvironmet() static

method which is derfined by GraphicsEnvironmentIt is shown here

static GraphicsEnvironment getLocalGraphicsEnvironment( )

Here is an applet that shown how to obtain the names of the available font families

ltapplet code=rdquoAllFontsrdquo width=500 height=100gt

ltappletgt

import javaapplet

import javaawt

public class AllFonts extends Applet

public void paint(Graphics g)

string fonts= ldquo rdquo

stirng allFontsList[]

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 31 of 38

GraphicsEnvironment t = GraphicsEnvironmentgetLocalGraphicsEnvironment()

allFontList = tgetAvailableFontFamilyNames()

for(int i= 0 ilt allFontsListlength i++)

fonts= fonts + allFontList[i] + ldquo rdquo

gdrawString(msg416)

b) Explain following check box class methods with appropriate example 4

i) Void setLable (String str) ii) Boolean getState ( )

(Explanation of each method-1 Marks Example-2 Marks)

Ans

i) void setLable(String str)

This method is used to set the label of check box

ii) Boolean getState()

This method is used to retrieve the current state of a check box It returns the value either true or

false depends on check box is selected or not

Example

Demonstrate check boxes

import javaawt

import javaawtevent

import javaapplet

ltapplet code=CheckboxDemo width=250 height=200gt

ltappletgt

public class CheckboxDemo extends Applet implements ItemListener

String msg =

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 32 of 38

Checkbox winXP winVista solaris mac

public void init()

winXP = new Checkbox(Windows XP null true)

mac = new Checkbox()

macsetLable(ldquoMac OSrdquo)

add(winXP)

add(mac)

winXPaddItemListener(this)

macaddItemListener(this)

public void itemStateChanged(ItemEvent ie)

repaint()

Display current state of the check boxes

public void paint(Graphics g)

msg = Current state

gdrawString(msg 6 80)

msg = Windows XP + winXPgetState()

gdrawString(msg 6 100)

msg = Mac OS + macgetState()

gdrawString(msg 6 120)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 33 of 38

c) Explain the techniques of session tracking management

(Any four techniques with explanation- 1 Mark each)

Ans Session tracking Techniques

1 User Authorization

Users can be authorized to use the web application in different ways Basic concept is that the

user will provide username and password to login to the application Based on that the user can

be identified and the session can be maintained

2 Hidden Fields

ltINPUT TYPE=rdquohiddenrdquo NAME=rdquotechnologyrdquo VALUE=rdquoservletrdquogt

Hidden fields like the above can be inserted in the webpages and information can be sent to the

server for session tracking These fields are not visible directly to the user but can be viewed

using view source option from the browsers This type doesnrsquot need any special configuration

from the browser of server and by default available to use for session tracking This cannot be

used for session tracking when the conversation included static resources lik html pages

3 URL Rewriting

Original URL httpserverportservletServletName

ewritten URL httpserverportservletServletNamesessionid=7456

When a request is made additional parameter is appended with the url In general added

additional parameter will be sessionid or sometimes the userid It will suffice to track the

session This type of session tracking doesnrsquot need any special support from the browser

Disadvantage is implementing this type of session tracking is tedious We need to keep track of

the parameter as a chain link until the conversation completes and also should make sure that

the parameter doesnrsquot clash with other application parameters

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 34 of 38

4 Cookies

Cookies are the mostly used technology for session tracking Cookie is a key value pair of

information sent by the server to the browser This should be saved by the browser in its space

in the client computer Whenever the browser sends a request to that server it sends the cookie

along with it Then the server can identify the client using the cookie

In java following is the source code snippet to create a cookie

Cookie cookie = new Cookie (ldquouserIDrdquo ldquo7456Prime)

resaddCookie(cookie)

5 Session tracking API

Session tracking API is built on top of the first four methods This is inorder to help the

developer to minimize the overhead of session tracking This type of session tracking is

provided by the underlying technology Lets take the java servlet example Then the servlet

container manages the session tracking task and the user need not do it explicitly using the java

servlets This is the best of all methods because all the management and errors related to

session tracking will be taken care of by the container itself

d) Give sequential steps for JTree in swing with example

(Steps- 2 Marks any small Example- 2 Marks)

Ans Steps for JTree

Atree is a component that presents a hierarchical view of data The user has the ability to

expand or collapse individual subtrees in this display Trees are implemented in Swing by

the JTree class

Here are the steps to follow to use a tree

1 Create an instance of JTree

2 Create a JScrollPane and specify the tree as the object to be scrolled

3 Add the tree to the scroll pane

4 Add the scroll pane to the content pane

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 35 of 38

Example

Demonstrate JTree

import javaawt

import javaxswingevent

import javaxswing

import javaxswingtree

ltapplet code=JTreeDemo width=400 height=200gt

ltappletgt

public class JTreeDemo extends JApplet

JTree tree

JLabel jlab

public void init()

try

SwingUtilitiesinvokeAndWait(

new Runnable()

public void run()

makeGUI()

)

catch (Exception exc)

Systemoutprintln(Cant create because of + exc)

private void makeGUI()

Create top node of tree

DefaultMutableTreeNode top = new DefaultMutableTreeNode(Options)

Create subtree of A

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 36 of 38

DefaultMutableTreeNode a = new DefaultMutableTreeNode(A)

topadd(a)

DefaultMutableTreeNode a1 = new DefaultMutableTreeNode(A1)

aadd(a1)

DefaultMutableTreeNode a2 = new DefaultMutableTreeNode(A2)

aadd(a2)

Create subtree of B

DefaultMutableTreeNode b = new DefaultMutableTreeNode(B)

topadd(b)

DefaultMutableTreeNode b1 = new DefaultMutableTreeNode(B1)

badd(b1)

DefaultMutableTreeNode b2 = new DefaultMutableTreeNode(B2)

badd(b2)

DefaultMutableTreeNode b3 = new DefaultMutableTreeNode(B3)

badd(b3)

Create the tree

tree = new JTree(top)

Add the tree to a scroll pane

JScrollPane jsp = new JScrollPane(tree)

Add the scroll pane to the content pane

add(jsp)

Add the label to the content pane

jlab = new JLabel()

add(jlab BorderLayoutSOUTH)

Handle tree selection events

treeaddTreeSelectionListener(new TreeSelectionListener()

public void valueChanged(TreeSelectionEvent tse)

jlabsetText(Selection is + tsegetPath())

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 37 of 38

e) Draw and explain the life cycle of servlet

(Explanation ndash 3 Marks Diagram -1 Marks)

Ans Three methods are central to the life cycle of a servlet

These are init( ) service( ) and destroy( )

They are implemented by every servlet and are invoked at specific times by the server Let

us consider a typical user scenario to understand when these methods are called

First assume that a user enters a Uniform Resource Locator (URL) to a web browser

The browser then generates an HTTP request for this URL This request is then sent to the

appropriate server

Second this HTTP request is received by the web server The server maps this request to

a particular servlet The servlet is dynamically retrieved and loaded into the address space

of the server

Third the server invokes the init( ) method of the servlet This method is invoked only

when the servlet is first loaded into memory It is possible to pass initialization parameters

to the servlet so it may configure itself

Fourth the server invokes the service( ) method of the servlet This method is called to

process the HTTP request You will see that it is possible for the servlet to read data that has

been provided in the HTTP request It may also formulate an HTTP response for the client

The servlet remains in the serverrsquos address space and is available to process any other

HTTP requests received from clients The service( ) method is called for each HTTP request

Finally the server may decide to unload the servlet from its memory The algorithms by

which this determination is made are specific to each server The server calls the destroy( )

method to relinquish any resources such as file handles that are allocated for the servlet

Important data may be saved to a persistent store The memory allocated for the servlet and

its objects can then be garbage collected

A servlet life cycle can be defined as the entire process from its creation till the destruction The

following are the paths followed by a servlet

The servlet is initialized by calling the init () method

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 38 of 38

The servlet calls service() method to process a clients request

The servlet is terminated by calling the destroy() method

Finally servlet is garbage collected by the garbage collector of the JVM

Initialization

(Load Resources)

Services

(Accept Requests)

Destruction

(Unload Resources)

Servlet

Request

Response

Page 28: AJP

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 28 of 38

c) Write a program to display three text fields and a button below to all an Applet Insert

the integer valuer from three text fields After pressing the button the background colour

of applet will be changed as per the RGB combination of the values given in the text field

(Correct logic - 6 Marks Syntax - 2 Marks)

4

Ans import javaawt

import javaawtevent

import javaapplet

ltapplet code=rdquoClrclassrdquo width=250 heigth=250gtltappletgt

public class Clrextends Applet implements ActionListener

int r g b

TextField t1t2t3

Button b1

Color c1

public void init()

t1= new TextField(5)

t2= new TextField(8)

t3= new TextField(11)

b1 = new Button(ldquo Set Colorrdquo)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 29 of 38

add(t1)

add(t2)

add(t3)

add(b1)

b1addActionListener(this)

public void void paint( )

setBackground(c1)

public void actionPerformed(ActionEvent ae)

r=IntegerparseInt(t1getText())

g=IntegerparseInt(t2getText())

b=IntegerparseInt(t3getText())

c1= new Color(rgb)

repaint()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 30 of 38

6) Attempt any four of the following Marks 16

a) How to check how many fonts are available in the computer system 4

Explain with example

(Explanation -2 Marks Example-2 Marks)

Ans When working with fonts often you need to know which fonts are available on your machine To

ontain this information you can use the getAvailableFontFamilyNames() method defined by the

GraphicsEnvironment classIt is shown here

String[ ] getAvailableFontFamilyNames( )

This method returns an array of string that contains the names of the available font families

Since this methods is members of GraphicsEnvironment you need a GraphicsEnvironment

reference to call itYou can obtain this reference by using the getlocalGrahicsEnvironmet() static

method which is derfined by GraphicsEnvironmentIt is shown here

static GraphicsEnvironment getLocalGraphicsEnvironment( )

Here is an applet that shown how to obtain the names of the available font families

ltapplet code=rdquoAllFontsrdquo width=500 height=100gt

ltappletgt

import javaapplet

import javaawt

public class AllFonts extends Applet

public void paint(Graphics g)

string fonts= ldquo rdquo

stirng allFontsList[]

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 31 of 38

GraphicsEnvironment t = GraphicsEnvironmentgetLocalGraphicsEnvironment()

allFontList = tgetAvailableFontFamilyNames()

for(int i= 0 ilt allFontsListlength i++)

fonts= fonts + allFontList[i] + ldquo rdquo

gdrawString(msg416)

b) Explain following check box class methods with appropriate example 4

i) Void setLable (String str) ii) Boolean getState ( )

(Explanation of each method-1 Marks Example-2 Marks)

Ans

i) void setLable(String str)

This method is used to set the label of check box

ii) Boolean getState()

This method is used to retrieve the current state of a check box It returns the value either true or

false depends on check box is selected or not

Example

Demonstrate check boxes

import javaawt

import javaawtevent

import javaapplet

ltapplet code=CheckboxDemo width=250 height=200gt

ltappletgt

public class CheckboxDemo extends Applet implements ItemListener

String msg =

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 32 of 38

Checkbox winXP winVista solaris mac

public void init()

winXP = new Checkbox(Windows XP null true)

mac = new Checkbox()

macsetLable(ldquoMac OSrdquo)

add(winXP)

add(mac)

winXPaddItemListener(this)

macaddItemListener(this)

public void itemStateChanged(ItemEvent ie)

repaint()

Display current state of the check boxes

public void paint(Graphics g)

msg = Current state

gdrawString(msg 6 80)

msg = Windows XP + winXPgetState()

gdrawString(msg 6 100)

msg = Mac OS + macgetState()

gdrawString(msg 6 120)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 33 of 38

c) Explain the techniques of session tracking management

(Any four techniques with explanation- 1 Mark each)

Ans Session tracking Techniques

1 User Authorization

Users can be authorized to use the web application in different ways Basic concept is that the

user will provide username and password to login to the application Based on that the user can

be identified and the session can be maintained

2 Hidden Fields

ltINPUT TYPE=rdquohiddenrdquo NAME=rdquotechnologyrdquo VALUE=rdquoservletrdquogt

Hidden fields like the above can be inserted in the webpages and information can be sent to the

server for session tracking These fields are not visible directly to the user but can be viewed

using view source option from the browsers This type doesnrsquot need any special configuration

from the browser of server and by default available to use for session tracking This cannot be

used for session tracking when the conversation included static resources lik html pages

3 URL Rewriting

Original URL httpserverportservletServletName

ewritten URL httpserverportservletServletNamesessionid=7456

When a request is made additional parameter is appended with the url In general added

additional parameter will be sessionid or sometimes the userid It will suffice to track the

session This type of session tracking doesnrsquot need any special support from the browser

Disadvantage is implementing this type of session tracking is tedious We need to keep track of

the parameter as a chain link until the conversation completes and also should make sure that

the parameter doesnrsquot clash with other application parameters

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 34 of 38

4 Cookies

Cookies are the mostly used technology for session tracking Cookie is a key value pair of

information sent by the server to the browser This should be saved by the browser in its space

in the client computer Whenever the browser sends a request to that server it sends the cookie

along with it Then the server can identify the client using the cookie

In java following is the source code snippet to create a cookie

Cookie cookie = new Cookie (ldquouserIDrdquo ldquo7456Prime)

resaddCookie(cookie)

5 Session tracking API

Session tracking API is built on top of the first four methods This is inorder to help the

developer to minimize the overhead of session tracking This type of session tracking is

provided by the underlying technology Lets take the java servlet example Then the servlet

container manages the session tracking task and the user need not do it explicitly using the java

servlets This is the best of all methods because all the management and errors related to

session tracking will be taken care of by the container itself

d) Give sequential steps for JTree in swing with example

(Steps- 2 Marks any small Example- 2 Marks)

Ans Steps for JTree

Atree is a component that presents a hierarchical view of data The user has the ability to

expand or collapse individual subtrees in this display Trees are implemented in Swing by

the JTree class

Here are the steps to follow to use a tree

1 Create an instance of JTree

2 Create a JScrollPane and specify the tree as the object to be scrolled

3 Add the tree to the scroll pane

4 Add the scroll pane to the content pane

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 35 of 38

Example

Demonstrate JTree

import javaawt

import javaxswingevent

import javaxswing

import javaxswingtree

ltapplet code=JTreeDemo width=400 height=200gt

ltappletgt

public class JTreeDemo extends JApplet

JTree tree

JLabel jlab

public void init()

try

SwingUtilitiesinvokeAndWait(

new Runnable()

public void run()

makeGUI()

)

catch (Exception exc)

Systemoutprintln(Cant create because of + exc)

private void makeGUI()

Create top node of tree

DefaultMutableTreeNode top = new DefaultMutableTreeNode(Options)

Create subtree of A

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 36 of 38

DefaultMutableTreeNode a = new DefaultMutableTreeNode(A)

topadd(a)

DefaultMutableTreeNode a1 = new DefaultMutableTreeNode(A1)

aadd(a1)

DefaultMutableTreeNode a2 = new DefaultMutableTreeNode(A2)

aadd(a2)

Create subtree of B

DefaultMutableTreeNode b = new DefaultMutableTreeNode(B)

topadd(b)

DefaultMutableTreeNode b1 = new DefaultMutableTreeNode(B1)

badd(b1)

DefaultMutableTreeNode b2 = new DefaultMutableTreeNode(B2)

badd(b2)

DefaultMutableTreeNode b3 = new DefaultMutableTreeNode(B3)

badd(b3)

Create the tree

tree = new JTree(top)

Add the tree to a scroll pane

JScrollPane jsp = new JScrollPane(tree)

Add the scroll pane to the content pane

add(jsp)

Add the label to the content pane

jlab = new JLabel()

add(jlab BorderLayoutSOUTH)

Handle tree selection events

treeaddTreeSelectionListener(new TreeSelectionListener()

public void valueChanged(TreeSelectionEvent tse)

jlabsetText(Selection is + tsegetPath())

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 37 of 38

e) Draw and explain the life cycle of servlet

(Explanation ndash 3 Marks Diagram -1 Marks)

Ans Three methods are central to the life cycle of a servlet

These are init( ) service( ) and destroy( )

They are implemented by every servlet and are invoked at specific times by the server Let

us consider a typical user scenario to understand when these methods are called

First assume that a user enters a Uniform Resource Locator (URL) to a web browser

The browser then generates an HTTP request for this URL This request is then sent to the

appropriate server

Second this HTTP request is received by the web server The server maps this request to

a particular servlet The servlet is dynamically retrieved and loaded into the address space

of the server

Third the server invokes the init( ) method of the servlet This method is invoked only

when the servlet is first loaded into memory It is possible to pass initialization parameters

to the servlet so it may configure itself

Fourth the server invokes the service( ) method of the servlet This method is called to

process the HTTP request You will see that it is possible for the servlet to read data that has

been provided in the HTTP request It may also formulate an HTTP response for the client

The servlet remains in the serverrsquos address space and is available to process any other

HTTP requests received from clients The service( ) method is called for each HTTP request

Finally the server may decide to unload the servlet from its memory The algorithms by

which this determination is made are specific to each server The server calls the destroy( )

method to relinquish any resources such as file handles that are allocated for the servlet

Important data may be saved to a persistent store The memory allocated for the servlet and

its objects can then be garbage collected

A servlet life cycle can be defined as the entire process from its creation till the destruction The

following are the paths followed by a servlet

The servlet is initialized by calling the init () method

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 38 of 38

The servlet calls service() method to process a clients request

The servlet is terminated by calling the destroy() method

Finally servlet is garbage collected by the garbage collector of the JVM

Initialization

(Load Resources)

Services

(Accept Requests)

Destruction

(Unload Resources)

Servlet

Request

Response

Page 29: AJP

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 29 of 38

add(t1)

add(t2)

add(t3)

add(b1)

b1addActionListener(this)

public void void paint( )

setBackground(c1)

public void actionPerformed(ActionEvent ae)

r=IntegerparseInt(t1getText())

g=IntegerparseInt(t2getText())

b=IntegerparseInt(t3getText())

c1= new Color(rgb)

repaint()

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 30 of 38

6) Attempt any four of the following Marks 16

a) How to check how many fonts are available in the computer system 4

Explain with example

(Explanation -2 Marks Example-2 Marks)

Ans When working with fonts often you need to know which fonts are available on your machine To

ontain this information you can use the getAvailableFontFamilyNames() method defined by the

GraphicsEnvironment classIt is shown here

String[ ] getAvailableFontFamilyNames( )

This method returns an array of string that contains the names of the available font families

Since this methods is members of GraphicsEnvironment you need a GraphicsEnvironment

reference to call itYou can obtain this reference by using the getlocalGrahicsEnvironmet() static

method which is derfined by GraphicsEnvironmentIt is shown here

static GraphicsEnvironment getLocalGraphicsEnvironment( )

Here is an applet that shown how to obtain the names of the available font families

ltapplet code=rdquoAllFontsrdquo width=500 height=100gt

ltappletgt

import javaapplet

import javaawt

public class AllFonts extends Applet

public void paint(Graphics g)

string fonts= ldquo rdquo

stirng allFontsList[]

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 31 of 38

GraphicsEnvironment t = GraphicsEnvironmentgetLocalGraphicsEnvironment()

allFontList = tgetAvailableFontFamilyNames()

for(int i= 0 ilt allFontsListlength i++)

fonts= fonts + allFontList[i] + ldquo rdquo

gdrawString(msg416)

b) Explain following check box class methods with appropriate example 4

i) Void setLable (String str) ii) Boolean getState ( )

(Explanation of each method-1 Marks Example-2 Marks)

Ans

i) void setLable(String str)

This method is used to set the label of check box

ii) Boolean getState()

This method is used to retrieve the current state of a check box It returns the value either true or

false depends on check box is selected or not

Example

Demonstrate check boxes

import javaawt

import javaawtevent

import javaapplet

ltapplet code=CheckboxDemo width=250 height=200gt

ltappletgt

public class CheckboxDemo extends Applet implements ItemListener

String msg =

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 32 of 38

Checkbox winXP winVista solaris mac

public void init()

winXP = new Checkbox(Windows XP null true)

mac = new Checkbox()

macsetLable(ldquoMac OSrdquo)

add(winXP)

add(mac)

winXPaddItemListener(this)

macaddItemListener(this)

public void itemStateChanged(ItemEvent ie)

repaint()

Display current state of the check boxes

public void paint(Graphics g)

msg = Current state

gdrawString(msg 6 80)

msg = Windows XP + winXPgetState()

gdrawString(msg 6 100)

msg = Mac OS + macgetState()

gdrawString(msg 6 120)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 33 of 38

c) Explain the techniques of session tracking management

(Any four techniques with explanation- 1 Mark each)

Ans Session tracking Techniques

1 User Authorization

Users can be authorized to use the web application in different ways Basic concept is that the

user will provide username and password to login to the application Based on that the user can

be identified and the session can be maintained

2 Hidden Fields

ltINPUT TYPE=rdquohiddenrdquo NAME=rdquotechnologyrdquo VALUE=rdquoservletrdquogt

Hidden fields like the above can be inserted in the webpages and information can be sent to the

server for session tracking These fields are not visible directly to the user but can be viewed

using view source option from the browsers This type doesnrsquot need any special configuration

from the browser of server and by default available to use for session tracking This cannot be

used for session tracking when the conversation included static resources lik html pages

3 URL Rewriting

Original URL httpserverportservletServletName

ewritten URL httpserverportservletServletNamesessionid=7456

When a request is made additional parameter is appended with the url In general added

additional parameter will be sessionid or sometimes the userid It will suffice to track the

session This type of session tracking doesnrsquot need any special support from the browser

Disadvantage is implementing this type of session tracking is tedious We need to keep track of

the parameter as a chain link until the conversation completes and also should make sure that

the parameter doesnrsquot clash with other application parameters

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 34 of 38

4 Cookies

Cookies are the mostly used technology for session tracking Cookie is a key value pair of

information sent by the server to the browser This should be saved by the browser in its space

in the client computer Whenever the browser sends a request to that server it sends the cookie

along with it Then the server can identify the client using the cookie

In java following is the source code snippet to create a cookie

Cookie cookie = new Cookie (ldquouserIDrdquo ldquo7456Prime)

resaddCookie(cookie)

5 Session tracking API

Session tracking API is built on top of the first four methods This is inorder to help the

developer to minimize the overhead of session tracking This type of session tracking is

provided by the underlying technology Lets take the java servlet example Then the servlet

container manages the session tracking task and the user need not do it explicitly using the java

servlets This is the best of all methods because all the management and errors related to

session tracking will be taken care of by the container itself

d) Give sequential steps for JTree in swing with example

(Steps- 2 Marks any small Example- 2 Marks)

Ans Steps for JTree

Atree is a component that presents a hierarchical view of data The user has the ability to

expand or collapse individual subtrees in this display Trees are implemented in Swing by

the JTree class

Here are the steps to follow to use a tree

1 Create an instance of JTree

2 Create a JScrollPane and specify the tree as the object to be scrolled

3 Add the tree to the scroll pane

4 Add the scroll pane to the content pane

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 35 of 38

Example

Demonstrate JTree

import javaawt

import javaxswingevent

import javaxswing

import javaxswingtree

ltapplet code=JTreeDemo width=400 height=200gt

ltappletgt

public class JTreeDemo extends JApplet

JTree tree

JLabel jlab

public void init()

try

SwingUtilitiesinvokeAndWait(

new Runnable()

public void run()

makeGUI()

)

catch (Exception exc)

Systemoutprintln(Cant create because of + exc)

private void makeGUI()

Create top node of tree

DefaultMutableTreeNode top = new DefaultMutableTreeNode(Options)

Create subtree of A

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 36 of 38

DefaultMutableTreeNode a = new DefaultMutableTreeNode(A)

topadd(a)

DefaultMutableTreeNode a1 = new DefaultMutableTreeNode(A1)

aadd(a1)

DefaultMutableTreeNode a2 = new DefaultMutableTreeNode(A2)

aadd(a2)

Create subtree of B

DefaultMutableTreeNode b = new DefaultMutableTreeNode(B)

topadd(b)

DefaultMutableTreeNode b1 = new DefaultMutableTreeNode(B1)

badd(b1)

DefaultMutableTreeNode b2 = new DefaultMutableTreeNode(B2)

badd(b2)

DefaultMutableTreeNode b3 = new DefaultMutableTreeNode(B3)

badd(b3)

Create the tree

tree = new JTree(top)

Add the tree to a scroll pane

JScrollPane jsp = new JScrollPane(tree)

Add the scroll pane to the content pane

add(jsp)

Add the label to the content pane

jlab = new JLabel()

add(jlab BorderLayoutSOUTH)

Handle tree selection events

treeaddTreeSelectionListener(new TreeSelectionListener()

public void valueChanged(TreeSelectionEvent tse)

jlabsetText(Selection is + tsegetPath())

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 37 of 38

e) Draw and explain the life cycle of servlet

(Explanation ndash 3 Marks Diagram -1 Marks)

Ans Three methods are central to the life cycle of a servlet

These are init( ) service( ) and destroy( )

They are implemented by every servlet and are invoked at specific times by the server Let

us consider a typical user scenario to understand when these methods are called

First assume that a user enters a Uniform Resource Locator (URL) to a web browser

The browser then generates an HTTP request for this URL This request is then sent to the

appropriate server

Second this HTTP request is received by the web server The server maps this request to

a particular servlet The servlet is dynamically retrieved and loaded into the address space

of the server

Third the server invokes the init( ) method of the servlet This method is invoked only

when the servlet is first loaded into memory It is possible to pass initialization parameters

to the servlet so it may configure itself

Fourth the server invokes the service( ) method of the servlet This method is called to

process the HTTP request You will see that it is possible for the servlet to read data that has

been provided in the HTTP request It may also formulate an HTTP response for the client

The servlet remains in the serverrsquos address space and is available to process any other

HTTP requests received from clients The service( ) method is called for each HTTP request

Finally the server may decide to unload the servlet from its memory The algorithms by

which this determination is made are specific to each server The server calls the destroy( )

method to relinquish any resources such as file handles that are allocated for the servlet

Important data may be saved to a persistent store The memory allocated for the servlet and

its objects can then be garbage collected

A servlet life cycle can be defined as the entire process from its creation till the destruction The

following are the paths followed by a servlet

The servlet is initialized by calling the init () method

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 38 of 38

The servlet calls service() method to process a clients request

The servlet is terminated by calling the destroy() method

Finally servlet is garbage collected by the garbage collector of the JVM

Initialization

(Load Resources)

Services

(Accept Requests)

Destruction

(Unload Resources)

Servlet

Request

Response

Page 30: AJP

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 30 of 38

6) Attempt any four of the following Marks 16

a) How to check how many fonts are available in the computer system 4

Explain with example

(Explanation -2 Marks Example-2 Marks)

Ans When working with fonts often you need to know which fonts are available on your machine To

ontain this information you can use the getAvailableFontFamilyNames() method defined by the

GraphicsEnvironment classIt is shown here

String[ ] getAvailableFontFamilyNames( )

This method returns an array of string that contains the names of the available font families

Since this methods is members of GraphicsEnvironment you need a GraphicsEnvironment

reference to call itYou can obtain this reference by using the getlocalGrahicsEnvironmet() static

method which is derfined by GraphicsEnvironmentIt is shown here

static GraphicsEnvironment getLocalGraphicsEnvironment( )

Here is an applet that shown how to obtain the names of the available font families

ltapplet code=rdquoAllFontsrdquo width=500 height=100gt

ltappletgt

import javaapplet

import javaawt

public class AllFonts extends Applet

public void paint(Graphics g)

string fonts= ldquo rdquo

stirng allFontsList[]

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 31 of 38

GraphicsEnvironment t = GraphicsEnvironmentgetLocalGraphicsEnvironment()

allFontList = tgetAvailableFontFamilyNames()

for(int i= 0 ilt allFontsListlength i++)

fonts= fonts + allFontList[i] + ldquo rdquo

gdrawString(msg416)

b) Explain following check box class methods with appropriate example 4

i) Void setLable (String str) ii) Boolean getState ( )

(Explanation of each method-1 Marks Example-2 Marks)

Ans

i) void setLable(String str)

This method is used to set the label of check box

ii) Boolean getState()

This method is used to retrieve the current state of a check box It returns the value either true or

false depends on check box is selected or not

Example

Demonstrate check boxes

import javaawt

import javaawtevent

import javaapplet

ltapplet code=CheckboxDemo width=250 height=200gt

ltappletgt

public class CheckboxDemo extends Applet implements ItemListener

String msg =

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 32 of 38

Checkbox winXP winVista solaris mac

public void init()

winXP = new Checkbox(Windows XP null true)

mac = new Checkbox()

macsetLable(ldquoMac OSrdquo)

add(winXP)

add(mac)

winXPaddItemListener(this)

macaddItemListener(this)

public void itemStateChanged(ItemEvent ie)

repaint()

Display current state of the check boxes

public void paint(Graphics g)

msg = Current state

gdrawString(msg 6 80)

msg = Windows XP + winXPgetState()

gdrawString(msg 6 100)

msg = Mac OS + macgetState()

gdrawString(msg 6 120)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 33 of 38

c) Explain the techniques of session tracking management

(Any four techniques with explanation- 1 Mark each)

Ans Session tracking Techniques

1 User Authorization

Users can be authorized to use the web application in different ways Basic concept is that the

user will provide username and password to login to the application Based on that the user can

be identified and the session can be maintained

2 Hidden Fields

ltINPUT TYPE=rdquohiddenrdquo NAME=rdquotechnologyrdquo VALUE=rdquoservletrdquogt

Hidden fields like the above can be inserted in the webpages and information can be sent to the

server for session tracking These fields are not visible directly to the user but can be viewed

using view source option from the browsers This type doesnrsquot need any special configuration

from the browser of server and by default available to use for session tracking This cannot be

used for session tracking when the conversation included static resources lik html pages

3 URL Rewriting

Original URL httpserverportservletServletName

ewritten URL httpserverportservletServletNamesessionid=7456

When a request is made additional parameter is appended with the url In general added

additional parameter will be sessionid or sometimes the userid It will suffice to track the

session This type of session tracking doesnrsquot need any special support from the browser

Disadvantage is implementing this type of session tracking is tedious We need to keep track of

the parameter as a chain link until the conversation completes and also should make sure that

the parameter doesnrsquot clash with other application parameters

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 34 of 38

4 Cookies

Cookies are the mostly used technology for session tracking Cookie is a key value pair of

information sent by the server to the browser This should be saved by the browser in its space

in the client computer Whenever the browser sends a request to that server it sends the cookie

along with it Then the server can identify the client using the cookie

In java following is the source code snippet to create a cookie

Cookie cookie = new Cookie (ldquouserIDrdquo ldquo7456Prime)

resaddCookie(cookie)

5 Session tracking API

Session tracking API is built on top of the first four methods This is inorder to help the

developer to minimize the overhead of session tracking This type of session tracking is

provided by the underlying technology Lets take the java servlet example Then the servlet

container manages the session tracking task and the user need not do it explicitly using the java

servlets This is the best of all methods because all the management and errors related to

session tracking will be taken care of by the container itself

d) Give sequential steps for JTree in swing with example

(Steps- 2 Marks any small Example- 2 Marks)

Ans Steps for JTree

Atree is a component that presents a hierarchical view of data The user has the ability to

expand or collapse individual subtrees in this display Trees are implemented in Swing by

the JTree class

Here are the steps to follow to use a tree

1 Create an instance of JTree

2 Create a JScrollPane and specify the tree as the object to be scrolled

3 Add the tree to the scroll pane

4 Add the scroll pane to the content pane

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 35 of 38

Example

Demonstrate JTree

import javaawt

import javaxswingevent

import javaxswing

import javaxswingtree

ltapplet code=JTreeDemo width=400 height=200gt

ltappletgt

public class JTreeDemo extends JApplet

JTree tree

JLabel jlab

public void init()

try

SwingUtilitiesinvokeAndWait(

new Runnable()

public void run()

makeGUI()

)

catch (Exception exc)

Systemoutprintln(Cant create because of + exc)

private void makeGUI()

Create top node of tree

DefaultMutableTreeNode top = new DefaultMutableTreeNode(Options)

Create subtree of A

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 36 of 38

DefaultMutableTreeNode a = new DefaultMutableTreeNode(A)

topadd(a)

DefaultMutableTreeNode a1 = new DefaultMutableTreeNode(A1)

aadd(a1)

DefaultMutableTreeNode a2 = new DefaultMutableTreeNode(A2)

aadd(a2)

Create subtree of B

DefaultMutableTreeNode b = new DefaultMutableTreeNode(B)

topadd(b)

DefaultMutableTreeNode b1 = new DefaultMutableTreeNode(B1)

badd(b1)

DefaultMutableTreeNode b2 = new DefaultMutableTreeNode(B2)

badd(b2)

DefaultMutableTreeNode b3 = new DefaultMutableTreeNode(B3)

badd(b3)

Create the tree

tree = new JTree(top)

Add the tree to a scroll pane

JScrollPane jsp = new JScrollPane(tree)

Add the scroll pane to the content pane

add(jsp)

Add the label to the content pane

jlab = new JLabel()

add(jlab BorderLayoutSOUTH)

Handle tree selection events

treeaddTreeSelectionListener(new TreeSelectionListener()

public void valueChanged(TreeSelectionEvent tse)

jlabsetText(Selection is + tsegetPath())

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 37 of 38

e) Draw and explain the life cycle of servlet

(Explanation ndash 3 Marks Diagram -1 Marks)

Ans Three methods are central to the life cycle of a servlet

These are init( ) service( ) and destroy( )

They are implemented by every servlet and are invoked at specific times by the server Let

us consider a typical user scenario to understand when these methods are called

First assume that a user enters a Uniform Resource Locator (URL) to a web browser

The browser then generates an HTTP request for this URL This request is then sent to the

appropriate server

Second this HTTP request is received by the web server The server maps this request to

a particular servlet The servlet is dynamically retrieved and loaded into the address space

of the server

Third the server invokes the init( ) method of the servlet This method is invoked only

when the servlet is first loaded into memory It is possible to pass initialization parameters

to the servlet so it may configure itself

Fourth the server invokes the service( ) method of the servlet This method is called to

process the HTTP request You will see that it is possible for the servlet to read data that has

been provided in the HTTP request It may also formulate an HTTP response for the client

The servlet remains in the serverrsquos address space and is available to process any other

HTTP requests received from clients The service( ) method is called for each HTTP request

Finally the server may decide to unload the servlet from its memory The algorithms by

which this determination is made are specific to each server The server calls the destroy( )

method to relinquish any resources such as file handles that are allocated for the servlet

Important data may be saved to a persistent store The memory allocated for the servlet and

its objects can then be garbage collected

A servlet life cycle can be defined as the entire process from its creation till the destruction The

following are the paths followed by a servlet

The servlet is initialized by calling the init () method

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 38 of 38

The servlet calls service() method to process a clients request

The servlet is terminated by calling the destroy() method

Finally servlet is garbage collected by the garbage collector of the JVM

Initialization

(Load Resources)

Services

(Accept Requests)

Destruction

(Unload Resources)

Servlet

Request

Response

Page 31: AJP

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 31 of 38

GraphicsEnvironment t = GraphicsEnvironmentgetLocalGraphicsEnvironment()

allFontList = tgetAvailableFontFamilyNames()

for(int i= 0 ilt allFontsListlength i++)

fonts= fonts + allFontList[i] + ldquo rdquo

gdrawString(msg416)

b) Explain following check box class methods with appropriate example 4

i) Void setLable (String str) ii) Boolean getState ( )

(Explanation of each method-1 Marks Example-2 Marks)

Ans

i) void setLable(String str)

This method is used to set the label of check box

ii) Boolean getState()

This method is used to retrieve the current state of a check box It returns the value either true or

false depends on check box is selected or not

Example

Demonstrate check boxes

import javaawt

import javaawtevent

import javaapplet

ltapplet code=CheckboxDemo width=250 height=200gt

ltappletgt

public class CheckboxDemo extends Applet implements ItemListener

String msg =

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 32 of 38

Checkbox winXP winVista solaris mac

public void init()

winXP = new Checkbox(Windows XP null true)

mac = new Checkbox()

macsetLable(ldquoMac OSrdquo)

add(winXP)

add(mac)

winXPaddItemListener(this)

macaddItemListener(this)

public void itemStateChanged(ItemEvent ie)

repaint()

Display current state of the check boxes

public void paint(Graphics g)

msg = Current state

gdrawString(msg 6 80)

msg = Windows XP + winXPgetState()

gdrawString(msg 6 100)

msg = Mac OS + macgetState()

gdrawString(msg 6 120)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 33 of 38

c) Explain the techniques of session tracking management

(Any four techniques with explanation- 1 Mark each)

Ans Session tracking Techniques

1 User Authorization

Users can be authorized to use the web application in different ways Basic concept is that the

user will provide username and password to login to the application Based on that the user can

be identified and the session can be maintained

2 Hidden Fields

ltINPUT TYPE=rdquohiddenrdquo NAME=rdquotechnologyrdquo VALUE=rdquoservletrdquogt

Hidden fields like the above can be inserted in the webpages and information can be sent to the

server for session tracking These fields are not visible directly to the user but can be viewed

using view source option from the browsers This type doesnrsquot need any special configuration

from the browser of server and by default available to use for session tracking This cannot be

used for session tracking when the conversation included static resources lik html pages

3 URL Rewriting

Original URL httpserverportservletServletName

ewritten URL httpserverportservletServletNamesessionid=7456

When a request is made additional parameter is appended with the url In general added

additional parameter will be sessionid or sometimes the userid It will suffice to track the

session This type of session tracking doesnrsquot need any special support from the browser

Disadvantage is implementing this type of session tracking is tedious We need to keep track of

the parameter as a chain link until the conversation completes and also should make sure that

the parameter doesnrsquot clash with other application parameters

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 34 of 38

4 Cookies

Cookies are the mostly used technology for session tracking Cookie is a key value pair of

information sent by the server to the browser This should be saved by the browser in its space

in the client computer Whenever the browser sends a request to that server it sends the cookie

along with it Then the server can identify the client using the cookie

In java following is the source code snippet to create a cookie

Cookie cookie = new Cookie (ldquouserIDrdquo ldquo7456Prime)

resaddCookie(cookie)

5 Session tracking API

Session tracking API is built on top of the first four methods This is inorder to help the

developer to minimize the overhead of session tracking This type of session tracking is

provided by the underlying technology Lets take the java servlet example Then the servlet

container manages the session tracking task and the user need not do it explicitly using the java

servlets This is the best of all methods because all the management and errors related to

session tracking will be taken care of by the container itself

d) Give sequential steps for JTree in swing with example

(Steps- 2 Marks any small Example- 2 Marks)

Ans Steps for JTree

Atree is a component that presents a hierarchical view of data The user has the ability to

expand or collapse individual subtrees in this display Trees are implemented in Swing by

the JTree class

Here are the steps to follow to use a tree

1 Create an instance of JTree

2 Create a JScrollPane and specify the tree as the object to be scrolled

3 Add the tree to the scroll pane

4 Add the scroll pane to the content pane

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 35 of 38

Example

Demonstrate JTree

import javaawt

import javaxswingevent

import javaxswing

import javaxswingtree

ltapplet code=JTreeDemo width=400 height=200gt

ltappletgt

public class JTreeDemo extends JApplet

JTree tree

JLabel jlab

public void init()

try

SwingUtilitiesinvokeAndWait(

new Runnable()

public void run()

makeGUI()

)

catch (Exception exc)

Systemoutprintln(Cant create because of + exc)

private void makeGUI()

Create top node of tree

DefaultMutableTreeNode top = new DefaultMutableTreeNode(Options)

Create subtree of A

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 36 of 38

DefaultMutableTreeNode a = new DefaultMutableTreeNode(A)

topadd(a)

DefaultMutableTreeNode a1 = new DefaultMutableTreeNode(A1)

aadd(a1)

DefaultMutableTreeNode a2 = new DefaultMutableTreeNode(A2)

aadd(a2)

Create subtree of B

DefaultMutableTreeNode b = new DefaultMutableTreeNode(B)

topadd(b)

DefaultMutableTreeNode b1 = new DefaultMutableTreeNode(B1)

badd(b1)

DefaultMutableTreeNode b2 = new DefaultMutableTreeNode(B2)

badd(b2)

DefaultMutableTreeNode b3 = new DefaultMutableTreeNode(B3)

badd(b3)

Create the tree

tree = new JTree(top)

Add the tree to a scroll pane

JScrollPane jsp = new JScrollPane(tree)

Add the scroll pane to the content pane

add(jsp)

Add the label to the content pane

jlab = new JLabel()

add(jlab BorderLayoutSOUTH)

Handle tree selection events

treeaddTreeSelectionListener(new TreeSelectionListener()

public void valueChanged(TreeSelectionEvent tse)

jlabsetText(Selection is + tsegetPath())

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 37 of 38

e) Draw and explain the life cycle of servlet

(Explanation ndash 3 Marks Diagram -1 Marks)

Ans Three methods are central to the life cycle of a servlet

These are init( ) service( ) and destroy( )

They are implemented by every servlet and are invoked at specific times by the server Let

us consider a typical user scenario to understand when these methods are called

First assume that a user enters a Uniform Resource Locator (URL) to a web browser

The browser then generates an HTTP request for this URL This request is then sent to the

appropriate server

Second this HTTP request is received by the web server The server maps this request to

a particular servlet The servlet is dynamically retrieved and loaded into the address space

of the server

Third the server invokes the init( ) method of the servlet This method is invoked only

when the servlet is first loaded into memory It is possible to pass initialization parameters

to the servlet so it may configure itself

Fourth the server invokes the service( ) method of the servlet This method is called to

process the HTTP request You will see that it is possible for the servlet to read data that has

been provided in the HTTP request It may also formulate an HTTP response for the client

The servlet remains in the serverrsquos address space and is available to process any other

HTTP requests received from clients The service( ) method is called for each HTTP request

Finally the server may decide to unload the servlet from its memory The algorithms by

which this determination is made are specific to each server The server calls the destroy( )

method to relinquish any resources such as file handles that are allocated for the servlet

Important data may be saved to a persistent store The memory allocated for the servlet and

its objects can then be garbage collected

A servlet life cycle can be defined as the entire process from its creation till the destruction The

following are the paths followed by a servlet

The servlet is initialized by calling the init () method

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 38 of 38

The servlet calls service() method to process a clients request

The servlet is terminated by calling the destroy() method

Finally servlet is garbage collected by the garbage collector of the JVM

Initialization

(Load Resources)

Services

(Accept Requests)

Destruction

(Unload Resources)

Servlet

Request

Response

Page 32: AJP

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 32 of 38

Checkbox winXP winVista solaris mac

public void init()

winXP = new Checkbox(Windows XP null true)

mac = new Checkbox()

macsetLable(ldquoMac OSrdquo)

add(winXP)

add(mac)

winXPaddItemListener(this)

macaddItemListener(this)

public void itemStateChanged(ItemEvent ie)

repaint()

Display current state of the check boxes

public void paint(Graphics g)

msg = Current state

gdrawString(msg 6 80)

msg = Windows XP + winXPgetState()

gdrawString(msg 6 100)

msg = Mac OS + macgetState()

gdrawString(msg 6 120)

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 33 of 38

c) Explain the techniques of session tracking management

(Any four techniques with explanation- 1 Mark each)

Ans Session tracking Techniques

1 User Authorization

Users can be authorized to use the web application in different ways Basic concept is that the

user will provide username and password to login to the application Based on that the user can

be identified and the session can be maintained

2 Hidden Fields

ltINPUT TYPE=rdquohiddenrdquo NAME=rdquotechnologyrdquo VALUE=rdquoservletrdquogt

Hidden fields like the above can be inserted in the webpages and information can be sent to the

server for session tracking These fields are not visible directly to the user but can be viewed

using view source option from the browsers This type doesnrsquot need any special configuration

from the browser of server and by default available to use for session tracking This cannot be

used for session tracking when the conversation included static resources lik html pages

3 URL Rewriting

Original URL httpserverportservletServletName

ewritten URL httpserverportservletServletNamesessionid=7456

When a request is made additional parameter is appended with the url In general added

additional parameter will be sessionid or sometimes the userid It will suffice to track the

session This type of session tracking doesnrsquot need any special support from the browser

Disadvantage is implementing this type of session tracking is tedious We need to keep track of

the parameter as a chain link until the conversation completes and also should make sure that

the parameter doesnrsquot clash with other application parameters

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 34 of 38

4 Cookies

Cookies are the mostly used technology for session tracking Cookie is a key value pair of

information sent by the server to the browser This should be saved by the browser in its space

in the client computer Whenever the browser sends a request to that server it sends the cookie

along with it Then the server can identify the client using the cookie

In java following is the source code snippet to create a cookie

Cookie cookie = new Cookie (ldquouserIDrdquo ldquo7456Prime)

resaddCookie(cookie)

5 Session tracking API

Session tracking API is built on top of the first four methods This is inorder to help the

developer to minimize the overhead of session tracking This type of session tracking is

provided by the underlying technology Lets take the java servlet example Then the servlet

container manages the session tracking task and the user need not do it explicitly using the java

servlets This is the best of all methods because all the management and errors related to

session tracking will be taken care of by the container itself

d) Give sequential steps for JTree in swing with example

(Steps- 2 Marks any small Example- 2 Marks)

Ans Steps for JTree

Atree is a component that presents a hierarchical view of data The user has the ability to

expand or collapse individual subtrees in this display Trees are implemented in Swing by

the JTree class

Here are the steps to follow to use a tree

1 Create an instance of JTree

2 Create a JScrollPane and specify the tree as the object to be scrolled

3 Add the tree to the scroll pane

4 Add the scroll pane to the content pane

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 35 of 38

Example

Demonstrate JTree

import javaawt

import javaxswingevent

import javaxswing

import javaxswingtree

ltapplet code=JTreeDemo width=400 height=200gt

ltappletgt

public class JTreeDemo extends JApplet

JTree tree

JLabel jlab

public void init()

try

SwingUtilitiesinvokeAndWait(

new Runnable()

public void run()

makeGUI()

)

catch (Exception exc)

Systemoutprintln(Cant create because of + exc)

private void makeGUI()

Create top node of tree

DefaultMutableTreeNode top = new DefaultMutableTreeNode(Options)

Create subtree of A

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 36 of 38

DefaultMutableTreeNode a = new DefaultMutableTreeNode(A)

topadd(a)

DefaultMutableTreeNode a1 = new DefaultMutableTreeNode(A1)

aadd(a1)

DefaultMutableTreeNode a2 = new DefaultMutableTreeNode(A2)

aadd(a2)

Create subtree of B

DefaultMutableTreeNode b = new DefaultMutableTreeNode(B)

topadd(b)

DefaultMutableTreeNode b1 = new DefaultMutableTreeNode(B1)

badd(b1)

DefaultMutableTreeNode b2 = new DefaultMutableTreeNode(B2)

badd(b2)

DefaultMutableTreeNode b3 = new DefaultMutableTreeNode(B3)

badd(b3)

Create the tree

tree = new JTree(top)

Add the tree to a scroll pane

JScrollPane jsp = new JScrollPane(tree)

Add the scroll pane to the content pane

add(jsp)

Add the label to the content pane

jlab = new JLabel()

add(jlab BorderLayoutSOUTH)

Handle tree selection events

treeaddTreeSelectionListener(new TreeSelectionListener()

public void valueChanged(TreeSelectionEvent tse)

jlabsetText(Selection is + tsegetPath())

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 37 of 38

e) Draw and explain the life cycle of servlet

(Explanation ndash 3 Marks Diagram -1 Marks)

Ans Three methods are central to the life cycle of a servlet

These are init( ) service( ) and destroy( )

They are implemented by every servlet and are invoked at specific times by the server Let

us consider a typical user scenario to understand when these methods are called

First assume that a user enters a Uniform Resource Locator (URL) to a web browser

The browser then generates an HTTP request for this URL This request is then sent to the

appropriate server

Second this HTTP request is received by the web server The server maps this request to

a particular servlet The servlet is dynamically retrieved and loaded into the address space

of the server

Third the server invokes the init( ) method of the servlet This method is invoked only

when the servlet is first loaded into memory It is possible to pass initialization parameters

to the servlet so it may configure itself

Fourth the server invokes the service( ) method of the servlet This method is called to

process the HTTP request You will see that it is possible for the servlet to read data that has

been provided in the HTTP request It may also formulate an HTTP response for the client

The servlet remains in the serverrsquos address space and is available to process any other

HTTP requests received from clients The service( ) method is called for each HTTP request

Finally the server may decide to unload the servlet from its memory The algorithms by

which this determination is made are specific to each server The server calls the destroy( )

method to relinquish any resources such as file handles that are allocated for the servlet

Important data may be saved to a persistent store The memory allocated for the servlet and

its objects can then be garbage collected

A servlet life cycle can be defined as the entire process from its creation till the destruction The

following are the paths followed by a servlet

The servlet is initialized by calling the init () method

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 38 of 38

The servlet calls service() method to process a clients request

The servlet is terminated by calling the destroy() method

Finally servlet is garbage collected by the garbage collector of the JVM

Initialization

(Load Resources)

Services

(Accept Requests)

Destruction

(Unload Resources)

Servlet

Request

Response

Page 33: AJP

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 33 of 38

c) Explain the techniques of session tracking management

(Any four techniques with explanation- 1 Mark each)

Ans Session tracking Techniques

1 User Authorization

Users can be authorized to use the web application in different ways Basic concept is that the

user will provide username and password to login to the application Based on that the user can

be identified and the session can be maintained

2 Hidden Fields

ltINPUT TYPE=rdquohiddenrdquo NAME=rdquotechnologyrdquo VALUE=rdquoservletrdquogt

Hidden fields like the above can be inserted in the webpages and information can be sent to the

server for session tracking These fields are not visible directly to the user but can be viewed

using view source option from the browsers This type doesnrsquot need any special configuration

from the browser of server and by default available to use for session tracking This cannot be

used for session tracking when the conversation included static resources lik html pages

3 URL Rewriting

Original URL httpserverportservletServletName

ewritten URL httpserverportservletServletNamesessionid=7456

When a request is made additional parameter is appended with the url In general added

additional parameter will be sessionid or sometimes the userid It will suffice to track the

session This type of session tracking doesnrsquot need any special support from the browser

Disadvantage is implementing this type of session tracking is tedious We need to keep track of

the parameter as a chain link until the conversation completes and also should make sure that

the parameter doesnrsquot clash with other application parameters

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 34 of 38

4 Cookies

Cookies are the mostly used technology for session tracking Cookie is a key value pair of

information sent by the server to the browser This should be saved by the browser in its space

in the client computer Whenever the browser sends a request to that server it sends the cookie

along with it Then the server can identify the client using the cookie

In java following is the source code snippet to create a cookie

Cookie cookie = new Cookie (ldquouserIDrdquo ldquo7456Prime)

resaddCookie(cookie)

5 Session tracking API

Session tracking API is built on top of the first four methods This is inorder to help the

developer to minimize the overhead of session tracking This type of session tracking is

provided by the underlying technology Lets take the java servlet example Then the servlet

container manages the session tracking task and the user need not do it explicitly using the java

servlets This is the best of all methods because all the management and errors related to

session tracking will be taken care of by the container itself

d) Give sequential steps for JTree in swing with example

(Steps- 2 Marks any small Example- 2 Marks)

Ans Steps for JTree

Atree is a component that presents a hierarchical view of data The user has the ability to

expand or collapse individual subtrees in this display Trees are implemented in Swing by

the JTree class

Here are the steps to follow to use a tree

1 Create an instance of JTree

2 Create a JScrollPane and specify the tree as the object to be scrolled

3 Add the tree to the scroll pane

4 Add the scroll pane to the content pane

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 35 of 38

Example

Demonstrate JTree

import javaawt

import javaxswingevent

import javaxswing

import javaxswingtree

ltapplet code=JTreeDemo width=400 height=200gt

ltappletgt

public class JTreeDemo extends JApplet

JTree tree

JLabel jlab

public void init()

try

SwingUtilitiesinvokeAndWait(

new Runnable()

public void run()

makeGUI()

)

catch (Exception exc)

Systemoutprintln(Cant create because of + exc)

private void makeGUI()

Create top node of tree

DefaultMutableTreeNode top = new DefaultMutableTreeNode(Options)

Create subtree of A

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 36 of 38

DefaultMutableTreeNode a = new DefaultMutableTreeNode(A)

topadd(a)

DefaultMutableTreeNode a1 = new DefaultMutableTreeNode(A1)

aadd(a1)

DefaultMutableTreeNode a2 = new DefaultMutableTreeNode(A2)

aadd(a2)

Create subtree of B

DefaultMutableTreeNode b = new DefaultMutableTreeNode(B)

topadd(b)

DefaultMutableTreeNode b1 = new DefaultMutableTreeNode(B1)

badd(b1)

DefaultMutableTreeNode b2 = new DefaultMutableTreeNode(B2)

badd(b2)

DefaultMutableTreeNode b3 = new DefaultMutableTreeNode(B3)

badd(b3)

Create the tree

tree = new JTree(top)

Add the tree to a scroll pane

JScrollPane jsp = new JScrollPane(tree)

Add the scroll pane to the content pane

add(jsp)

Add the label to the content pane

jlab = new JLabel()

add(jlab BorderLayoutSOUTH)

Handle tree selection events

treeaddTreeSelectionListener(new TreeSelectionListener()

public void valueChanged(TreeSelectionEvent tse)

jlabsetText(Selection is + tsegetPath())

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 37 of 38

e) Draw and explain the life cycle of servlet

(Explanation ndash 3 Marks Diagram -1 Marks)

Ans Three methods are central to the life cycle of a servlet

These are init( ) service( ) and destroy( )

They are implemented by every servlet and are invoked at specific times by the server Let

us consider a typical user scenario to understand when these methods are called

First assume that a user enters a Uniform Resource Locator (URL) to a web browser

The browser then generates an HTTP request for this URL This request is then sent to the

appropriate server

Second this HTTP request is received by the web server The server maps this request to

a particular servlet The servlet is dynamically retrieved and loaded into the address space

of the server

Third the server invokes the init( ) method of the servlet This method is invoked only

when the servlet is first loaded into memory It is possible to pass initialization parameters

to the servlet so it may configure itself

Fourth the server invokes the service( ) method of the servlet This method is called to

process the HTTP request You will see that it is possible for the servlet to read data that has

been provided in the HTTP request It may also formulate an HTTP response for the client

The servlet remains in the serverrsquos address space and is available to process any other

HTTP requests received from clients The service( ) method is called for each HTTP request

Finally the server may decide to unload the servlet from its memory The algorithms by

which this determination is made are specific to each server The server calls the destroy( )

method to relinquish any resources such as file handles that are allocated for the servlet

Important data may be saved to a persistent store The memory allocated for the servlet and

its objects can then be garbage collected

A servlet life cycle can be defined as the entire process from its creation till the destruction The

following are the paths followed by a servlet

The servlet is initialized by calling the init () method

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 38 of 38

The servlet calls service() method to process a clients request

The servlet is terminated by calling the destroy() method

Finally servlet is garbage collected by the garbage collector of the JVM

Initialization

(Load Resources)

Services

(Accept Requests)

Destruction

(Unload Resources)

Servlet

Request

Response

Page 34: AJP

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 34 of 38

4 Cookies

Cookies are the mostly used technology for session tracking Cookie is a key value pair of

information sent by the server to the browser This should be saved by the browser in its space

in the client computer Whenever the browser sends a request to that server it sends the cookie

along with it Then the server can identify the client using the cookie

In java following is the source code snippet to create a cookie

Cookie cookie = new Cookie (ldquouserIDrdquo ldquo7456Prime)

resaddCookie(cookie)

5 Session tracking API

Session tracking API is built on top of the first four methods This is inorder to help the

developer to minimize the overhead of session tracking This type of session tracking is

provided by the underlying technology Lets take the java servlet example Then the servlet

container manages the session tracking task and the user need not do it explicitly using the java

servlets This is the best of all methods because all the management and errors related to

session tracking will be taken care of by the container itself

d) Give sequential steps for JTree in swing with example

(Steps- 2 Marks any small Example- 2 Marks)

Ans Steps for JTree

Atree is a component that presents a hierarchical view of data The user has the ability to

expand or collapse individual subtrees in this display Trees are implemented in Swing by

the JTree class

Here are the steps to follow to use a tree

1 Create an instance of JTree

2 Create a JScrollPane and specify the tree as the object to be scrolled

3 Add the tree to the scroll pane

4 Add the scroll pane to the content pane

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 35 of 38

Example

Demonstrate JTree

import javaawt

import javaxswingevent

import javaxswing

import javaxswingtree

ltapplet code=JTreeDemo width=400 height=200gt

ltappletgt

public class JTreeDemo extends JApplet

JTree tree

JLabel jlab

public void init()

try

SwingUtilitiesinvokeAndWait(

new Runnable()

public void run()

makeGUI()

)

catch (Exception exc)

Systemoutprintln(Cant create because of + exc)

private void makeGUI()

Create top node of tree

DefaultMutableTreeNode top = new DefaultMutableTreeNode(Options)

Create subtree of A

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 36 of 38

DefaultMutableTreeNode a = new DefaultMutableTreeNode(A)

topadd(a)

DefaultMutableTreeNode a1 = new DefaultMutableTreeNode(A1)

aadd(a1)

DefaultMutableTreeNode a2 = new DefaultMutableTreeNode(A2)

aadd(a2)

Create subtree of B

DefaultMutableTreeNode b = new DefaultMutableTreeNode(B)

topadd(b)

DefaultMutableTreeNode b1 = new DefaultMutableTreeNode(B1)

badd(b1)

DefaultMutableTreeNode b2 = new DefaultMutableTreeNode(B2)

badd(b2)

DefaultMutableTreeNode b3 = new DefaultMutableTreeNode(B3)

badd(b3)

Create the tree

tree = new JTree(top)

Add the tree to a scroll pane

JScrollPane jsp = new JScrollPane(tree)

Add the scroll pane to the content pane

add(jsp)

Add the label to the content pane

jlab = new JLabel()

add(jlab BorderLayoutSOUTH)

Handle tree selection events

treeaddTreeSelectionListener(new TreeSelectionListener()

public void valueChanged(TreeSelectionEvent tse)

jlabsetText(Selection is + tsegetPath())

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 37 of 38

e) Draw and explain the life cycle of servlet

(Explanation ndash 3 Marks Diagram -1 Marks)

Ans Three methods are central to the life cycle of a servlet

These are init( ) service( ) and destroy( )

They are implemented by every servlet and are invoked at specific times by the server Let

us consider a typical user scenario to understand when these methods are called

First assume that a user enters a Uniform Resource Locator (URL) to a web browser

The browser then generates an HTTP request for this URL This request is then sent to the

appropriate server

Second this HTTP request is received by the web server The server maps this request to

a particular servlet The servlet is dynamically retrieved and loaded into the address space

of the server

Third the server invokes the init( ) method of the servlet This method is invoked only

when the servlet is first loaded into memory It is possible to pass initialization parameters

to the servlet so it may configure itself

Fourth the server invokes the service( ) method of the servlet This method is called to

process the HTTP request You will see that it is possible for the servlet to read data that has

been provided in the HTTP request It may also formulate an HTTP response for the client

The servlet remains in the serverrsquos address space and is available to process any other

HTTP requests received from clients The service( ) method is called for each HTTP request

Finally the server may decide to unload the servlet from its memory The algorithms by

which this determination is made are specific to each server The server calls the destroy( )

method to relinquish any resources such as file handles that are allocated for the servlet

Important data may be saved to a persistent store The memory allocated for the servlet and

its objects can then be garbage collected

A servlet life cycle can be defined as the entire process from its creation till the destruction The

following are the paths followed by a servlet

The servlet is initialized by calling the init () method

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 38 of 38

The servlet calls service() method to process a clients request

The servlet is terminated by calling the destroy() method

Finally servlet is garbage collected by the garbage collector of the JVM

Initialization

(Load Resources)

Services

(Accept Requests)

Destruction

(Unload Resources)

Servlet

Request

Response

Page 35: AJP

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 35 of 38

Example

Demonstrate JTree

import javaawt

import javaxswingevent

import javaxswing

import javaxswingtree

ltapplet code=JTreeDemo width=400 height=200gt

ltappletgt

public class JTreeDemo extends JApplet

JTree tree

JLabel jlab

public void init()

try

SwingUtilitiesinvokeAndWait(

new Runnable()

public void run()

makeGUI()

)

catch (Exception exc)

Systemoutprintln(Cant create because of + exc)

private void makeGUI()

Create top node of tree

DefaultMutableTreeNode top = new DefaultMutableTreeNode(Options)

Create subtree of A

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 36 of 38

DefaultMutableTreeNode a = new DefaultMutableTreeNode(A)

topadd(a)

DefaultMutableTreeNode a1 = new DefaultMutableTreeNode(A1)

aadd(a1)

DefaultMutableTreeNode a2 = new DefaultMutableTreeNode(A2)

aadd(a2)

Create subtree of B

DefaultMutableTreeNode b = new DefaultMutableTreeNode(B)

topadd(b)

DefaultMutableTreeNode b1 = new DefaultMutableTreeNode(B1)

badd(b1)

DefaultMutableTreeNode b2 = new DefaultMutableTreeNode(B2)

badd(b2)

DefaultMutableTreeNode b3 = new DefaultMutableTreeNode(B3)

badd(b3)

Create the tree

tree = new JTree(top)

Add the tree to a scroll pane

JScrollPane jsp = new JScrollPane(tree)

Add the scroll pane to the content pane

add(jsp)

Add the label to the content pane

jlab = new JLabel()

add(jlab BorderLayoutSOUTH)

Handle tree selection events

treeaddTreeSelectionListener(new TreeSelectionListener()

public void valueChanged(TreeSelectionEvent tse)

jlabsetText(Selection is + tsegetPath())

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 37 of 38

e) Draw and explain the life cycle of servlet

(Explanation ndash 3 Marks Diagram -1 Marks)

Ans Three methods are central to the life cycle of a servlet

These are init( ) service( ) and destroy( )

They are implemented by every servlet and are invoked at specific times by the server Let

us consider a typical user scenario to understand when these methods are called

First assume that a user enters a Uniform Resource Locator (URL) to a web browser

The browser then generates an HTTP request for this URL This request is then sent to the

appropriate server

Second this HTTP request is received by the web server The server maps this request to

a particular servlet The servlet is dynamically retrieved and loaded into the address space

of the server

Third the server invokes the init( ) method of the servlet This method is invoked only

when the servlet is first loaded into memory It is possible to pass initialization parameters

to the servlet so it may configure itself

Fourth the server invokes the service( ) method of the servlet This method is called to

process the HTTP request You will see that it is possible for the servlet to read data that has

been provided in the HTTP request It may also formulate an HTTP response for the client

The servlet remains in the serverrsquos address space and is available to process any other

HTTP requests received from clients The service( ) method is called for each HTTP request

Finally the server may decide to unload the servlet from its memory The algorithms by

which this determination is made are specific to each server The server calls the destroy( )

method to relinquish any resources such as file handles that are allocated for the servlet

Important data may be saved to a persistent store The memory allocated for the servlet and

its objects can then be garbage collected

A servlet life cycle can be defined as the entire process from its creation till the destruction The

following are the paths followed by a servlet

The servlet is initialized by calling the init () method

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 38 of 38

The servlet calls service() method to process a clients request

The servlet is terminated by calling the destroy() method

Finally servlet is garbage collected by the garbage collector of the JVM

Initialization

(Load Resources)

Services

(Accept Requests)

Destruction

(Unload Resources)

Servlet

Request

Response

Page 36: AJP

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 36 of 38

DefaultMutableTreeNode a = new DefaultMutableTreeNode(A)

topadd(a)

DefaultMutableTreeNode a1 = new DefaultMutableTreeNode(A1)

aadd(a1)

DefaultMutableTreeNode a2 = new DefaultMutableTreeNode(A2)

aadd(a2)

Create subtree of B

DefaultMutableTreeNode b = new DefaultMutableTreeNode(B)

topadd(b)

DefaultMutableTreeNode b1 = new DefaultMutableTreeNode(B1)

badd(b1)

DefaultMutableTreeNode b2 = new DefaultMutableTreeNode(B2)

badd(b2)

DefaultMutableTreeNode b3 = new DefaultMutableTreeNode(B3)

badd(b3)

Create the tree

tree = new JTree(top)

Add the tree to a scroll pane

JScrollPane jsp = new JScrollPane(tree)

Add the scroll pane to the content pane

add(jsp)

Add the label to the content pane

jlab = new JLabel()

add(jlab BorderLayoutSOUTH)

Handle tree selection events

treeaddTreeSelectionListener(new TreeSelectionListener()

public void valueChanged(TreeSelectionEvent tse)

jlabsetText(Selection is + tsegetPath())

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 37 of 38

e) Draw and explain the life cycle of servlet

(Explanation ndash 3 Marks Diagram -1 Marks)

Ans Three methods are central to the life cycle of a servlet

These are init( ) service( ) and destroy( )

They are implemented by every servlet and are invoked at specific times by the server Let

us consider a typical user scenario to understand when these methods are called

First assume that a user enters a Uniform Resource Locator (URL) to a web browser

The browser then generates an HTTP request for this URL This request is then sent to the

appropriate server

Second this HTTP request is received by the web server The server maps this request to

a particular servlet The servlet is dynamically retrieved and loaded into the address space

of the server

Third the server invokes the init( ) method of the servlet This method is invoked only

when the servlet is first loaded into memory It is possible to pass initialization parameters

to the servlet so it may configure itself

Fourth the server invokes the service( ) method of the servlet This method is called to

process the HTTP request You will see that it is possible for the servlet to read data that has

been provided in the HTTP request It may also formulate an HTTP response for the client

The servlet remains in the serverrsquos address space and is available to process any other

HTTP requests received from clients The service( ) method is called for each HTTP request

Finally the server may decide to unload the servlet from its memory The algorithms by

which this determination is made are specific to each server The server calls the destroy( )

method to relinquish any resources such as file handles that are allocated for the servlet

Important data may be saved to a persistent store The memory allocated for the servlet and

its objects can then be garbage collected

A servlet life cycle can be defined as the entire process from its creation till the destruction The

following are the paths followed by a servlet

The servlet is initialized by calling the init () method

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 38 of 38

The servlet calls service() method to process a clients request

The servlet is terminated by calling the destroy() method

Finally servlet is garbage collected by the garbage collector of the JVM

Initialization

(Load Resources)

Services

(Accept Requests)

Destruction

(Unload Resources)

Servlet

Request

Response

Page 37: AJP

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 37 of 38

e) Draw and explain the life cycle of servlet

(Explanation ndash 3 Marks Diagram -1 Marks)

Ans Three methods are central to the life cycle of a servlet

These are init( ) service( ) and destroy( )

They are implemented by every servlet and are invoked at specific times by the server Let

us consider a typical user scenario to understand when these methods are called

First assume that a user enters a Uniform Resource Locator (URL) to a web browser

The browser then generates an HTTP request for this URL This request is then sent to the

appropriate server

Second this HTTP request is received by the web server The server maps this request to

a particular servlet The servlet is dynamically retrieved and loaded into the address space

of the server

Third the server invokes the init( ) method of the servlet This method is invoked only

when the servlet is first loaded into memory It is possible to pass initialization parameters

to the servlet so it may configure itself

Fourth the server invokes the service( ) method of the servlet This method is called to

process the HTTP request You will see that it is possible for the servlet to read data that has

been provided in the HTTP request It may also formulate an HTTP response for the client

The servlet remains in the serverrsquos address space and is available to process any other

HTTP requests received from clients The service( ) method is called for each HTTP request

Finally the server may decide to unload the servlet from its memory The algorithms by

which this determination is made are specific to each server The server calls the destroy( )

method to relinquish any resources such as file handles that are allocated for the servlet

Important data may be saved to a persistent store The memory allocated for the servlet and

its objects can then be garbage collected

A servlet life cycle can be defined as the entire process from its creation till the destruction The

following are the paths followed by a servlet

The servlet is initialized by calling the init () method

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 38 of 38

The servlet calls service() method to process a clients request

The servlet is terminated by calling the destroy() method

Finally servlet is garbage collected by the garbage collector of the JVM

Initialization

(Load Resources)

Services

(Accept Requests)

Destruction

(Unload Resources)

Servlet

Request

Response

Page 38: AJP

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous)

(ISOIEC - 27001 - 2005 Certified)

WINTER ndash 13 EXAMINATION

Subject Code 12259 Model Answer Subject Name Advanced Java Programming

____________________________________________________________________________________________________

Page 38 of 38

The servlet calls service() method to process a clients request

The servlet is terminated by calling the destroy() method

Finally servlet is garbage collected by the garbage collector of the JVM

Initialization

(Load Resources)

Services

(Accept Requests)

Destruction

(Unload Resources)

Servlet

Request

Response