You are on page 1of 40

T.Y. B.Sc. (IT) : Sem.

Advanced Java

Time : 2 Hrs.]

Prelim Question Paper

[10]
[5]
[2 mark]

Vi
dy
al
an
ka
r

Q.1
Attempt the following (any TWO)
Q.1(a) Explain Checkbox with example.
(A)
Checkbox
1) Checkbox is a class which is used to create Checkbox in awt.
2) Its constructors are :
Checkbox( );
Checkbox (string s);
Checkbox (string s, Boolean state);
up (b
((b));
Checkbox (string s, Boolean state, Checkbox Group

[Marks : 75

sed to convert a checkbox into a


Here Checkbox Group is a class which is used
radio button.
thods
ds :
Checkbox Group has following two methods
1) get Selected Checkbox ( );
cted
d Checkbo
Checkbox.
It is used to retrieve a selected
Checkbox
eckbox c);
2) Set Selected Checkbox (Checkbox
n appropriate
propriate C
Chec
It is used to select an
Checkbox.
ox :
Methods of Checkbox
i) getLabel( );
It is used to retrieve name of the Checkbox.
el(string s);
ii) setLael(string
ed
d to se
set a ne
It is used
new name on a Checkbox.

iii) getState( );
It is used to retrieve state of the Checkbox.
iv) setState(Boolean State);
It is used to set a new state to a Checkbox.

Write a program to create a following window which consist of five


Checkboxes, by clicking them the appropriate message should get changed.
[3 mark]

1014/BSc/IT/TY/Pre_Pap/2014/Adv. Java

Vidyalankar : T.Y. B.Sc. (IT) Adv. Java

Java

Linux

ST

NS

ASP

Current Selection :
Java : True
Linux : False
ASP : False
ST : False
NS : False

Vi
dy
al
an
ka
r

