Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
136 views

Adv Java Soln

This document contains the solutions to questions from an Advanced Java prelim exam for a B.Sc. (IT) program. It includes explanations and code examples for questions about the default frame layout (BorderLayout), the delegation event model, inner classes, and adapter classes. The solutions provide detailed explanations and code snippets to illustrate the concepts in 2-3 sentences or less.

Uploaded by

sonali
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
136 views

Adv Java Soln

This document contains the solutions to questions from an Advanced Java prelim exam for a B.Sc. (IT) program. It includes explanations and code examples for questions about the default frame layout (BorderLayout), the delegation event model, inner classes, and adapter classes. The solutions provide detailed explanations and code snippets to illustrate the concepts in 2-3 sentences or less.

Uploaded by

sonali
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

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

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

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


Q.1(a) What is the default layout of the frame? Explain the same. [5]
(A) [Explanation  2 marks, Diagram  1 marks, Program  2 marks]
 BORDERLAYOUT is the default layout of the frame.
 It splits the container into five distinct sections where each section can hold one
component.
 The five sections of the BorderLayout are known as NORTH, SOUTH, EAST, WEST and
CENTER as shown in the diagram.
 To add a component to a BorderLayout, one needs to specify which section one wants it
placed.

r
ka
an
JFrame frm1 = new JFrame();
JPanel op = new JPanel();
frm1 .add (op, BorderLayout.NORTH);
al
Example
import java.awt.*;
import javax.swing.*;
dy

class BorderTest extends JFrame {

public static void main(String[] args)


{
JFrame window = new BorderTest();
window.setVisible(true);
Vi

}
BorderTest()
{
//... Create components (but without listeners)
JButton north = new JButton("North");
JButton east = new JButton("East");
JButton south = new JButton("South");
JButton west = new JButton("West");
JButton center = new JButton("Center");

//... Create content pane, set layout, add components


JPanel content = new JPanel();
content.setLayout(new BorderLayout());

content.add(north , BorderLayout.NORTH);
1
Vidyalankar : T.Y. B.Sc. (IT) – Adv. Java

content.add(east , BorderLayout.EAST);
content.add(south , BorderLayout.SOUTH);
content.add(west , BorderLayout.WEST);
content.add(center, BorderLayout.CENTER);

//... Set window characteristics.


setContentPane(content);
setTitle("BorderTest");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

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


(A) Delegation event model

r
Delegation event model consist of following three concepts which are used for handling the
event :

ka
1) Event
Definition : Event is also object.
i) Event is de3fined as the object which describe the state change of the particular
source.
ii) Event can be occur on multiple conditions like clicking on a button. Selecting a
Checkbox, Scrolling the scrollbars, etc.

2) Source
an
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);
al
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
dy

can be used to override their methods.

Event Handling
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
Vi

appropriate event will get generated. When the event will get generated the event object
will get throw and to receive that object different receiving method can be used.
A component can generated a particular event only when it is registered for that particular event.

Q.1(c) Write a short note on Inner class. [5]


(A) Inner Class
Example :
import java.awt.*;
import java.awt.event.*;

class testevent extends frame implements


ActionListener
{
testevent( )
{

2
Prelim Question Paper Solution

setLayout (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);
add (b1);
add (b2);
add (b3);

r
setSize (200, 300);

ka
setTitle (“SSS”);
setVisible (true);
}

public void actionPerformed (ActionEvent ae);


{
an
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);
al
if (s.equals (“Red”))
{
setBackground (c1);
}
else if (s.equals (“Green”))
dy

{
setBackground (c2);
else
{
setBackground (c3);
}
Vi

}
class demo extends WindowAdapter
{
public void WindowCloasing (WindowEvent we);
{
System.exit (0);
}
}

public static void main (string a[ ])


{
testevent t = new testevent( );
}
}

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

Inner Class
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
Example :
import java.awt.*;
import java.awt.event.*;

class testevent extends WindowAdapter


implements ActionListener

