Sunteți pe pagina 1din 40

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

V
Advanced Java
Time : 2½ Hrs.] Prelim Question Paper [Marks : 75

Q.1 Attempt the following (any TWO) [10]


Q.1(a) Explain Checkbox with example. [5]
(A) Checkbox [2 mark]
1) Checkbox is a class which is used to create Checkbox in awt.
2) It’s constructors are :
Checkbox( );
Checkbox (string s);
Checkbox (string s, Boolean state);
up (b
Checkbox (string s, Boolean state, Checkbox Group ((b));

r
Here Checkbox Group is a class which is used sed to convert a checkbox into a
radio button.
ka
Checkbox Group has following two methods
1) get Selected Checkbox ( );
thods
ds :
an
cted
d Checkbo
It is used to retrieve a selected Checkbox.
Checkbox
eckbox c);
2) Set Selected Checkbox (Checkbox
n appropriate
It is used to select an propriate C
Chec
Checkbox.
al

Methods of Checkbox ox :
dy

i) getLabel( );
It is used to retrieve name of the Checkbox.

el(string s);
ii) setLael(string
Vi

ed
d to se
It is used set a ne
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 1
Vidyalankar : T.Y. B.Sc. (IT) – Adv. Java

Java Linux ASP

ST NS

Current Selection :
Java : True
Linux : False
ASP : False
ST : False
NS : False
import java.applet.*;
import java.awt.event.*;
import.java.awt.*;
/* <applet code = test width = 200 height = 30>>

r
< /applet>/

ka
public class test extends Applet implements
ItemListener
{
nts
ts
an
Checkbox c1, c2, c3, c4, c5,
public void init( )
{
al

setLayout (new FlowLayou ));


new FlowLayout( ))
c1 = new Checkbox (“Ja
(“Java”);
(“Java”
dy

c2 = new Checkbox (“Lin


(“Linux”);
c3 = new Checkbox ((“ASP”);
c4 = new Checkbo
Chec
Checkbox (“ST”);
Vi

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)

2
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 (a, 10, 120);


g.drawString (b, 10, 130);
g.drawString (c, 10, 140);
g.drawString (d, 10, 150);
g.drawString (e, 10, 160);
g.drawString (f, 10, 170);
}

r
public void itemStateChanged (Itemevent
event
nt ie);
{

}
ka
repaint( );
an
}

Q.1(b) Explain delegation event model.del. [5]


al

(A) Delegation event model el


Delegation event modeldel consist of follo
f
following three concepts which are used for
dy

handling the eventt : [4 mark]


1) Event
ion : Event is also
Definition a object.
Vi

ent is de3fined
i) Event de3fin as the object which describe the state change of
ticul source.
the particular s
ii) Event canan be
b occur on multiple conditions like clicking on a button.
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);

3
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.

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
the event object will get throw and to receive eive that
th object different
receiving method can be used.

r
vent only when it iis registered for
A component can generated a particular event

ka
that particular event.

ss.
Q.1(c) Write a short note on Inner class. [5]
an
(A) Inner Class [4 mark]
Example :
import java.awt.*;
al

import java.awt.event.*;
*;
dy

class testevent extends frame im implements


ActionListener
tener
ener
{
Vi

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);

4
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( );

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


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

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

ka
if (s.equals (“Red”))
{
an
setBackground (c1);
}
Green”))
en ))
else if (s.equals (“Green”))
al

{
ground
round (c2);
setBackground
else
dy

{
setBackgro
setBackground (c3);
}
Vi

}
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. [5]


(A) Adapter Class [3 mark]
Example :
import java.awt.*;
import java.awt.event.*;

class testevent extends WindowAdapter


implements ActionListener

r
{

ka
Frame f;
testevent( )
{
an
f = new Frame( );
f.setLayout(new FlowLayout(
wLayout( ))
));
Label l = new Label
el (“select a color:”);
co
al

Button b11 = new Button


Butto (“Red”);
(“
dy

on b2 = new Button
Button Butto (“Green”);
But
Button
utton Button (“Blue”);
tton b3 = new Bu
Vi

b1.addActionListener (this);
b1.addActionL
b1.addA
b2.addActionListener
2.addAct (this);
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);

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

r
}
else
{ ka c3);
f.setBackground (c3);
an
}
}
al

Public void WindowClosing


Closing (WindowEvent
ndowClosing (Wind
(W we)
{
dy

System.exit (0);
tem.exit (0)
}
Vi

Pubic
c Static void main (String a[ ])
bic
{
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.

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

EventClass EventListener EventAdapter Class


ActionEvent ActionListener ActionAdapter
ItemEvent ItemListener ItemAdapter
MouseEvent MouseListener MouseAdapter
KeyEvent KeyListener KeyAdapter
ComponentEvent ComponentListener ComponentAdapter
ContainerEvent ContainerListener ContainerAdapter
AdjustmentEvent AdjustmentListener AdjustmentAdapter
TextEvent TextListener TextAdapter
WindowEvent WindowListener WindowAdapter
MouseWheelEvent MouseWheelListener MouseWheelAdapter

Q.2 Attempt the following (any TWO) [10]


ng Component.
Q.2(a) Differentiate between AWT component and Swing Compo
Com [5]
(A)

r
components
ka
AWT Components
1) AWT components are non java a
Swing Com
Swing components
componen
compone
comp
components
Components
are pure java
an
2) They are platform dependent
endent They arear platform independent
components com
compon
components
3) They are non decorative components
mponents The
They
T are decorative. We can even
al

place an image on a component


4) They are normallyally
ly rectangular ini We can create different shape
dy

shape components
5) Those are e considered as heavy Those are considered as light weight
omponents
weight components components
Vi

6) They arere not used to perform They are used to perform complex
erations
tion
complex operations operations
7) Those classes are present in java.awt Those classes are present in
package 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.

8
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

Yes No Cancel

r
ka e);
(c) ShowInputDialog(String message);

Message
sage
an
OK
K Cancel
al

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

the userss

c
Q.2(c) Write a program to create a combobox, and add different items in [5]
Vi

that combobox
obox accepting them from user.
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;

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);

setSize(500,500);
setVisible(true);
LOSE);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);E);
}

r
e)
public void actionPerformed(ActionEvent ae)
{
ka
String s=jt.getText();
jc.addItem(s);
an
}
public static void main(String
ng args[])
gs[])
{
al

combo cb=new combo(); );


}
dy

Q.2(d) Write a program to cr create a table and perform addition and removal [5]
Vi

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.*;

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);

jb1.addActionListener(this);

r
jb2.addActionListener(this);

ka
c.add(jsp,BorderLayout.CENTER);
c.add(jb1,BorderLayout.NORTH);
an
c.add(jb2,BorderLayout.SOUTH); H);
setSize(1000,500);
setVisible(true);
al

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ation(JFrame.EXIT
JFrame.E
}
dy

public void actionPerformed(ActionEvent


onPerformed(Actio
nPerformed(Ac ae)
{
ae.getActionC
ae.getActionComma
String s=ae.getActionCommand();
Vi

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) [10]


Q.3(a) Explain RequestDispatcher with example. [5]
(A) RequestDispatcher [ 2 mark]

username :

r
password :

ka Login
an
<html>
<head>
<title> Servlet Applicationn </title>
title> </head>
</he
al

<body>
<form method = "post" t" action = "test">
ost" "t
"test
dy

<b> Username </b>b


b>
<input type = "text"
text" name = "u" value = " " size = "10">
e = "password"
<input type "password nam name = "p" value = " " size = "10">
Vi

<input type = "submit"


"subm va value = "login">
</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

{
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

r
("Errors");

} ka
out.close( );
forward(request,
ward(reques rresponse);
rd2.forward(request,
an
}
}
al

Request Dispatchers [2 mark]


1) Any Servlet application
pplication
ication can b created as a request dispatcher by using
be c
dy

ethod
following method
equestDispatcher(
questDispatcher( );
getRequestDispatcher(
stDispatchers is a class which is there inside the package
stDispatcher
2) RequestDispatchers
Vi

ervlet
javax.servlet
spatche can be created for following 2 reasons.
3) RequestDispatcher
(a) To includede the contains of RequestDispatcher into the current
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

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 :
x It is used by the client to send a Session sion ID to the Servlet.
x It is in Hidden form & only Servlet et can
an read it & Hence called as

r
Hidden form field.

ka
(b) Url rewriting :
x It is used to send SessionID
x Servlet can put the SessionID
nID to the client.
sionID inside
insi
clie
rresponse packet or it will
an
generate a special token
oken to send a Se
SessionID
(c) Cookies :
x By using cookie, okie, a Servl
Servlet ana send SessionID to the client
al

machine.
x For thatt purpose Servlet
Serv will create a new cookie for Session ID &
dy

dss it to the client


sends w
client, with the help of response packet Header.
For example,e,
rogram to create
Write a program cr a client side application which is used to accept
Vi

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>

server side application


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class test extends HttpServlet

r
{

{
ka
public void doGet(HttpServletRequestt req, HttpServletResponse
throws IOException, Servlet
HttpServlet
HttpSer
et Exception
res)
an
xt/html");
res.setContentType("text/html");html");
PrintWriter pw = res.getWriter(
getWriter(
etWriter( );
arseInt(req.getPa
eInt(req.ge
int roll = Integer.parseInt(req.getParameter("r"));
al

eq.getParameter("
getParamet
String name = req.getParameter("n");
pw.println ("The
The roll no. =" + roll);
ro
n("<br>");
br>");
pw.println("<br>");
dy

ntln("The name =" + name);


pw.println("The
HttpSession
ession hs = rreq.getSession(true);
pSession req.
(hs.isNew(
hs.isNew( ))
if(hs.isNew(
Vi

{
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

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


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
<input type="radio" name="java" value="b">Bjarne S
<input type="radio" name="java" value="j">James
>James Goslin
="j">James Gosl
G

r
<br>

</form>
</body>
ka mit">
t">
<input type="submit" value="Submit">
an
</html>

//test.java
al

import java.io.*;
t.*;
import javax.servlet.*;*;
dy

vlet.http.*;
import javax.servlet.http.*;

public class test


st extends H
Http
HttpServlet
{
Vi

public voidid doPost(


doP
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();
}
}
}

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


HttpServletRequest and HttpServletResponse.
(A) //index.jsp
<html>

r
<head>

ka
<meta http-equiv="Content-Type" content="text/htm
<title>JSP Page</title>
</head>
tent="text/
content="text/html; charset=UTF-8">
an
<body>
<form method="post" action="calculate">
n="calculat
or</h1>
h1>
<h1>Simple Calculator</h1>
al

<hr>
<b>Enter First Number</b>
dy

e="number"
="number" name="
<input type="number" name
name="n1" value="" size="2">
<p>
ter Second N
<b>Enter Numb
Number</b>
Vi

<input type="number
type="n
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

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("+"))
{

r
c=a+b;
}
ka
else if(op.equals("-"))
{
an
c=a-b;
}
"*")))
else if(op.equals("*"))
al

{
c=a*b;
dy

}
else
{
Vi

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
{

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(?,?)");

r
ps.setInt(1,10);

ka
ps.setString(2,"SSS");
ps.execute();
ps.close();
an
c.close();
}
catch(Exception e)
al

{
System.out.println("Exception
println("Exception
rintln("Excep occur");
dy

}
}
}
Vi

cter quo
Q.4(b) Explain character quoting convention in JSP [5]
(A) Character Quotingng Conventions
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 Description
Characters
\' 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

Example
<% String message = ‘Escaping \’ single
e quote’;
uote’; %>

r
ouble quote’; %
<% String message = ‘Escaping \’ double %>

ka
<% String message = ‘Escaping \ \ backslash’; %>
<% String message = ‘Escaping
ng % \ > scripting
aping
script
ng < \ % scriptin
<% String message = ‘Escaping scr
%
end tag’’; %>
e
scripting start tag’’; %>
an
<% String message = ‘Escaping
scaping \$ dollar
Escaping dol sign”
s ; %>

caping
As an alternative to escapinging quote cha
characters, the character entities
al

&apos; and &quot; can also be used.


dy

Q.4(c) Explain transactionion in JDBC. [5]


(A) c.setAutoCommit (false);
mit (false
s.execut("insert
nsert into employ
emp value }} )
Vi

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.

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 JSP’s 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) s) the
he JSP code
c into a servlet

r
code.

ka
x After this stage there is no JSP
x The resultant is a java class
(b) Compilation :
SP everything is a servlet.
ss instead
nstead of aan ht
html page (JSP page)
an
x The generated servletet iss compiled tto vvalidate the syntax.
enerate
nerate class file to run on JVM.
x The compilation generate
(c) Loading :
al

x The complied ed byte code is loaded in web container i.e. Web


server.
dy

If not
Request
ues
Client initi
initialized Translation Compilation Loading
Vi

Already
Initializ Initialization Instantiation

Response
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.

Q.5 Attempt the following (any TWO) [10]


Q.5(a) Explain JSF life cycle. [5]
(A) JSF life cycle

r
ka Response
e
plete
complete
Response
complete
an
Faces
Restore Apply Process
cess Process Process
response request
view event Validation event
values
al

e
Reader response

Response
Resp
Response co
complete
complete Response complete
dy

Faces
Render Process
rocess Invotie Process Update
response model
Vi

response
e Event application Event
values
Conversion
Convers error/render

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

ii) If any error occur then the error message will get store inside
“Facescontext” object.
3. 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.
4. 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.
5. Invest application
i) In this face the application will get invest st or
o execute to create
responses.
ii) Also if they are multiple pages then lintsing
tsing of thos
tthose page will also

r
get done in this phase.
6.
ka
Render response
In this phase the generated responses
client as a response.
ponses
ses will get re
render i.e. provided to a
an
Q.5(b) Explain advantages of EJB.. [5]
(A) Advantages of EJB
al

endent, EJB
Apart from platform independent, E has following advantages.
x More focus on n business log
logic : In industry because of use EJB the
dy

developmentt time of on application


a can be reduce, so that the
tion
on can able to more
organization mo focus on business logic.
ble Componen
x Portable Components : EJB
E components creted inside one web server can
Vi

be usedd in another
anot we server.
web
x Reusable compone
component : We can create on EJB only once and by storing it
inside the webb server we can use it multiple time.
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: EJB’s can be sue in distributed architecture
where the EJB’s can get store in multiple system in distributed manner.
x Interoperability : EJB’s 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 EJB’S. [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

Types of session bean

r
(1) Statefull session bean

ka
Those are the bean which iss use to stor
information between the client
ore
e the informatio
state in which they can store inform
store the conversational
ent & server for that they maintain a
information. Because of that state,
an
the processing of this bean are slower.
slowe

n bean
(2) Stateless session an
al

Those are the e bean


an which is not use to store the conversational
n between the client
information clie & server for that they not maintain a
dy

hich they can Be


state which Beca
Because of that.

ngleton Session
(3) Singleton Sessi bean
be
Vi

Thiss bean are


a requested
req 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 [5]
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>

<h:outputLabel for="txtName">

r
<h:outputText value="Name" />

ka
</h:outputLabel>

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


value="#{user.name}">
alue="#{use
an
rn="[a-z]+"/>
n="[a-z]+"/>
<f:validateRegex pattern="[a-z]+"/>
</h:inputText>
al

<h:outputLabell for="txtPassword
for="txtPassword">
="txtPassw
<h:outputText
ext value="Password" />
xt value="Passwor
value="Pass
dy

utLabel>
</h:outputLabel>

<h:inputSecret
:inputSecret id="txtPassword"
id="t value ="#{user.password}">
Vi

<f:validateRegex
validateRegex
alidateR pattern="(.{6,20})" />
</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;
}

r
public void setpassword(String p)

}
{
ka
password = p;
an
public String getpassword()
ord())
{
al

return password;
rd;
}
dy

public String
ring verifyUser()
{
Vi

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

26
Prelim Paper Solution

Q.6 Attempt the following (any TWO) [10]


Q.6(a) Explain MVC architecture. [5]
(A) MVC architecture

Event

Controller

View

Model

r
1.
ka
MVC architecture is normally use to create mult
application.
2. The basic intention of MVS S is to separate
sep
multiple views of the same

separat application logic with


an
presentation logic.
3. The architecture of MVC C contains
ntains follo
followin
following 3 components.
x Model: It represent ent a data or collection
colle of multiple data use in MVC.
al

e.g. database
x View: It is the he component
componen wh which is responsible for creating multiple
dy

applicat
applic
views of the some application.
sp
e.g. jspp
ntroller: This com
x Controller: component is sue to control model as well as view.
Vi

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.

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

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


(A) Core Components of struts Framework

http
Invoke
request Filter
Interception return Action
dispatcher

Reads dispatchers
configurator

Struts
Result
Client Xml

1. Struts Framework is use to support MVC architec architecture


chit and hence 3
components of struts are resemble with MVC architecture.
C architectur
architec

r
i) Filter dispatcher will behave like controller
ontroller

ka
ii) Action will work as Model
iii) Result and Result type will work
ork as a view
owing
Struts framework contain following ng core component
compon
co
an
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
al

component to forwardard the reque


re
request.
For selectinging
g a particular
particu action component, “Struts.xml” helps
dy

spatcher.
Filterdispatcher.
Once itt identifies appr
apprompriate action, Filterdispatcher invoke the
tion by sendi
action th request.
sending the
Vi

tion:
on: Action
ii) Action: Ac will behave like model and hence it has the
priate dt
appropriate dta use to crete multiple views.

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


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

<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”/>

</sessionfactory>

r
</hibernateconfiguration>

Elements: ka
hibernate.dialect It represents the
e name of the
th SQL dialect for the
an
database

r_class
ass
 It rrepre
hibernate.connection.driver_class represents the JDBC driver class for
al

the specific database


dy

ion.url It represents
ion.url
hibernate.connection.url repr
represe the JDBC connection to the database

onnection.use
onnection.usernam
hibernate.connection.username It represents the user name which is used to
Vi

he
e database
connect to the datab

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

Q.6(d) Explain hibernate architecture in detail. [5]


(A)

r
Fig. 1

ka
(1) The working of hibernate will state
te when persistent
cation.
n.
been created by the java application.
persist object i.e. POJO has
an
(2) Hibernate layer is divided into
nto following different
diff object which are use
eration.
tion.
to perform different operation.

(i) Configuration :
al

(i) This object iss used to establish


esta a connection with the database.
(ii) It containss following
ollowing 2 files
dy

ernate. properties
(a) hibernate. propertie  it is use to give some additional
propert
information
ormation about
ab the hibernate layer.
(b)) hibernate (f.g.
(  xml  It is use to establish a connection with a
Vi

rticul database.)
particular da
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
calc
c using awt [5]
components.
(A) import java.awt.*;
import java.applet.*;
import java.awt.event.*;
t=300>
/*<applet code=e5 width=200 height=300>00>
</applet>*/
public class e5 extends Applett implements ActionListener
Actio
A
{
Label l1,l2;
Button b1,b2,b3,b4;
TextField t1,t2,t3;;
public void init())
{
(new FlowLay
setLayout(new FlowLayout(
FlowLayout());
el("Number
"Numb 1");
l1=new Label("Number 1"
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);
}

public void actionPerformed(ActionEvent ae)


{
String s=ae.getActionCommand();
int n1=Integer.parseInt(t1.getText());

r
int n2=Integer.parseInt(t2.getText());
int n;
ka
if(s.equals("Add"))
{
an
n=n1+n2;
}
else if(s.equals("Sub"))
al

{
n=n1-n2;
dy

}
else if(s.equals("Mul"))
als("Mul"))
s("Mul"))
{
Vi

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 [5]
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.*;

class list extends JFrame implements ListSelectionListener


{
JSplitPane jsp;
ImageIcon i1,i2,i3;
JList jl;
JLabel j;
list()
{

r
Container c=getContentPane();

ka
c.setLayout(new FlowLayout());

turn"};
n"};
String s[]={"earth","mercury","saturn"};
an
jl=new JList(s);
jl.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
ectionModel.SING
onModel.S
al

i1=new ImageIcon("earth.jpg");
rth.jpg");
pg");
i2=new ImageIcon("mercury.png");
("mercury.png");
mercury.png")
dy

i3=new ImageIcon("saturn.jpg");
on("saturn.jpg")
on("saturn.jpg");

bel(i1);
j=new JLabel(i1);
Vi

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

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);
}

r
}

{ ka
public static void main(String args[])

list l=new list();


an
}
}
al

Q.7(c) Explain CGI and its woring.


g. Also wirte
w disadvantages of CGI. [5]
(A)
dy

http reg.
web
Client
ent
nt CGI
Server
http
ht res
re
Vi

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

x Once this can be done web server destroy the process to free its
memory.
(d) Three-tier architecture
http reg
web
Client
Server
http res

DB
Server

(i) In this there exist three entity i.e. client, webserver & Database
server.
(ii) Basically here server get distributed in web server se & database
server.

r
(iii) Web server is responsible to interact ract with client
clien as well as database

ka
server.
(iv) Although this architecture e minimize perf
performance delay it has
an
following disadvantage.
(v) Disadvantage
lure
(i) Single point failure e can occure if the webserver get failed.
ecture
(ii) This architecture re does not use to provide dynamic response.
al

(vi) Disadvantage e
rocess
x CGI process cess are platform
platfo
p dependent process because they are
dy

plemented in C, C+
implemented C++ pearl.
x It increase the ov overhead of webserver because every time a new
process get loaded
loa & unloaded from web server.
Vi

x It is very
ver difficult
di to implement CGI programming.
x Lack k of scalablity
s 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 [5]


JMenuItem class in swing.
(A) import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

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());