import java.applet.*;
import java.awt.event.*;
import.java.awt.*;
/* <applet code = test width = 200 height = 30>>
< /applet>/
public class test extends Applet implements
nts
ts
ItemListener
{
Checkbox c1, c2, c3, c4, c5,
public void init( )
{
setLayout (new
new FlowLayout(
FlowLayou ));
))
c1 = new Checkbox (Ja
(Java);
(Java
c2 = new Checkbox (Lin
(Linux);
c3 = new Checkbox ((ASP);
c4 = new Checkbo
Chec
Checkbox
(ST);
c5 = new Ch
Check
Checkbox (NS);
c1.addItem
addIte Listener (this);
d
c2.addItem
Listener (this);
c3.addItem Listener (this);
c4.addItem Listener (this);
c5.addItem Listener (this);
add(c1);
add(c2);
add(c3);
add(c4);
add(c5);
}
public void paint (Graphics g)

Prelim Paper Solution

{
string a = Current Selection;
string b = Java + c1.getState( );
string c = Linux + c2.getState( );
string d = ASP + c3.getState( );
string e = ST + c4.getState( );
string f = NS + c5.getState( );
g.drawString
g.drawString
g.drawString
g.drawString
g.drawString
g.drawString

(a, 10, 120);


(b, 10, 130);
(c, 10, 140);
(d, 10, 150);
(e, 10, 160);
(f, 10, 170);

Vi
dy
al
an
ka
r

}
public void itemStateChanged (Itemevent
event
nt ie);
{
repaint( );
}

del.
Q.1(b) Explain delegation event model.
[5]
el
(A)
Delegation event model
del consist of follo
f
Delegation event model
following three concepts which are used for
handling the eventt :
[4 mark]
1) Event
ion : Event is also
a
Definition
object.
ent is de3fined
de3fin
i) Event
as the object which describe the state change of
ticul source.
s
the particular
an be
b occur on multiple conditions like clicking on a button.
ii) Event can
Selecting a Checkbox, Scrolling the scrollbars, etc.
2) Source
i) Definition : Source are the objects which generates a particular
event.
ii) If we want a particular source should generate a particular event, in
that case that source should get registered with a specific event
using following method :
addTypeListener (TypeListener tl);

Vidyalankar : T.Y. B.Sc. (IT) Adv. Java

3) EventListeners
i) EventListeners are those interfaces which contains different
methods which are used or get override to receive the event and
take the corrective action on that event.
ii) ActionListener, ItemListener, MouseListener, etc. are different
interfaces which can be used to override their methods.

Vi
dy
al
an
ka
r

Event Handling
[1 mark]
Even the operations which are occurred when the components will get clicked
or selected to handle each type of event java develops different event
classes.
Each event class has its specific condition and when that condition will occur
the appropriate event will get generated. When the
event will get generated
e ev
eive that
th
the event object will get throw and to receive
object different
receiving method can be used.
vent only when it iis registered for
A component can generated a particular event
that particular event.
ss.
Q.1(c) Write a short note on Inner class.
(A)
Inner Class
Example :
import java.awt.*;
import java.awt.event.*;
*;

[5]
[4 mark]

class testevent extends frame im


implements
ActionListener
tener
ener
{
testevent(
ent(
nt( )
{
setLayoutt ((new FlowLayout( ));
Label l = new Label (select a color :);
Button b1 = new Button (Red);
Button b2 = new Button (Green);
Button b3 = new Button (Blue);
b1.addActionListener (this);
b2.addActionListener (this);
b3.addActionListener (this);
addWindowListener (new demo ( ));
add (l);

Prelim Paper Solution

add (b1);
add (b2);
add (b3);
setSize (200, 300);
setTitle (SSS);
setVisible (true);
}
public void actionPerformed (ActionEvent ae);
{
String s = ae.getActionCommand( );

Vi
dy
al
an
ka
r

Color c1 = new Color (255,0,0);


Color c2 = new Color (0,255,0);
Color c3 = new Color (0,0,255);

if (s.equals (Red))
{
setBackground (c1);
}
Green))
en ))
else if (s.equals (Green))
{
ground
round (c2);
setBackground
else
{
setBackgro
setBackground (c3);
}
}
emo e
class demo
extends WindowAdapter
{
public void WindowCloasing (WindowEvent we);
{
System.exit (0);
}
}
public static void main (string a[ ])
{
testevent t = new testevent( );
}

}
5

Vidyalankar : T.Y. B.Sc. (IT) Adv. Java

Inner Class
[1 mark]
1) Inner class is used when we want our main class to get derived from
Frame class.
2) In that case we create a new class called as inner class, place it inside
the main class and derived it from the appropriate adapter class, so that
we can override a specific method from that adapter class.
Q.1(d) Explain Adapter Class with example.
(A)
Adapter Class
Example :
import java.awt.*;
import java.awt.event.*;

[5]
[3 mark]

Vi
dy
al
an
ka
r

class testevent extends WindowAdapter


implements ActionListener
{
Frame f;
testevent( )
{
f = new Frame( );
f.setLayout(new FlowLayout(
wLayout( ))
));
el (select a color:);
co
Label l = new Label
Button b11 = new Button
Butto (Red);
(
on b2 = new Button
Butto (Green);
But
Button
Button
Button (Blue);
utton
tton b3 = new Bu

b1.addActionListener (this);
b1.addActionL
b1.addA
b2.addActionListener
(this);
2.addAct
dA
b3.addActionListener
(this);
f.addWindowListener (this);
f.add(l);
f.add(b1);
f.add(b2);
f.add(b3);
f.setSize (200, 300);
f.setTitle (SSS);
f.setVisible (true);

}
6

Prelim Paper Solution

Public void actionPerformed (ActionEvent ae)


{
String s = ae.getActionCommand( );
Color c1 = new Color (255,0,0);
Color c2 = new Color (0,255,0);
Color c3 = new Color (0,0,255);

Vi
dy
al
an
ka
r

if (s.equals (Red))
{
f.setBackground (c1);
}
else if (s equals (Green))
{
f.setBackground (c2);
}
else
{
c3);
f.setBackground (c3);
}

Public void WindowClosing


we)
ndowClosing
Closing (WindowEvent
(Wind
(W
{
System.exit
(0);
tem.exit (0)
}
Pubic
bic
c Static void main (String a[ ])
{
test ev
event t = new testevent( );
}

}
Adapter Class
[2 mark]
1) Adapter class is used to overcome the problem of writing different
methods of empty implementation.
2) Normally if we use event listener, then we need to override all its
methods.
3) If we want to override only certain specific method, then in that case
EventListener can be replaced with EventAdapter Class.

Vidyalankar : T.Y. B.Sc. (IT) Adv. Java

EventClass
ActionEvent
ItemEvent
MouseEvent
KeyEvent
ComponentEvent
ContainerEvent
AdjustmentEvent
TextEvent
WindowEvent
MouseWheelEvent

EventListener
ActionListener
ItemListener
MouseListener
KeyListener
ComponentListener
ContainerListener
AdjustmentListener
TextListener
WindowListener
MouseWheelListener

EventAdapter Class
ActionAdapter
ItemAdapter
MouseAdapter
KeyAdapter
ComponentAdapter
ContainerAdapter
AdjustmentAdapter
TextAdapter
WindowAdapter
MouseWheelAdapter
[10]
[5]

Vi
dy
al
an
ka
r

Q.2
Attempt the following (any TWO)
ng Component.
Compo
Com
Q.2(a) Differentiate between AWT component and Swing
(A)
AWT Components
1) AWT components are non java
a
components
2) They
are
platform
dependent
endent
components
3) They are non decorative components
mponents
4) They are normally
ally
ly rectangular in
i
shape
5) Those are
e considered as heavy
omponents
weight components
6) They are
re not used to perform
erations
tion
complex operations
7) Those classes are present in java.awt
package

Swing Com
Components
Swing components
compone
comp
are pure java
componen
components
They are
ar
platform independent
com
compon
components
The
They
T
are decorative. We can even
place an image on a component
We can create different shape
components
Those are considered as light weight
components
They are used to perform complex
operations
Those classes are present in
javax.swing package

Q.2(b) Explain JOptionPane in detail.


[5]
(A)
JOptionPane
1) It is use to create Option Pane or pop-up messages in case of swing.
[1 mark]
2) It provides different static methods which are use to display different
pop-ups.
[4 mark]
(a) ShowMessageDialog (Parent Window Object, String message)
It is used to create a simple popup message with "OK" button.

Prelim Paper Solution

Message
OK

(b) ShowConfirmDialog(String message);


It is used to display a confirmation message with 3 buttons "YES",
"NO" and "CANCEL".
Message
No

Cancel

Vi
dy
al
an
ka
r

Yes

e);
(c) ShowInputDialog(String message);
Message
sage

OK
K

Cancel

It is used to display a po
pop-up which is used to accept an input from
pop-u
the userss

c
Q.2(c) Write a program to create
a combobox, and add different items in
that combobox
accepting them from user.
obox
box by accep
(A)
import java.awt.*;
wt.*;
eve
import java.awt.event.*;
import javax.swing.*;
class combo extends JFrame implements ActionListener
{
JComboBox jc;
JButton jb;
JTextField jt;

[5]

combo()
{
Container c=getContentPane();
c.setLayout(new FlowLayout());
9

Vidyalankar : T.Y. B.Sc. (IT) Adv. Java

jc=new JComboBox();
jb=new JButton("Add");
jt=new JTextField(10);
jb.addActionListener(this);
c.add(jc);
c.add(jt);
c.add(jb);

Vi
dy
al
an
ka
r

setSize(500,500);
setVisible(true);
LOSE);
E);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
e)
public void actionPerformed(ActionEvent ae)
{
String s=jt.getText();
jc.addItem(s);
}
public static void main(String
ng args[])
gs[])
{
combo cb=new combo();
);
}
}

Q.2(d) Write a program to cr


create a table and perform addition and removal
of rows by accepting
acceptin row no, using 2 buttons "Add" and "Remove".
(A)
import java.awt.*;
wt.*;
ng
import javax.swing.*;
import java.awt.event.*;
import javax.swing.table.*;

[5]

class table extends JFrame implements ActionListener


{
JScrollPane jsp;
DefaultTableModel dt;
JTable j;
JButton jb1,jb2;
table()
10

Prelim Paper Solution

{
Container c=getContentPane();
c.setLayout(new BorderLayout());
jb1=new JButton("Add Row");
jb2=new JButton("Remove Row");
String data[][]={{"1","sss","dadar"},{"2","akn","sion"},{"3","sdw","thane"}};
String colheads[]={"Id","Name","Address"};
dt=new DefaultTableModel(data,colheads);
j=new JTable(dt);
jsp=new JScrollPane(j);

Vi
dy
al
an
ka
r

jb1.addActionListener(this);
jb2.addActionListener(this);

c.add(jsp,BorderLayout.CENTER);
c.add(jb1,BorderLayout.NORTH);
c.add(jb2,BorderLayout.SOUTH);
H);
setSize(1000,500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ation(JFrame.EXIT
JFrame.E
}
public void actionPerformed(ActionEvent
ae)
onPerformed(Actio
nPerformed(Ac
{
ae.getActionC
ae.getActionComma
String s=ae.getActionCommand();

if(s.equals("Add
dd Row"))
Row")
{
String a=JOptionPane.showInputDialog("Enter row number");
int m=Integer.parseInt(a);
String b=JOptionPane.showInputDialog("Enter Id");
String c=JOptionPane.showInputDialog("Enter Name");
String d=JOptionPane.showInputDialog("Enter Address");
String e[]={b,c,d};
dt.insertRow(m,e);
}
else
{
String f=JOptionPane.showInputDialog("Enter row number to be deleted");
11

Vidyalankar : T.Y. B.Sc. (IT) Adv. Java

int n=Integer.parseInt(f);
dt.removeRow(n);
}
}
public static void main(String args[])
{
table t=new table();
}
}
Q.3
Attempt the following (any TWO)
Q.3(a) Explain RequestDispatcher with example.
(A)
RequestDispatcher

[10]
[5]
[ 2 mark]

Vi
dy
al
an
ka
r

username :
password :

Login

<html>
<head>
n </title>
title> </head>
</he
<title> Servlet Application
<body>
<form method = "post"
ost"
t" action = "test">
"t
"test
<b> Username </b>
b
b>
<input type = "text"
text" name = "u" value = " " size = "10">
e = "password"
"password nam
<input type
name = "p" value = " " size = "10">
<input type = "submit"
value = "login">
"subm va
</form>
</body>
</html>

//test.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class test extends HttpServlet
{
public void doPost(HttpServletRequest Request,
HttpServletResponse Response) throws IOException
ServletException
12

Prelim Paper Solution

}
}

Vi
dy
al
an
ka
r

response.setContentType("text/html?);
PrintWriter out = response.getWriter( );
String n = request.getParameter("u");
String p = request.getParameter("p");
out.print ln("H \ }} ");
if((n.equals("admin")) && (p.equals("admin")))
{
RequestDispatcher rd1 = request.getrequestDispatchers
("Welcome");
rd1.include(request, response);
}
else
{
RequestDispatchers rd2 = request.getRequestDispatchers
uest.getReques
t.getRequ
("Errors");
forward(request,
ward(reques rresponse);
rd2.forward(request,
}
out.close( );

Request Dispatchers
[2 mark]
1) Any Servlet application
created as a request dispatcher by using
pplication
ication can b
be c
ethod
following method
equestDispatcher(
questDispatcher( );
getRequestDispatcher(
stDispatchers is a class which is there inside the package
stDispatcher
2) RequestDispatchers
ervlet
javax.servlet
spatche can be created for following 2 reasons.
3) RequestDispatcher
de the contains of RequestDispatcher into the current
(a) To include
Servlet application for that purpose we are using include( ); of
RequestDispatcher.
(b) To forward the control from current servlet application to any
requestDispatcher servlet. For that purpose we are using forward(
); of RequestDistpacher.
Q.3(b) Explain session management with its techniques.
[5]
(A)
Session management techniques
1) Session Management is used by Servlet to store information about a
particular client.

13

Vidyalankar : T.Y. B.Sc. (IT) Adv. Java

Vi
dy
al
an
ka
r

2) When a new client sends a request for a Servlet, Servlet will create a
session Memory to store a transaction information about a that
particular client.
3) Apart from that Servlet also generate a Session ID to keep a trap for
that session Memory.
4) Servlet Sends the SessionID to the client side. Application which will
get stored inside the client machine.
5) Next time if the Same client wants to do the transaction with the same
Servlet, then client will send request packet with session ID.
6) By retrieving the session ID, Servlet updates Session Memory for new
transaction generater new SessionID & send it to the client.
7) To perform this mechanism following three techniques can be used.
(a) Hidden formField :
sion ID to the Servlet.
x It is used by the client to send a Session
et can
an read it & Hence called as
x It is in Hidden form & only Servlet
Hidden form field.
(b) Url rewriting :
nID to the client.
clie
x It is used to send SessionID
sionID inside
insi
rresponse packet or it will
x Servlet can put the SessionID
oken to send a Se
generate a special token
SessionID
(c) Cookies :
okie, a Servl
Servlet an
a send SessionID to the client
x By using cookie,
machine.
Serv
x For thatt purpose Servlet
will create a new cookie for Session ID &
dss it to the client
w
sends
client, with
the help of response packet Header.
For example,
e,
rogram to create
cr
Write a program
a client side application which is used to accept
Roll No. and Name from user. It should also have a button named "display"
licked should send those value to the servlet. Servlet
which when clicked
application should accept them display them on web browser.
Roll No. :
Name :
Display
client side application
<html>
<head>
<title> Servlet Application </title> </head>
<body>
14

Prelim Paper Solution

<form method = "get" action = "test">


<b> Roll No. </b>
<input type = "number" name = "r" value = " " size = "10">
<b> Name </b>
<input type = "text" name = "n" value = " " size = "10)>
<input type = "submit" value = "Display">
</form>
</body>
</html>

Vi
dy
al
an
ka
r

server side application


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class test extends HttpServlet
{
HttpServlet
HttpSer
public void doGet(HttpServletRequestt req, HttpServletResponse
res)
et Exception
throws IOException, Servlet
{
xt/html");
html");
res.setContentType("text/html");
PrintWriter pw = res.getWriter(
getWriter(
etWriter( );
arseInt(req.getPa
eInt(req.ge
int roll = Integer.parseInt(req.getParameter("r"));
eq.getParameter("
getParamet
String name = req.getParameter("n");
pw.println ("The
The roll no. =" + roll);
ro
n("<br>");
br>");
pw.println("<br>");
ntln("The name =" + name);
pw.println("The
HttpSession
pSession
ession hs = rreq.getSession(true);
req.
(hs.isNew(
hs.isNew( ))
if(hs.isNew(
{
printl
pw.println("Session
is new");
}
else
{
pw.println("session is old");
pw.println("session id =" + hs.getId( ));
pw.println("Creationtime =" + hs.getId( ));
pw.println("Lastaccessed time =" + hs.getLastAccessedTime");
}
pw.cloase( );
}
}

15

Vidyalankar : T.Y. B.Sc. (IT) Adv. Java

[5]

Vi
dy
al
an
ka
r

Q.3(c) Develop simple servlet question-answer application to demonstrate


use of HttpServletRequest and HttpServletResponse interfaces.
(A)
//index.jsp
<html>
<head>
<title>Welcome To SSS's Quiz Contest</title>
</head>
<body>
<h1 align="center">Welcome To SSS's Quiz Contest</h1>
<form method="post" action="test">
<b>Who developes Java</b>
<br>
<input type="radio" name="java" value="d">Dennis
enn Ritchie
">Bjarne
arne Straunstrup
S
<input type="radio" name="java" value="b">Bjarne
<input type="radio" name="java" value="j">James
="j">James
>James Goslin
Gosl
G
<br>
mit">
t">
<input type="submit" value="Submit">
</form>
</body>
</html>
//test.java
import java.io.*;
t.*;
*;
import javax.servlet.*;
vlet.http.*;
import javax.servlet.http.*;

public class test


st extends H
Http
HttpServlet
{
id doPost(
doP
public void
doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try
{
String answer=request.getParameter("java");
if((answer.equals("d"))||(answer.equals("b")))
{
out.println("Wrong Answer");
}
else
16

Prelim Paper Solution

{
out.println("Correct Answer");
}
}
finally
{
out.close();
}
}
}

Vi
dy
al
an
ka
r

Q.3(d) Develop servlet application of basic calculator (+, , *, /) using [5]


HttpServletRequest and HttpServletResponse.
(A)
//index.jsp
<html>
<head>
tent="text/
<meta http-equiv="Content-Type" content="text/htm
content="text/html;
charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
n="calculat
<form method="post" action="calculate">
or</h1>
h1>
<h1>Simple Calculator</h1>
<hr>
<b>Enter First Number</b>
e="number"
="number" name="
name
<input type="number"
name="n1" value="" size="2">
<p>
ter Second N
Numb
<b>Enter
Number</b>
type="n
<input type="number
type="number" name="n2" value="" size="2">
<p>
per
<b>Enter Operation</b>
<input type="text" name="op" value="" size="2">
<p>
<input type="submit" value="Calculate">
</form>
</body>
</html>
//calculate.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
17

Vidyalankar : T.Y. B.Sc. (IT) Adv. Java

Vi
dy
al
an
ka
r

public class calculate extends HttpServlet


{
public void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
int a=Integer.parseInt(request.getParameter("n1"));
int b=Integer.parseInt(request.getParameter("n2"));
String op=request.getParameter("op");
int c;
if(op.equals("+"))
{
c=a+b;
}
else if(op.equals("-"))
{
c=a-b;
}
"*")))
else if(op.equals("*"))
{
c=a*b;
}
else
{
c=a/b;
a/b;
/b;
}
n(
out.println("The
Result is "+c);
} finally {
out.close();
}
}
}

18

Prelim Paper Solution

Q.4
Attempt the following (any TWO)
[10]
Q.4(a) Write a program using Prepared Statement to add record in student [5]
table containing roll number and name.
(A)
import java.sql.*;
public class Main
{

Vi
dy
al
an
ka
r

public static void main(String[] args)


{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection c = DriverManager.getConnection("jdbc:odbc:sss");
n( j
ment("inse
t("i
PreparedStatement ps=c.prepareStatement("insert
into student
values(?,?)");
ps.setInt(1,10);
ps.setString(2,"SSS");
ps.execute();
ps.close();
c.close();
}
catch(Exception e)
{
System.out.println("Exception
occur");
println("Exception
rintln("Excep
}
}
}
cter quo
Q.4(b) Explain character
quoting convention in JSP
[5]
ng Conventions
(A)
Character Quoting
Because certain character sequences are used to represent start and stop
tags, the developer sometimes need to escape a character so the JSP engine
does not interpret it as part of a special character sequence.
In scripting element, if the characters %> needs to be used, escape the
greater than sign with a backslash:
<% String message = This is the %\ ! message ; %>
The backslash before the expression acts as an escape character, informing
the JSP engine to deliver the expression verbatim instead of evaluating it.

19

Vidyalankar : T.Y. B.Sc. (IT) Adv. Java

There are a number of special constructs used in various cases to insert


characters that would otherwise be treated specially, they are as follows :
Escape
Characters
\'
\ ''
\\
%\>
<\%
\$

Description
A single quote in attribute that uses single quotes.
A double quote in an attribute that uses double quotes.
A backslash in an attribute that uses backslash.
Escaping the scripting end tag with a backslash.
Escaping the scripting start tag with a backslash.
Escaping the dollar sign [dollar sign is used to start an EL
expression] with a backslash

Vi
dy
al
an
ka
r

Example
<% String message = Escaping \ single
e quote;
uote; %>
ouble quote; %
%>
<% String message = Escaping \ double
<% String message = Escaping \ \ backslash; %>
%
<% String message = Escaping
end tag; %>
ng % \ > scripting
script
e
aping
ng < \ % scriptin
scr
<% String message = Escaping
scripting start tag; %>
<% String message = Escaping
sign
; %>
Escaping
scaping \$ dollar
dol
s
caping
ing quote cha
As an alternative to escaping
characters, the character entities
&apos; and &quot; can also be used.
ion in JDBC.
Q.4(c) Explain transaction
[5]
(A)
c.setAutoCommit
(false);
mit (false
s.execut("insert
value }} )
nsert into employ
emp
delete from em
s.execut("delete
employ }} )
ate("updat
("up
s.executUpdate("update
employ }} )
c.commit( );
ResultSet rs = s.executeQuery("select * from employee");
i) In case of JDBC the default value of commit protocol is true.
ii) Which means all the transaction will get perform in the same order as
they are written in the JDBC application.
iii) We can make the value of commit protocol as false with the help of
following method
c.setAutoCommit (false);
iv) It means all the transaction written after this will be kept hold and only
will get performed when we called the commit protocol.
v) All the transaction because of this will execute simultaneously at a same
time.
20

Prelim Paper Solution

vi) The major problem of using this transaction mechanism is that when 2
operations will get perform on the same record, sometime it will
generate deadlock condition.
vii) To overcome this deadlock transaction mechanism uses rollback concept.
viii)Because of rollback all the transaction will get undone and the operation
will get nullified.

Vi
dy
al
an
ka
r

Q.4(d) Explain life cycle of JSP.


[5]
(A)
LIFECYCLE OF JSP
1) Instantiation : When a web container receives a JSP request, it checks
for the JSPs servlet instance. If no servlet instance is available then
the web container creates the servlet instance using following steps.
(a) Translation :
x Web container translates (converts)
into a servlet
s) the
he JSP code
c
code.
SP everything is a servlet.
x After this stage there is no JSP
ss instead
nstead of a
an ht
x The resultant is a java class
html page (JSP page)
(b) Compilation :
et iss compiled tto vvalidate the syntax.
x The generated servlet
enerate
nerate class file to run on JVM.
x The compilation generate
(c) Loading :
ed byte code is loaded in web container i.e. Web
x The complied
server.

Client

Request
ues

If not
initi
initialized
Translation
Already
Initializ

Response

Compilation

Initialization

Loading

Instantiation

Request Processing

Destruction

(d) Instantiation:
x In this step, instance of the servlet class is created, so that it
can handle request.

21

Vidyalankar : T.Y. B.Sc. (IT) Adv. Java

(e) Initialization :
x It can be done using jspInit( ). This is one time actively and after
initialization, the servlet is ready to process requests.
2) Request Processing : Entire initialization process is done to make the
servlet available in order to process the incoming request.
jspService( ) is the method that actually process the request.
3) Destroy : Whenever the server needs memory, the server removes the
instance of the servlet.
The jspDestory( ) can be called by the server after initialization and before
or after request processing.
[10]
[5]

Vi
dy
al
an
ka
r

Q.5
Attempt the following (any TWO)
Q.5(a) Explain JSF life cycle.
(A)
JSF life cycle

Response
e
plete
complete

Faces
response

Restore
view

Apply
request
values

Process
cess
event

Process
Validation

Response
complete

Process
event

e
Reader response

Response
Resp
Res
ponse co
complete
com
plete

Faces
response

Render
response
e

Process
rocess
Event

Invotie
application

Conversion
C
onvers
error/render

Response complete

Process
Event

Update
model
values

Validation error /response

JSP lifecycle consist of following phases


1. Restore view :
i) In this face the appropriate view are created for a particular
request and will get sotre in Facescontext object.
ii) Also different component will get retrieve from webserver and
component tree can be generated.
2. Apply request values
i) In this the local values of the components will get changed with the
request value i.e. request will get apply on component tree.

22

Prelim Paper Solution

4.

5.

6.

Vi
dy
al
an
ka
r

3.

ii) If any error occur then the error message will get store inside
Facescontext object.
Process validation
i) In this the local values of the component will get checked with the
validation rule registered for a components.
ii) If the rules does not match then the error message will get render
to a client.
Update model values
i) In this face the components from component tree will update the
component present inside the webserver.
ii) It is also called as baching a bear.
Invest application
i) In this face the application will get invest
st or
o execute to create
responses.
tsing of thos
tthose page will also
ii) Also if they are multiple pages then lintsing
get done in this phase.
Render response
ponses
ses will get re
In this phase the generated responses
render i.e. provided to a
client as a response.

Q.5(b) Explain advantages of EJB..


[5]
(A)
Advantages of EJB
endent, EJB
E
Apart from platform independent,
has following advantages.
n business log
logic : In industry because of use EJB the
x More focus on
a
developmentt time of on application
can be reduce, so that the
tion
on can able to more
mo focus on business logic.
organization
ble Componen
Components : EJB
E
x Portable
components creted inside one web server can
d in another
anot
we server.
be used
web
x Reusable compone
component : We can create on EJB only once and by storing it
b server we can use it multiple time.
inside the web
x Reduces execution time: As EJB component are readymade component
the user need not to create this component every time, which reduces
overall execution time.
x Distributed deployment: EJBs can be sue in distributed architecture
where the EJBs can get store in multiple system in distributed manner.
x Interoperability : EJBs can be use by multiple types of request, because
the EJB has concept of CORBA (common object request brother
architecture) which converts different type of request into common
format.

23

Vidyalankar : T.Y. B.Sc. (IT) Adv. Java

Q.5(c) Explain different types of EJBS.


[5]
(A)
(i) Session bins
Session bins are the beans which can requested by particular client i.e.
they can perform their work only after getting the client request.
Characteristic of session bean
(1) They are short live beans
(2) They are transaction oriented
(3) They cannot be created by using a data from database, but they
have the ability to make changes in database.
(4) They can be stateful or stateless bean.
(5) They are synchronous in nature.
(6) They can be accessed with the help of home
e interface.
int

Vi
dy
al
an
ka
r

Types of session bean


(1) Statefull session bean
store the conversational
Those are the bean which iss use to stor
information between the client
ent & server for that they maintain a
ore
e the informatio
inform
state in which they can store
information. Because of that state,
the processing of this bean are slower.
slowe
n bean
an
(2) Stateless session
e bean
an which is not use to store the conversational
Those are the
n between the client
clie & server for that they not maintain a
information
hich they can Be
Beca
state which
Because of that.
ngleton Session
Sessi bean
be
(3) Singleton
a requested
req
Thiss bean are
by multiple client simultaneously.
ve bean
(ii) Message driven
Message driven bean can be use by generating the appropriate event or a
message by java messaging system.
Characteristics
(1) They are short live beans
(2) They are transaction oriented.
(3) They cannot be created by using a data from database, but they
have the ability to make changes in database.
(4) They are stateless.
(5) They are asynchronous.
(6) They does not use any home interface.
24

Prelim Paper Solution

Q.5(d) Write a program to create a login application using JSF with builtin
validation.
(A)
//index.xhtml
<?xml version='1.0' encoding='UTF-8' ?>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>Login</title>
</h:head>
<h:body>
<h:form>
<h1>The Login Form</h1>

[5]

Vi
dy
al
an
ka
r

<h:outputLabel for="txtName">
<h:outputText value="Name" />
</h:outputLabel>

<h:inputText id="txtName"" value="#{user.na


value="#{user.name}">
alue="#{use
rn="[a-z]+"/>
n="[a-z]+"/>
<f:validateRegex pattern="[a-z]+"/>
</h:inputText>
<h:outputLabell for="txtPassword
for="txtPassword">
="txtPassw
<h:outputText
value="Password" />
ext
xt value="Passwor
value="Pass
utLabel>
</h:outputLabel>

<h:inputSecret
value ="#{user.password}">
:inputSecret id="txtPassword"
id="t
<f:validateRegex
pattern="(.{6,20})" />
validateRegex
alidateR
</h:inputSecret>
putSecre
<h:commandButton value="Login" action="#{user.verifyUser}"/>

</h:form>
</h:body>
</html>
//userbean.java
import javax.faces.bean.*;
@ManagedBean(name="user")
public class userbean
25

Vidyalankar : T.Y. B.Sc. (IT) Adv. Java

{
String name;
String password;

public void setname(String n)


{
name = n;
}
public String getname()
{
return name;

Vi
dy
al
an
ka
r

}
public void setpassword(String p)
{
password = p;
}
public String getpassword()
ord())
{
return password;
rd;

public String
ring verifyUser()
{
if(name.equals("admin")
&& password.equals("sssssss"))
me.equals("adm
e.equals
{
ess
return "success";
}
else
{
return "failure";
}
}
}

26

Prelim Paper Solution

Q.6
Attempt the following (any TWO)
Q.6(a) Explain MVC architecture.
(A)
MVC architecture

[10]
[5]

Event

Controller

View

Vi
dy
al
an
ka
r

Model

multiple views of the same


MVC architecture is normally use to create mult
application.
S is to separate
sep
separat application logic with
2. The basic intention of MVS
presentation logic.
C contains
ntains follo
followin
3. The architecture of MVC
following 3 components.
ent a data or collection
colle
x Model: It represent
of multiple data use in MVC.
e.g. database
he component
componen wh
x View: It is the
which is responsible for creating multiple
applicat
applic
views of the some application.
sp
p
e.g. jsp
ntroller: This com
x Controller:
component is sue to control model as well as view.
e.g.. Servlet
4. Working
i) Wheneverr on event will occur for the use of MVC architecture, the
event or the request has been accepted by controller.
ii) Controller forward that request to model component, where model
component retrives the appropriate date use for handling the data
and send that data to controller.
Controller forwards that data to view which will create multiple views
from that data.
Sometimes the data accepted by view is not sufficient to create the
multiple views in that case view can directly interact with model for
getting that additional data.

1.

27

Vidyalankar : T.Y. B.Sc. (IT) Adv. Java

Q.6(b) Explain any 3 core components of struts framework.


(A)
Core Components of struts Framework
http
request

Interception

Filter
dispatcher
Reads
configurator

Client

Invoke
return

Action

dispatchers

Result

Struts Framework is use to support MVC architec


architecture
and hence 3
chit
components of struts are resemble with MVC
architecture.
C architectur
architec
i) Filter dispatcher will behave like controller
ontroller
ii) Action will work as Model
iii) Result and Result type will work
ork as a view
owing
ng core component
compon
co
Struts framework contain following
contro
co
i) Filter dispatcher: It behave like controller
which is use to accept
ent.
request from the client.
Once it accept the request it w
will search an appropriate action
ard the reque
re
component to forward
request.
ing
g a particular
particu
For selecting
action component, Struts.xml helps
spatcher.
Filterdispatcher.
Once itt identifies appr
apprompriate action, Filterdispatcher invoke the
tion by sendi
th request.
action
sending the
tion:
on: Action
Ac
ii) Action:
will behave like model and hence it has the
priate dt
appropriate
dta use to crete multiple views.

Vi
dy
al
an
ka
r

1.

Struts
Xml

[5]

Q.6(c) Explain Structure of hibernate.cfg.xml file (Hibernate configuration


file).
(A) <?xml version=1.0 encoding=UTF8?>

[5]

<hibernateconfiguration>
<sessionfactory>
<property name=hibernate.dialect>
org.hibernate.dialect.MySQLDialect</property>

28

Prelim Paper Solution

property name=hibernate.connection.driver_class>
com.mysql.jdbc.Driver</property>
<property name=hibernate.connection.url>
jdbc:mysql://localhost/DBname</property>
<property name=hibernate.connection.username>
root</property>
<property name=hibernate.connection.password>
root</property>
<mapping resource=guestbook.hbm.xml/>

Vi
dy
al
an
ka
r

</sessionfactory>
</hibernateconfiguration>

Elements:
e name of the
th SQL dialect for the
hibernate.dialect It represents the
database
r_class
ass
 It rrepre
hibernate.connection.driver_class
represents the JDBC driver class for
the specific database
ion.url It represents
ion.url
repr
represe
hibernate.connection.url
the JDBC connection to the database
onnection.use
onnection.usernam
hibernate.connection.username
It represents the user name which is used to
he
e database
datab
connect to the
on
hibernate.connection.password
It represents the password which is used to
connect to the database
guestbook.hbm.xml It represents the name of mapping file

29

Vidyalankar : T.Y. B.Sc. (IT) Adv. Java

[5]

Vi
dy
al
an
ka
r

Q.6(d) Explain hibernate architecture in detail.


(A)

Fig. 1

(1) The working of hibernate will state


te when persistent
persist
object i.e. POJO has
cation.
n.
been created by the java application.
(2) Hibernate layer is divided into
object which are use
nto following different
diff
eration.
tion.
to perform different operation.
(i) Configuration :
esta
(i) This object iss used to establish
a connection with the database.
ollowing 2 files
(ii) It containss following
ernate. properties
propertie  it is use to give some additional
propert
(a) hibernate.
information
ormation about
ab
the hibernate layer.
(
(b)) hibernate (f.g.
 xml  It is use to establish a connection with a
rticul database.)
da
particular
ration object is also use to create session factory.
(iii) Configuration
(ii) Session factory :
(a) As the name suggest session factory is use to create different
session objects.
(b) Session factory will created only once, but to perform multiple
operation it will create multiple session object.
(iii) Session :
x It is generally use to receive a persistent object inside the
hibernate layer.
x Session object is responsible to create transaction object & perform
appropriate operation on persistent object.
30

Prelim Paper Solution

(iv) Transaction :
x It is the optional object which is use to represent unit of work.
x It represent the starting & ending of the transaction on database.
(v) Query :
(i) If we want to perform operations on database using SQL or hQl
queries, then in that case session object create query object.
(vi) Criteria :
If we want to perform operations on database using java methods then
in that case session create criteria object.
Q.7
Attempt the following (any THREE)
[15]
Q.7(a) Write a program to implement single arithmetic calculator
using awt [5]
calc
c
components.
(A)
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
t=300>
00>
/*<applet code=e5 width=200 height=300>
</applet>*/
Actio
A
public class e5 extends Applett implements ActionListener
{
Label l1,l2;
Button b1,b2,b3,b4;
TextField t1,t2,t3;;
public void init())
{
(new FlowLay
FlowLayout(
setLayout(new
FlowLayout());
el("Number
"Numb 1");
1"
l1=new Label("Number
Numbe 2");
l2=new Label("Number
Ad
b1=new Button("Add");
b2=new Button("Sub");
b3=new Button("Mul");
b4=new Button("Div");
t1=new TextField(10);
t2=new TextField(10);
t3=new TextField(10);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
31

Vidyalankar : T.Y. B.Sc. (IT) Adv. Java

add(l1);
add(t1);
add(l2);
add(t2);
add(b1);
add(b2);
add(b3);
add(b4);
add(t3);
}

Vi
dy
al
an
ka
r

public void actionPerformed(ActionEvent ae)


{
String s=ae.getActionCommand();
int n1=Integer.parseInt(t1.getText());
int n2=Integer.parseInt(t2.getText());
int n;
if(s.equals("Add"))
{
n=n1+n2;
}
else if(s.equals("Sub"))
{
n=n1-n2;
}
else if(s.equals("Mul"))
als("Mul"))
s("Mul"))
{
n=n1*n2;
}
else
{
n=n1/n2;
}
Integer I=new Integer(n);
String p=I.toString();
t3.setText(p);
}
}

32

Prelim Paper Solution

Q.7(b) Write a program to meate a split pane in which left side of split
Rane contains a list of plants and when user clicks on any planet
name, its image should get displayed an right side.
(A)
import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;

[5]

Vi
dy
al
an
ka
r

class list extends JFrame implements ListSelectionListener


{
JSplitPane jsp;
ImageIcon i1,i2,i3;
JList jl;
JLabel j;
list()
{
Container c=getContentPane();
c.setLayout(new FlowLayout());
turn"};
n"};
String s[]={"earth","mercury","saturn"};
jl=new JList(s);
jl.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
ectionModel.SING
onModel.S
i1=new ImageIcon("earth.jpg");
rth.jpg");
pg");
i2=new ImageIcon("mercury.png");
("mercury.png");
mercury.png")
i3=new ImageIcon("saturn.jpg");
on("saturn.jpg")
on("saturn.jpg");
bel(i1);
j=new JLabel(i1);

jsp=new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
tPane(JS
jsp.setLeftComponent(jl);
jsp.setRightComponent(j);
jl.addListSelectionListener(this);
c.add(jsp);
setSize(500,500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

33

Vidyalankar : T.Y. B.Sc. (IT) Adv. Java

Vi
dy
al
an
ka
r

public void valueChanged(ListSelectionEvent ls)


{
String p=(String)jl.getSelectedValue();
if(p.equals("earth"))
{
j.setIcon(i1);
}
else if(p.equals("mercury"))
{
j.setIcon(i2);
}
else
{
j.setIcon(i3);
}
}
public static void main(String args[])
{
list l=new list();
}
}

g. Also wirte
w
Q.7(c) Explain CGI and its woring.
disadvantages of CGI.

(A)

http reg.

Client
ent
nt

http
ht res
re

web
Server

[5]

CGI

DB
Server

(i) CGI : Common gateway interface is responsible to provide dynamic


response in case of Three tire architecture.
(ii) Working :
x When webserver accept request which require dynamic response web
server forward the request to CGI.
x CGI is a program which accept the request & to handle that request
create CGI. Process & load that process inside the web server.
x Now that process is responsible to provide dynamic response to the
client.
34

Prelim Paper Solution

Once this can be done web server destroy the process to free its
memory.

(d) Three-tier architecture


http reg
Client

http res

web
Server

DB
Server

Vi
dy
al
an
ka
r

(i) In this there exist three entity i.e. client, webserver & Database
server.
se
(ii) Basically here server get distributed in web server
& database
server.
ract with client
clien as well as database
(iii) Web server is responsible to interact
server.
e minimize perf
(iv) Although this architecture
performance delay it has
following disadvantage.
(v) Disadvantage
lure
e can occure if the webserver get failed.
(i) Single point failure
ecture
re does not use to provide dynamic response.
(ii) This architecture
e
(vi) Disadvantage
rocess
cess are platform
platfo
p
x CGI process
dependent process because they are
plemented in C, C+
C++ pearl.
implemented
x It increase the ov
overhead of webserver because every time a new
process get loaded
loa
& unloaded from web server.
ver difficult
di
x It is very
to implement CGI programming.
k of scalablity
s
x Lack
if the number of client will get increase.
x Lack of security.
x It uses lots of webserver resources.
x Only one resource can be use at a time i.e. lack of resource
sharing.
Q.7(d) Write a program to demonstrate use of JMenuBar, JMenu and
JMenuItem class in swing.
(A)
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

[5]

class notepad2 extends JFrame implements ActionListener


35

Vidyalankar : T.Y. B.Sc. (IT) Adv. Java

{
JMenuBar jm;
JMenu jm1,jm2;
JMenuItem m1,m2,m3,m4,m5,m6;;
JTextArea jta;
JScrollPane jsp;
notepad2()
{
Container c=getContentPane();
c.setLayout(new BorderLayout());

Vi
dy
al
an
ka
r

jm=new JMenuBar();
jm1=new JMenu("File");
jm2=new JMenu("Edit");
m1=new JMenuItem("New");
m2=new JMenuItem("Open");
m3=new JMenuItem("Save");
m4=new JMenuItem("Exit");
m5=new JMenuItem("Foreground");
nd");
m6=new JMenuItem("Background");
round");
d");
jm1.add(m1);
jm1.add(m2);
jm1.add(m3);
jm1.add(m4);
jm2.add(m5);
m6);
jm2.add(m6);
jm.add(jm1);
jm.add(jm2);

jta=new JTextArea();
jsp=new JScrollPane(jta);
m1.addActionListener(this);
m2.addActionListener(this);
m3.addActionListener(this);
m4.addActionListener(this);
m5.addActionListener(this);
m6.addActionListener(this);
36

Prelim Paper Solution

c.add(jm,BorderLayout.NORTH);
c.add(jsp,BorderLayout.CENTER);
setSize(500,500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

Vi
dy
al
an
ka
r

public void actionPerformed(ActionEvent ae)


{
String s=ae.getActionCommand();
if(s.equals("New"))
{
jta.setText("");
}
else if(s.equals("Open"))
{
JFileChooser jf1=new JFileChooser();;
jf1.showOpenDialog(null);
}
else if(s.equals("Save"))
{
JFileChooser jf2=new JFileChooser();
eChooser(
jf2.showSaveDialog(null);
g(null);
null);
}
else if(s.equals("Exit"))
als("Exit"))
s("Exit"))
{
dispose();
}
Fo
else if(s.equals("Foreground"))
{
JColorChooser jc1=new JColorChooser();
Color c1=jc1.showDialog(null,"Select Foreground",null);
jta.setForeground(c1);
}
else
{
JColorChooser jc2=new JColorChooser();
Color c2=jc2.showDialog(null,"Select Foreground",null);
jta.setBackground(c2);
}

37

Vidyalankar : T.Y. B.Sc. (IT) Adv. Java

}
public static void main(String args[])
{
notepad2 n=new notepad2();
}
}
Q.7(e) Explain different types of JSP tags.
(A)
JSP tags / JSP elements
JSP tags are normally use to embed java code inside the JSP page.
Following are various type of JSP tags
(A) Directive tag
It has three types

[5]

Vi
dy
al
an
ka
r

(a) Page directive tag


opera
It is use to perform those operation which can be o
operated through out
the JSP page.
e.g.:
<% @ page import = java.10* %>
<% @ page session = true%>
%>
<% @ Page language = java%>
ava%>
%>
ype = text/html%
text/h
<% @ Page content Type
text/html%>
ve
e tag :
(b) Include directive
o include the contents
con
It is use to
of one JSP application inside the
SP application.
application
current JSP
e.g.
clude
lude file = abc.jsp
ab
<%@ include
%>
ve tag :
(c) taglib directive
Inside the JSP application, if we want to use some other tag apart from
html & JSP then the tag server or the tag library can be be included
using taglib directive tag.
e.g.:
<%@taglib uri = www.w3.org%>
(d) Declaration tag
It is use to declare a particular variable inside the JSP application.
e.g.
<%! int a = 2; %>

38

Prelim Paper Solution

(e) Expression tag


It is use to display the value of a particular variable or an expression on
a web browser.
e.g.
<% = a%>

Vi
dy
al
an
ka
r

(c) Script let


It is use to write java code as it is inside the JSP page as it is written in
java application.
e.g.
<%
___
___ java code
___
>
(d) Comment tag
e jsp
p page. A comment
comm
c
It is use to write comment inside
is non executable
ovide
e some additio
add
statement which is use to provide
additional
information about the
some instruction.
e.g.
<%   comment   %>
f hibernate mapping
m
map
Q.7(f) Explain structure of
file.

(A)

[5]

<?xml version=1.0
1.0 encoding=U
encoding=UT
encoding=UTF8?>
<hibernatemapping>
mapping>
apping>

ame=guestboo
me=gue
<class name=guestbook
table=guestbooktable>
am
<property name=name
type=string>
<column name=username length=50 />
</property>

<property name=message type=string>


<column name=usermessage length=100 />
</property>
</class>
</hibernatemapping>

39

Vidyalankar : T.Y. B.Sc. (IT) Adv. Java

Elements:
<hibernatemapping>.......</hibernatemapping>
It is the base tag which is used to write hibernate mapping file, which is
used to map POJO class with database table.
<class>.......</class>
It represents name of the class and database table which we want to map
with each other. It has 2 parameters:
name It represents name of the class
table It represents name of the database table

Vi
dy
al
an
ka
r

<property>.......</property>
It is used to write the property which we want to map with database column.
It has 2 parameters:
name It represents name of the property
type It represents type of the property
<column>.......</column>
mn which w
we wa
It is used to write the database column
want to map with java class
property. It has 2 parameters:
e column
name It represents name of the
aximum
um length of a column value
length It represents maximum

40

You might also like