r
{
Frame f;

ka
testevent( )
{
f = new Frame( );
f.setLayout(new FlowLayout( ));
Label l = new Label (“select a color:”);
an
Button b1 = new Button (“Red”);
Button b2 = new Button (“Green”);
Button b3 = new Button (“Blue”);

b1.addActionListener (this);
b2.addActionListener (this);
b3.addActionListener (this);
al
f.addWindowListener (this);

f.add(l);
f.add(b1);
dy

f.add(b2);
f.add(b3);
f.setSize (200, 300);
f.setTitle (“SSS”);
f.setVisible (true);
}
Vi

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

4
Prelim Question Paper Solution

}
else
{
f.setBackground (c3);
}
}

Public void WindowClosing (WindowEvent we)


{
System.exit (0);
}

Pubic Static void main (String a[ ])


{

r
test event t = new testevent( );
}

ka
}

Adapter Class
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.
an
3) If we want to override only certain specific method, then in that case EventListener can
be replaced with EventAdapter Class.

EventClass EventListener EventAdapter Class


ActionEvent ActionListener ActionAdapter
ItemEvent ItemListener ItemAdapter
MouseEvent MouseListener MouseAdapter
al
KeyEvent KeyListener KeyAdapter
ComponentEvent ComponentListener ComponentAdapter
ContainerEvent ContainerListener ContainerAdapter
AdjustmentEvent AdjustmentListener AdjustmentAdapter
dy

TextEvent TextListener TextAdapter


WindowEvent WindowListener WindowAdapter
MouseWheelEvent MouseWheelListener MouseWheelAdapter

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


Q.2(a) Differentiate between AWT component and Swing Component. [5]
Vi

(A)
AWT Components Swing Components
1) AWT components are non java components Swing components are pure java components
2) They are platform dependent components They are platform independent components
3) They are non decorative components They are decorative. We can even place an
image on a component
4) They are normally rectangular in shape We can create different shape components
5) Those are considered as heavy weight Those are considered as light weight
components components
6) They are not used to perform complex They are used to perform complex
operations operations
7) Those classes are present in java.awt Those classes are present in javax.swing
package package

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

Q.2(b) How can a Tree structure be created in Swing? Explain. [5]


(A)  A tree structure is created in the following ways.
 The node is represented in Swing API as TreeNode which is an interface. The interface
MutableTreeNode extends this interface which represents a mutable node. Swing API
provides an implementation of this interface in the form of DefaultMutableTreeNode class.
 DefaultMutableTreeNode class is to be used to represent the node. This class is
provided in the Swing API. This class has a handy add() method which takes in an
instance of MutableTreeNode.
 So, first root node is created. And then recursively nodes are added to that oot.

import java.awt.event.*;
import java.awt.*;
import javax.swing.event.*;
import javax.swing.tree.*;
import javax.swing.*;

r
public class JTreeExample extends JFrame{

ka
public JTreeExample()
{
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DefaultMutableTreeNode everything = new
DefaultMutableTreeNode("Everything");
JTree avm = new JTree(everything);
an
DefaultMutableTreeNode animal = new
DefaultMutableTreeNode("Animal");
everything.add(animal);

animal.add(new DefaultMutableTreeNode("Cat"));
animal.add(new DefaultMutableTreeNode("Dog"));
animal.add(new DefaultMutableTreeNode("Fish"));
al
DefaultMutableTreeNode vegetable = new
DefaultMutableTreeNode("Vegetable");
everything.add(vegetable);
dy

vegetable.add(new DefaultMutableTreeNode("Onion"));
vegetable.add(new DefaultMutableTreeNode("Lettuce"));
vegetable.add(new DefaultMutableTreeNode("Carrot"));

DefaultMutableTreeNode fruits = new


DefaultMutableTreeNode("Fruits");
everything.add(fruits);
Vi

fruits.add(new DefaultMutableTreeNode("Mango"));
fruits.add(new DefaultMutableTreeNode("Banabna"));
fruits.add(new DefaultMutableTreeNode("Guava"));

Container con = getContentPane();


con.add(avm, BorderLayout.CENTER);
setSize(200,300);
setVisible(true);
}
public static void main(String args[])
{
new JTreeExample();
}
}

6
Prelim Question Paper Solution

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