jm=new JMenuBar();
jm1=new JMenu("File");
jm2=new JMenu("Edit");

r
m1=new JMenuItem("New");

ka
m2=new JMenuItem("Open");
m3=new JMenuItem("Save");
m4=new JMenuItem("Exit");
an
m5=new JMenuItem("Foreground");
nd");
m6=new JMenuItem("Background");
round");
d");
jm1.add(m1);
al

jm1.add(m2);
jm1.add(m3);
dy

jm1.add(m4);
jm2.add(m5);
m6);
jm2.add(m6);
Vi

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);
}

public void actionPerformed(ActionEvent ae)


{
String s=ae.getActionCommand();
if(s.equals("New"))
{
jta.setText("");
}

r
else if(s.equals("Open"))
{
ka
JFileChooser jf1=new JFileChooser();;
jf1.showOpenDialog(null);
an
}
else if(s.equals("Save"))
{
al

JFileChooser jf2=new JFileChooser();


eChooser(
jf2.showSaveDialog(null);
g(null);
null);
dy

}
else if(s.equals("Exit"))
als("Exit"))
s("Exit"))
{
Vi

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. [5]


(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

(a) Page directive tag

r
It is use to perform those operation which can be o
opera
operated through out

e.g.: ka
the JSP page.

<% @ page import = “java.10*” %>


an
<% @ page session = “true”%>
%>
<% @ Page language = “java”%>
ava”%>
%>
ype = “text/html”%
<% @ Page content Type “text/h
“text/html”%>
al

ve
(b) Include directivee tag :
dy

It is use too include the contents


con of one JSP application inside the
SP application.
current JSP application
e.g.
Vi

clude
lude file = “abc.jsp”
<%@ include “ab %>

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%>

(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
___
>

r
ka
(d) Comment tag
It is use to write comment insidee jsp
ovide
statement which is use to provide
p page. A comment
e some additio
add
comm
c
additional
is non executable
information about the
an
some instruction.
e.g.
<%   comment   %>
al

f hibernate mapping
Q.7(f) Explain structure of m
map file. [5]
dy

(A) <?xml version=”1.0”


1.0” encoding=”U
encoding=”UT
encoding=”UTF8”?>
<hibernatemapping>
mapping>
apping>
Vi

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

<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

r
type It represents type of the property

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

‰‰‰‰‰‰
dy
Vi

40

S-ar putea să vă placă și