combo()
{
Container c=getContentPane();

r
c.setLayout(new FlowLayout());
jc=new JComboBox();

ka
jb=new JButton("Add");
jt=new JTextField(10);

jb.addActionListener(this);
an
c.add(jc);
c.add(jt);
c.add(jb);
setSize(500,500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
al
public void actionPerformed(ActionEvent ae)
{
String s=jt.getText();
jc.addItem(s);
dy

}
public static void main(String args[])
{
combo cb=new combo();
}
}
Vi

Q.2(d) What is the purpose of tabbed panes? Explain with suitable example. [5]
(A) Purpose of TabbedPanes :
 This component lets the user switch between a group of components by clicking on a tab
with a given title and/or icon.
 Tabs are added to a TabbedPane object by using the addTab() or an insertTab()
methods.

Example:
import javax.swing.JTabbedPane;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JTabbedPaneDemo extends JFrame {
public static void main(String args[])

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

{
JTabbedPaneDemo d = new JTabbedPaneDemo();
JTabbedPane p = new JTabbedPane();
p.addTab("Cities", new CitiesPanel());
p.addTab("Colors", new ColorsPanel());
d.add(p);
d.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
d.setSize(500,500);
d.setVisible(true);

}
}
class CitiesPanel extends JPanel
{

r
public CitiesPanel ()
{

ka
JButton b1 = new JButton("New York");
add(b1);
}
}

class ColorsPanel extends JPanel


{
public ColorsPanel ()
an
{
JButton b1 = new JButton("Blue");
add(b1);
}
}
al
Q.3 Attempt the following (any TWO) [10]
Q.3(a) Explain RequestDispatcher with example. [5]
(A) RequestDispatcher
dy

username :

password :

Login
Vi

<html>
<head>
<title> Servlet Application </title> </head>
<body>
<form method = "post" action = "test">
<b> Username </b>
<input type = "text" name = "u" value = " " size = "10">
<input type = "password" name = "p" value = " " size = "10">
<input type = "submit" value = "login">
</form>
</body>
</html>
//test.java
import javax.servlet.*;
import javax.servlet.http.*;

8
Prelim Question Paper Solution

import java.io.*;
public class test extends HttpServlet
{
public void doPost(HttpServletRequest Request,
HttpServletResponse Response) throws IOException
ServletException
{
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")))
{

r
RequestDispatcher rd1 = request.getrequestDispatchers
("Welcome");

ka
rd1.include(request, response);
}
else
{
RequestDispatchers rd2 = request.getRequestDispatchers
("Errors");

}
an rd2.forward(request, response);

out.close( );
}
}

Request Dispatchers
al
1) Any Servlet application can be created as a request dispatcher by using following
method
getRequestDispatcher( );
2) RequestDispatchers is a class which is there inside the package javax.servlet
dy

3) RequestDispatcher can be created for following 2 reasons.


(a) To include 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.
Vi

Q.3(b) Explain the generic servlet and HTTP servlet. [5]


(A) Generic Servlet:
 GenericServlet class is direct subclass of Servlet interface.
 Generic Servlet is protocol independent.It handles all types of protocol like http, smtp,
ftp etc.
 Generic Servlet only supports service() method.It handles only simple request .
 public void service(ServletRequest req,ServletResponse res ).
 A generic servlet should override its service() method to handle requests as appropriate
for the servlet.
 The service() method accepts two parameters: a request object and a response object.
The request object tells the servlet about the request, while the response object is
used to return a response.

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

Generic Servlet only supports service() method.

Generic Servlet Request Handling

HttpServlet:
 HttpServlet class is the direct subclass of Generic Servlet.
 HttpServlet is protocol dependent. It handles only http protocol.

r
 HttpServlet supports public void service(ServletRequest req,ServletResponse res ) and
protected void service(HttpServletRequest req,HttpServletResponse res).

ka
 HttpServlet supports also
doGet(),doPost(),doPut(),doDelete(),doHead(),doTrace(),doOptions() etc.
 An HTTP servlet usually does not override the service() method. Instead, it overrides
doGet() to handle GET requests and doPost() to handle POST requests.
 An HTTP servlet can override either or both of these methods, depending on the type
of requests it needs to handle.
an
 The service() method of HttpServlet handles the setup and dispatching to all the
doXXX() methods
al
dy

HTTP servlet request handling

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


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

<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 Ritchie
<input type="radio" name="java" value="b">Bjarne Straunstrup
<input type="radio" name="java" value="j">James Goslin
<br>
<input type="submit" value="Submit">
</form>
</body>

10
Prelim Question Paper Solution

</html>

//test.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class test extends HttpServlet


{
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try

r
{
String answer=request.getParameter("java");

ka
if((answer.equals("d"))||(answer.equals("b")))
{
out.println("Wrong Answer");
}
else
{

}
an
out.println("Correct Answer");

}
finally
{
out.close();
al
}
}
}

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

and HttpServletResponse.
(A) //index.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
Vi

</head>
<body>
<form method="post" action="calculate">
<h1>Simple Calculator</h1>
<hr>
<b>Enter First Number</b>
<input type="number" name="n1" value="" size="2">
<p>
<b>Enter Second Number</b>
<input type="number" name="n2" value="" size="2">
<p>
<b>Enter Operation</b>
<input type="text" name="op" value="" size="2">
<p>

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

<input type="submit" value="Calculate">


</form>
</body>
</html>
//calculate.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class calculate extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{

r
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();

ka
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;
an
}
else if(op.equals("-"))
{
c=a-b;
}
al
else if(op.equals("*"))
{
c=a*b;
}
dy

else
{
c=a/b;
}
out.println("The Result is "+c);
} finally {
Vi

out.close();
}
}
}

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


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

public static void main(String[] args)


{
try

12
Prelim Question Paper Solution

{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection c = DriverManager.getConnection("jdbc:odbc:sss");
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");
}

r
}
}

ka
Q.4(b) Explain character quoting convention in JSP [5]
(A) Character Quoting 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.
an
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.
al
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
dy

\' 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
Vi

backslash

Example
<% String message = ‘Escaping \’ single quote’; %>
<% String message = ‘Escaping \’ double quote’; %>
<% String message = ‘Escaping \ \ backslash’; %>
<% String message = ‘Escaping % \ > scripting end tag’’; %>
<% String message = ‘Escaping < \ % scripting start tag’’; %>
<% String message = ‘Escaping \$ dollar sign” ; %>

As an alternative to escaping quote characters, the character entities &apos; and &quot; can
also be used.

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

Q.4(c) Explain different types of JDBC drivers [5]


(A) JDBC drivers :
Type 1 : (JDBC ODBC Bridge Driver)
JDBC ODBC DB specific
calls calls calls
JDBC T1 ODBC
DB
Appl. Drivers

Advantage : (i) Free of cost


(ii) Easy to implement

Disadvantage : (i) Slow


(ii) Only can be used with Microsoft DataBase.

Type 2 : (Native API)

r
JDBC DB specific
calls calls

ka
JDBC T2
DB
Appl.

Native API

Advantage : Faster than T1


an
Disadvantage : Native API Burdens the work.

Type 3 : (Network Protocol)


JDBC Middleware server DB specific
calls specific calls calls
JDBC T3 MS
DB
Appl.
al
Advantage : Security/Most Secured

Disadvantage : It is slower than T2 and T4.


dy

Type 4 : (DataBase Protocol)


JDBC DB specific
calls calls
JDBC T4
DB
Appl.
Vi

Native API

Advantage : Fastest among all


Disadvantage : Costliest

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 :
 Web container translates (converts) the JSP code into a servlet code.
 After this stage there is no JSP everything is a servlet.
 The resultant is a java class instead of an html page (JSP page)

14
Prelim Question Paper Solution

(b) Compilation :
 The generated servlet is compiled to validate the syntax.
 The compilation generate class file to run on JVM.
(c) Loading :
 The complied byte code is loaded in web container i.e. Web server.

If not
Request initialized
Client Translation Compilation Loading

Already
Initialized
Initialization Instantiation

Response
Request Processing

r
Destruction

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

(e) Initialization :
an
 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.
al
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
dy

request processing.

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


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

Faces Apply
Restore Process Process Process
response request
view event Validation event
values

Reader response

Response complete Response complete

Faces Update
Render Process Invotie Process
response model
response Event application Event
values
Conversion error/render

Validation error /response

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

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

r
ii) If the rules does not match then the error message will get render to a client.
4. Update model values

ka
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 or execute to create responses.
ii) Also if they are multiple pages then lintsing of those page will also get done in this
phase.
6. Render response
an
In this phase the generated responses will get render i.e. provided to a client as a
response.

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


(A) Advantages of EJB
al
Apart from platform independent, EJB has following advantages.
 More focus on business logic : In industry because of use EJB the development time of
on application can be reduce, so that the organization can able to more focus on business
logic.
dy

 Portable Components : EJB components created inside one web server can be used in
another web server.
 Reusable component : We can create on EJB only once and by storing it inside the web
server we can use it multiple time.
 Reduces execution time: As EJB component are readymade component the user need not
to create this component every time, which reduces overall execution time.
Vi

 Distributed deployment: EJB’s can be used in distributed architecture where the EJB’s
can get store in multiple system in distributed manner.
 Interoperability : EJB’s can be used 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.

Q.5(c) Explain different ways of accessing EJB’s [5]


(A) EJB’s can be used or accessed in following 2 ways :
(a) No Interface View
 In this case, there is no any interface or software which can be used to access a
particular bean.
 For accessing a bean, we can call public method of a Bean using which a Bean can be
used.

16
Prelim Question Paper Solution

(b) Business Interface View


 In this case, for accessing a Bean we use different interfaces or different software’s.
 Those software’s which can be used for accessing is called as BDK (Bean Development Kit).
 In this case we are not required to call public method of a Bean for accessing a Bean.

Q.5(d) Write a program using JSF to find square root of a number. [5]
(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">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>

r
<h:form>
<h:outputLabel for="txtName">

ka
<h:outputText value="Enter number:" />
</h:outputLabel>
<h:inputText id="txtName" value="#{user.number}">
</h:inputText>
<h:commandButton value="Square Root" action="#{user.calculate}"/>
</h:form>
</h:body>
</html>
an
//userbean.java
import javax.faces.bean.*;
@ManagedBean(name="user")
public class userbean
al
{
int number;
double root;
public int getnumber()
dy

{
return number;
}
public void setnumber(int a)
{
number=a;
Vi

}
public double getroot()
{
return root;
}
public void setroot(double b)
{
root=b;
}
public String calculate()
{
root=Math.sqrt(number);
return "success";
}
}

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

//faces-config.xml
<?xml version='1.0' encoding='UTF-8'?>
<faces-config version="2.0">
<navigation-rule>
<from-view-id>/index.xhtml</from-view-id>
<navigation-case>
<from-outcome>success</from-outcome>
<to-view-id>/first.xhtml</to-view-id>
</navigation-case>
</navigation-rule>
</faces-config>

//first.xhtml
<?xml version='1.0' encoding='UTF-8' ?>

r
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">

ka
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
<h:form>
<h:outputText value="Square root is= #{user.root} ">
</h:outputText>
</h:form>
an
</h:body>
</html>

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


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

Event
dy

Controller

View
Vi

Model

1. MVC architecture is normally use to create multiple views of the same application.
2. The basic intention of MVS is to separate application logic with presentation logic.
3. The architecture of MVC contains following 3 components.
 Model: It represent a data or collection of multiple data use in MVC.
e.g. database
 View: It is the component which is responsible for creating multiple views of the
some application.
e.g. jsp
 Controller: This component is sue to control model as well as view.
e.g. Servlet

18
Prelim Question Paper Solution

4. Working
i) Whenever 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 retrieves
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.

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

r
Reads dispatchers
configurator

ka
Struts
Result
Client Xml

1. Struts Framework is use to support MVC architecture and hence 3 components of


struts are resemble with MVC architecture.
i) Filter dispatcher will behave like controller
an
ii) Action will work as Model
iii) Result and Result type will work as a view
Struts framework contain following core component
i) Filter dispatcher: It behave like controller which is use to accept request from the client.
Once it accept the request it will search an appropriate action component to
forward the request.
al
For selecting a particular action component, “Struts.xml” helps Filterdispatcher.
Once it identifies apprompriate action, Filterdispatcher invoke the action by sending
the request.
ii) Action: Action will behave like model and hence it has the appropriate dta use to
dy

crete multiple views.

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


(A) <?xml version=”1.0” encoding=”UTF8”?>

<hibernateconfiguration>
<sessionfactory>
Vi

<property name=”hibernate.dialect”> org.hibernate.dialect.MySQLDialect</property>

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

</sessionfactory>
</hibernateconfiguration>

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

Elements:
hibernate.dialect It represents the name of the SQL dialect for the database
hibernate.connection.driver_class It represents the JDBC driver class for the specific
database
hibernate.connection.url It represents the JDBC connection to the database
hibernate.connection.username It represents the user name which is used to connect to
the database
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

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

r
(A)

ka
an
Fig. 1
al
(1) The working of hibernate will state when persistent object i.e. POJO has been created
by the java application.
(2) Hibernate layer is divided into following different object which are use to perform
different operation.
dy

(i) Configuration :
(i) This object is used to establish a connection with the database.
(ii) It contains following 2 files
(a) hibernate. properties  it is use to give some additional information about the
hibernate layer.
(b) hibernate (f.g.  xml  It is use to establish a connection with a particular
Vi

database.)
(iii) Configuration object is also use to create session factory.
(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 :
 It is generally use to receive a persistent object inside the hibernate layer.
 Session object is responsible to create transaction object & perform appropriate
operation on persistent object.
(iv) Transaction :
 It is the optional object which is use to represent unit of work.
 It represent the starting & ending of the transaction on database.

20
Prelim Question Paper Solution

(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) What are the different types of layout in Java? Explain GridLayout. [5]
(A) 1. FlowLayout 2. BorderLayout 3. GridLayout
4. CardLayout 5. BoxLayout 6. GridBagLayout
7. Grid Layout

Grid Layout

r
A GridLayout object places components in a grid of cells. Each component takes all the
available space within its cell, and each cell is exactly the same size. If the GridLayoutDemo

ka
window is resized, the GridLayout object changes the cell size so that the cells are as large
as possible, given the space available to the container.

Layout Design
an
Sample Program or Code snippet
al
import java.awt.*;
import java.applet.*;
.
/*
dy

<applet code=”SimpleKey” width=300 height=300>


</applet>
*/
public class gridLayoutDemo extends Applet
{
static final int n = 4;
Vi

public void init()


{
setLayout (new GridLayout(n , n));
setFont (new Font(“SansSerif”, Font.BOLD, 24));
for(int i=0; i<n; i++)
{
for(j=0; j<n; j++)
{
int k =i*n+j;
if (k > 0)
add(new Button (“ ”+ k));
}
}
}
}

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

Q.7(b) Write a program to create a split pane in which left side of split Pane contains a [5]
list of planet 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());

String s[]={"earth","mercury","saturn"};
jl=new JList(s);
jl.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
an
i1=new ImageIcon("earth.jpg");
i2=new ImageIcon("mercury.png");
i3=new ImageIcon("saturn.jpg");

j=new JLabel(i1);

jsp=new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
al
jsp.setLeftComponent(jl);
jsp.setRightComponent(j);
jl.addListSelectionListener(this);
dy

c.add(jsp);

setSize(500,500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Vi

}
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
{

22
Prelim Question Paper Solution

j.setIcon(i3);
}
}
public static void main(String args[])
{
list l=new list();
}
}

Q.7(c) Explain CGI and its woring. Also wirte disadvantages of CGI. [5]
(A)
http reg.
web
Client CGI
Server
http res

r
DB

ka
Server

(i) CGI : Common gateway interface is responsible to provide dynamic response in case of
Three tire architecture.
(ii) Working :
 When webserver accept request which require dynamic response web server
an
forward the request to CGI.
 CGI is a program which accept the request & to handle that request create CGI.
Process & load that process inside the web server.
 Now that process is responsible to provide dynamic response to the client.
 Once this can be done web server destroy the process to free its memory.
(d) Three-tier architecture
al
http reg
web
Client
Server
http res
dy

DB
Server
(i) In this there exist three entity i.e. client, webserver & Database server.
(ii) Basically here server get distributed in web server & database server.
(iii) Web server is responsible to interact with client as well as database server.
Vi

(iv) Although this architecture minimize performance delay it has following


disadvantage.
(v) Disadvantage
(i) Single point failure can occure if the webserver get failed.
(ii) This architecture does not use to provide dynamic response.
(vi) Disadvantage
 CGI process are platform dependent process because they are implemented in C,
C++ pearl.
 It increase the overhead of webserver because every time a new process get
loaded & unloaded from web server.
 It is very difficult to implement CGI programming.
 Lack of scalablity if the number of client will get increase.
 Lack of security.
 It uses lots of webserver resources.
 Only one resource can be used at a time i.e. lack of resource sharing.

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

Q.7(d) Explain with suitable example <navigation-rule> element of faces-config.xml [5]


(A) <navigation-rule>

</navigation-rule>
The <navigation-rule> element represents an individual decision rule. This rule is accessed
when the default Navigation Handler is implemented. This rule helps make decisions on what
view to display next, based on the View ID being processed.

The <from-view-id> Element


<from-view-id> /index.xhtml </from-view-id>
The <from-view-id> element contains the view identifier bound to the view for which the
containing navigation rule is relevant. If no <from-view> element is specified, then this rule
automatically applies to navigation decisions on all views.
Since this element is not specified, a value of “*” is assumed, which means that this
navigation rule applies to all views.

r
The <navigation-case> Element

ka
<navigation-case>
- - -
- - -
</navigation-case>
The <navigation-case> element describes a specific combination of conditions that must
match, for this case to be executed. It also describes the view id of the component tree
an
that should be selected next.

The <from-outcome> Element


<from-outcome> login </from-outcome>

The <from-outcome> element contains a logical outcome string. This string is returned by
the execution of an application action method via an actionRef property of a UICommand
al
component.

If this element is specified, then this rule is relevant only if the outcome value matches this
element’s value.
If this element is not specified, then this rule is relevant no matter what the outcome value
dy

was.

The <to-view-id> Element


<to-view-id> / Welcome.xhtml </to-view-id>
The <to-view-id> element contains the view identifier of the next view that must be
displayed when this navigation rule is matched.
Vi

Example
<navigation-rule>
<from-view-id>/pages/inputname.jsp</from-view-id>
<navigation-case>
<from-outcome>sayHello</from-outcome>
<to-view-id>/pages/greeting.jsp</to-view-id>
</navigation-case>
<navigation-case>
<from-outcome>sayGoodbye</from-outcome>
<to-view-id>/pages/goodbye.jsp</to-view-id>
</navigation-case>
</navigation-rule>
This code specifies that view /pages/inputname.jsp has two outputs, sayHello and
sayGoodbye, associated with particular pages.

24
Prelim Question Paper Solution

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


It is use to perform those operation which can be operated through out the JSP page.
e.g.:
<% @ page import = “java.10*” %>
<% @ page session = “true”%>
<% @ Page language = “java”%>
<% @ Page content Type = “text/html”%>

r
(b) Include directive tag :
It is use to include the contents of one JSP application inside the current JSP

ka
application.
e.g.
<%@ include file = “abc.jsp” %>

(c) taglib directive tag :


Inside the JSP application, if we want to use some other tag apart from html & JSP
an
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.
al
<%! int a = 2; %>

(e) Expression tag


It is use to display the value of a particular variable or an expression on a web browser.
dy

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

e.g.
<%
___
___ java code
___
>

(d) Comment tag


It is use to write comment inside jsp page. A comment is non executable statement
which is use to provide some additional information about the some instruction.
e.g.
<%   comment   %>

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

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


(A) <?xml version=”1.0” encoding=”UTF8”?>
<hibernatemapping>

<class name=”guestbook” table=”guestbooktable”>

<property name=”name” type=”string”>


<column name=”username” length=”50” />
</property>

<property name=”message” type=”string”>


<column name=”usermessage” length=”100” />
</property>

r
</class>
</hibernatemapping>

ka
Elements:
<hibernatemapping>….......</hibernatemapping>
It is the base tag which is used to write hibernate mapping file, which is used to map POJO
class with database table.
an
<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>
al
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
dy

<column>….......</column>
It is used to write the database column which we want to map with java class property. It
has 2 parameters:
name It represents name of the column
length It represents maximum length of a column value
Vi



26

You might also like