-
1
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.
JFrame frm1 = new JFrame(); JPanel op = new JPanel(); frm1 .add
(op, BorderLayout.NORTH);
Example import java.awt.*; import javax.swing.*;
class BorderTest extends JFrame {
public static void main(String[] args) { JFrame window = new
BorderTest(); window.setVisible(true); } BorderTest() {
Vidy
alank
ar
-
Vidyalankar : T.Y. B.Sc. (IT) – Adv. Java
2
//... 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); 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 the Java event delegation model. [5](A)
[Explanation 2 marks, Explanation of Event, event source,
Event Listeners – 2marks, Program 1 marks] The Java event
delegation model. Java Event Delegation model defines standard and
consistent
mechanisms to generate and process events. The source generates
an event and sends it to one or more listeners. The listener simply
waits until it receives an event. Once the event is received, the
listener processes the event and
returns. The advantage of this design is that the application
logic that processes
events is cleanly separated from the user interface logic that
generates those events.
The user interface element is able to ‘delegate’ the processing
of an event to a separate piece of code.
In this event model, listeners must register with a source in
order to receive an event notification.
Vidy
alank
ar
-
Prelim Question Paper Solution
3
This provides an important benefit : notifications are sent only
to listeners that want to receive them. Events : In the delegation
model, an event is an object that describes a
state change in a source. It can be generated as a consequence
of a person interacting with the elements in a graphical user
interface. Example Pressing a button.
Event Source : is an object that generates an event. This occurs
when the internal state of that object change in some way. A source
must register listeners in order to receive notifications about a
specific type of event.
Example: public void addTypeListener(TypeListener el) Event
Listeners : a Listener is an object that is notified when an
event
occurs. It has two requirements, first, it must have been
registered with one or more sources to receive notifications about
specific type of events and second, it must implement methods to
receive and process these notifications. Example : import
java.awt.*; import java.awt.event.*; import java.applet.*; /* */
public class SimpleKey extends Applet implements KeyListener {
String msg = “ ” ; int X = 10, Y=20; public void init() {
addKeyListener(this); } public void KeyPresses(KeyEvent ke) {
showStatus(“Key Down”); } public void KeyReleased(KeyEvent ke)
Vidy
alank
ar
-
Vidyalankar : T.Y. B.Sc. (IT) – Adv. Java
4
{ showStatus(“Key Up”); } public void KeyTyped(KeyEvent ke) {
msg += ke.KeyChar(); repaint(); } public void paint(Graohics g) {
g.drawString(msg, X, Y); } }
Q.1(c) Write a short note on “Event Listeners”. Explain the
working with
code [5]
(A)
[Explanation 1 marks, Example 2
marks, Program 2 marks] A listener is an object that is notified
when an event occurs. It has two major requirements. It must have
been registered with one or
more sources to receive notifications about specific types of
events. Second, it must implement methods to receive and process
these
notifications. The methods that receive and process events are
defined in a set of
interfaces found in java.awt.event. For example: The
MouseMotionListener interface defines two methods
to receive notifications when the mouse is dragged or moved.
void mouseDragged(MouseEvent me) – method is called multiple times
as the mouse is dragged. void mouseMoved(MouseEvent me) - method is
called multiple times as the mouse is moved.
Any object may receive and process one or both of these events
if it provides an implementation of this interface.
Example : import java.awt.*; import java.awt.event.*; import
java.applet.*; /* */
Vidy
alank
ar
-
Prelim Question Paper Solution
5
public class MouseEvents extends Applet implements
MouseListener, MouseMotionListener { String msg = " "; int mouseX =
0, mouseY = 0; public void init() { addMouseMotionListener(this); }
//handle mouse dragged public void mouseDragged(MouseEvent me) {
//save coordinates mouseX = me.getX(); mouseY = me.getY(); msg =
"*"; showStatus("Dragging mouse at " + mouseX + ", " + mouseY); }
//handle mouse moved public void mouseMoved(MouseEvent me) { //show
status showStatus("Moving mouse at " + me.getX()+ ", " +
me.getY()); } //Display message in the applet window at current X,Y
location public void paint(Graphics g) {
g.drawString(msg,mouseX,mouseY); } }
Q.1(d) What are adapter classes? What are inner classes? Explain
withexamples.
[5]
(A) Adapter Classes: [1 Marks] An adapter class provides the
default(empty) implementation of all
methods in an event listener interface. Adapter classes are very
useful when one wants to process only few of
the events that are handled by a particular event listener
interface. One can define a new class by extending one of the
adapter classes and
implement only those events relevant to the program.
Vidy
alank
ar
-
Vidyalankar : T.Y. B.Sc. (IT) – Adv. Java
6
Example : [1½ Marks] import java.awt.*; import java.awt.event.*;
import java.applet.*; public class AdapterDemo extends MouseAdapter
{ public void init() { addMouseListener(new MyMouseAdapter(this));
addMouseMotionListener(new MyMouseMotionAdapter(this)); } } class
MyMouseAdapter extends MouseAdapter { AdapterDemo adDemo1; public
MyMouseAdapter(AdapterDemo adDemo2) {
adDemo1 = adDemo2; } //handles mouse clicked and ignores all
other events. public void mouseClicked(MouseEvent me) {
adDemo1.showStatus(“Mouse clicked”); } }
Inner Classes [1 Marks] Inner classes are class within Class.
Inner class instance has special relationship with Outer class.
This special relationship gives inner class access to member of
outer class as if they are the part of outer class. Example: [1½
Marks] import java.applet.*; import java.awt.event.*; /* */
Vidy
alank
ar
-
Prelim Question Paper Solution
7
public class InnerClassDemo extends Applet { public void init()
{ addMouseListener(new MyMouseAdapter()); } class MyMouseAdapter
extends MouseAdapter { public void mousePressed(MouseEvent me) {
showStatus(“Mouse Pressed”); } } }
Q.2 Attempt the following (any TWO) [10]Q.2(a) Write a Java
program using JCheckBox and JRadioButton to get the
following output. Once the items are chosen and Place order
buttonis clicked, the items selected should be displayed in the
commandline.
[5]
(A) import java.awt.*; import java.awt.event.*; import
javax.swing.*; class test extends Jprame implements ActionListener
{
JCheckBox jc1, jc2, jc3; JRadioButton jr1, jr2, jr3; Button
Group bg; JButton jb; test( ) {
Container C2 getContentPane( ); C.setLayout(newFlowLayout());
jc1 = new JCheckBox(“ketchup”); jc2 = new JCheckBox(“Mustard”); jc3
= new JCheckBox(“Pickles”);
Pickles
Order
Vidy
alank
ar
-
Vidyalankar : T.Y. B.Sc. (IT) – Adv. Java
8
jr1 = new JRadioButton(“Grilled”); jr2 = new
JRadioButton(“Chicken”); jr3 = new JRadioButton(“Veggie”); bg = new
ButtonGroup( ); bg.add(jr1); bg.add(jr2); bg.add(jr3);
jb=newJButton(“Place order”); jb.addActionListener(this);
c.add(jc1); c.add(jc2); c.add(jc3); c.add(jr1); c.add(jr2);
c.add(jr3); c.add(jb); setsize(1000, 1500); setvisible (true);
} public void actionPerformed (ActionEvent as) {
if (jc1.isSelected( )) {
System.out.println(jc1.getText()); } if(jc2.isSelected( )) {
System.out.println(jc2.getText( )); } if(jc3.isSelected( ))
{
System.out.println(jc3.getText( )); } if(jr1.isSelected( ))
{
System.out.println(jr1.getText( )); } if(jr2.isSelected( ))
{
System.out.println(jr2.getText( )); } if(jr3.isSelected( ))
{
System.out.println(jr3.getText( )); }
Vidy
alank
ar
-
Prelim Question Paper Solution
9
public static void main (string a[]) {
text t = new test( ); }
} }
Q.2(b) How can a Tree structure be created in Swing?
Explain.in
JOptionPane in detail. [5]
(A) A tree structure is created in the following ways [2 Marks]
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.*; [3 Marks] import java.awt.*; import
javax.swing.event.*; import javax.swing.tree.*; import
javax.swing.*; public class JTreeExample extends JFrame{ public
JTreeExample() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DefaultMutableTreeNode everything = new
DefaultMutableTreeNode("Everything"); JTree avm = new
JTree(everything); DefaultMutableTreeNode animal = new
DefaultMutableTreeNode("Animal"); everything.add(animal);
animal.add(new DefaultMutableTreeNode("Cat")); animal.add(new
DefaultMutableTreeNode("Dog")); animal.add(new
DefaultMutableTreeNode("Fish")); DefaultMutableTreeNode vegetable =
new
Vidy
alank
ar
-
Vidyalankar : T.Y. B.Sc. (IT) – Adv. Java
10
DefaultMutableTreeNode("Vegetable"); everything.add(vegetable);
vegetable.add(new DefaultMutableTreeNode("Onion"));
vegetable.add(new DefaultMutableTreeNode("Lettuce"));
vegetable.add(new DefaultMutableTreeNode("Carrot"));
DefaultMutableTreeNode fruits = new
DefaultMutableTreeNode("Fruits");
everything.add(fruits); 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(); } }
Q.2(c) How to divide frame window in two parts. Explain with
code
specification. [5]
(A) A frame window can be divided into two parts using
JSplitPane component. [2 Marks]
A frame can be divided into two parts either vertically or
horizontally. In the following code, a frame is divided into two
parts horizontally. Firstly, the object of JSplitPane is created.
Then its setOrientation() method is used to set the orientation,
either
Horizontal or Vertical.
import java.awt.*; [3 Marks] import java.awt.event.*; import
javax.swing.*;
public class JSplitPaneDemo {
public static void main(String[] args) { JFrame frame = new
JFrame(“JSplitPane demo”);
Vidy
alank
ar
-
Prelim Question Paper Solution
11
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JSplitPane
sp = new JSplitPane();
sp.setOrientation(JSplitPane.HORIZONTAL_SPLIT);
frame.getContentPane().add(sp, BorderLayout.CENTER);
frame.setSize(500,500); frame.setVisible(true); } }
Q.2(d) What is the purpose of tabbed panes? Explain with
suitable
example. [5]
(A) Purpose of TabbedPanes : [2 Marks] 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: [3 Marks] 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[]) { 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 { public CitiesPanel () { JButton b1 = new
JButton("New York");
Vidy
alank
ar
-
Vidyalankar : T.Y. B.Sc. (IT) – Adv. Java
12
add(b1); } } class ColorsPanel extends JPanel { public
ColorsPanel () { JButton b1 = new JButton("Blue"); add(b1); } }
Q.3 Attempt the following (any TWO) [10]Q.3(a) Write a Servlet
program to display the simple sentence Welcome
along with the name entered by the user through an HTML form.
[5]
(A) Index.jsp [1 Marks] JSP Page Name : WelcomeServlet.java [4
Marks] import java.io.*; import java.net.*;
import javax.servlet.*; import javax.servlet.http.*; public
class WelcomeServlet extends HttpServlet { protected void
processRequest(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
Vidy
alank
ar
-
Prelim Question Paper Solution
13
response.setContentType("text/html;charset=UTF-8"); PrintWriter
out = response.getWriter(); try { out.println(""); out.println("");
out.println("Servlet WelcomeServlet"); out.println("");
out.println(""); out.println("Servlet WelcomeServlet at " +
request.getParameter ("txtName") + ""); out.println("");
out.println(""); } finally { out.close(); } }
Q.3(b) Explain the generic servlet and HTTP servlet. [5](A)
Generic Servlet: [1 Marks]
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.
Generic Servlet only supports service() method.
Generic Servlet Request Handling
[1½ Marks] Vidy
alank
ar
-
Vidyalankar : T.Y. B.Sc. (IT) – Adv. Java
14
HttpServlet: [1 Marks] HttpServlet class is the direct subclass
of Generic Servlet. HttpServlet is protocol dependent. It handles
only http protocol. HttpServlet supports public void
service(ServletRequest
req,ServletResponse res ) and protected void
service(HttpServletRequest req,HttpServletResponse res).
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.
The service() method of HttpServlet handles the setup and
dispatching to all the doXXX() methods
HTTP servlet request handling
Q.3(c) Explain the importance of request dispatcher of servlet
in inter
servlet communication. [5]
(A) RequestDispatcher object: [1 Marks] RequestDispatcher object
is used in the servlets to implement request
dispatching. A Servlet recives the client request, does the
processing partially and
hands over the request processing duty to another servlet. This
mechanism is known as request dispatching.
Inter servlet communication is implemented using
RequestDispacher object. In a servlet one can get RequestDispatcher
object reference in two ways. [2 marks] 1. RequestDispatcher rd =
context.getRequestDispatcher(String
absolutepath); 2. RequestDispatcher rd =
request.getRequestDispatcher(String
relativepath);
[1½ Marks]
Vidy
alank
ar
-
Prelim Question Paper Solution
15
If the ServletContext object is used to get the
RequestDispatcher, absolute URL of the target resource is to be
supplied. If HttpServletRequest is used to get the
RequestDispatcher object, only relative url of the target resource
is to be supplied. Request dispatching can be implemented in two
ways. [2 Marks]
Forward mechanism - Forwards a request from a servlet to another
resource such as Servlet, JSP or HTML file on the server.
Include mechanism - includes the contents of a resource such as
Servlet, JSP, HTML file in the response.
Q.3(d) Explain the life cycle phases of servlet. [5](A) [Listing
of phases 1 marks, Explanation of all phases 3 marks,
Diagram 1 marks] Servlet Lifecycle [1 Marks] The servlet
lifecycle consists of the following phases: Loaded Instantiated
Initialized Service request Destroyed Finally garbage collected 1.
Loaded - As soon as there is a request for a servlet, it is loaded
on the
JVM, if it does not exist. A servlet is only loaded once. 2.
Instantiated - After loading the servlet, it is instantiated i.e.
an object
of the requested servlet class is created to service the
request. 3. Initialized - Post instantiation, the servlet’s
init(ServletConfig config)
method is called in order to initialize the servlet.
The init() method is defined as public void init(ServletConfig
config) throws ServletException During initialization, the servlet
has access to two objects: ServletConfig ServletContext
The following are the most common tasks that are implemented in
the init() method: Reading initialization parameters Reading
configuration data from persistent resource like a config
file Initializing a database driver Opening a JDBC connection
Writing of information to a network resource
Vidy
alank
ar
-
Vidyalankar : T.Y. B.Sc. (IT) – Adv. Java
16
4. Service Request - Only after the completion of the init()
method, the service() method is invoked.
Once the server has loaded and initialized the servlet, it is
able to handle client requests through the service() method. Each
client request to the service() method is run in a separate servlet
thread. The service() method is defined as follows: public void
service(ServletRequest req, ServletResponse res) throws
ServletException, IOException The ServletRequest object helps in
accessing the original request data and the ServletResponse object
provides methods that help in building a response.
5. Destroyed - Post servicing the request, the servlet can be
unloaded by
calling the destroy() method.ll resources which were allocated
by init() should be released by destroy(). The destroy() method is
defined as public void destroy() throws ServletException This
method is only called once in the lifetime of a servlet. The most
common tasks in the destroy() method are: Synchronizing cleanup
tasks such as closing open resources or closing
a connection pool Informing other applications that the servlet
will no longer be available
Vidy
alank
ar
-
Prelim Question Paper Solution
17
Q.4 Attempt the following (any TWO) [10]Q.4(a) What is JDBC
driver? Explain the types of JDBC drivers. [5](A) JDBC driver :
JDBC drivers implement the defined interfaces in the JDBC
API for interacting with your database server. For example,
using JDBC drivers enable you to open database connections and to
interact with it by sending SQL or database commands then receiving
results with Java. The Java.sql package that ships with JDK
contains various classes with their behaviours defined and their
actual implementaions are done in third-party drivers. Third party
vendors implements thejava.sql.Driver interface in their database
driver. JDBC Driver Types: There are four categories of drivers by
which developer can apply a connection between Client (The JAVA
application or an applet) to a DBMS. 1. Type 1 Driver : JDBC-ODBC
Bridge. (Platform dependent) 2. Type 2 Driver : Native-API Driver
(Partly Java driver). (Platform dependent) 3. Type 3 Driver :
Network-Protocol Driver (Pure Java driver for database
Middleware). (Platform independent) 4. Type 4 Driver :
Native-Protocol Driver (Pure Java driver directly
connected to database). (Platform independent) 1. Type 1 Driver:
JDBC-ODBC Bridge :
The JDBC type 1 driver which is also known as a JDBC-ODBC Bridge
converts JDBC methods into ODBC function calls. Sun provides a
JDBC-ODBC Bridge driver by “sun.jdbc.odbc.JdbcOdbcDriver”. The
driver is a platform dependent because it uses ODBC which is
depends on native libraries of the operating system and also the
driver needs other installation for example, ODBC must be installed
on the computer and the database must support ODBC driver. Type 1
is the simplest compare to all other driver but it’s a platform
specific i.e. only on Microsoft platform. The JDBC-ODBC Bridge is
use only when there is no PURE-JAVA driver available for a
particular database.
Vidy
alank
ar
-
Vidyalankar : T.Y. B.Sc. (IT) – Adv. Java
18
Architecture Diagram:
Process: Java Application → JDBC APIs → JDBC Driver Manager →
Type 1 Driver → ODBC Driver → Database library APIs → Database
Advantage: Connect to almost any database on any system, for which
ODBC
driver is installed. It’s an easy for installation as well as
easy(simplest) to use as
compare the all other driver. Disadvantage: The ODBC Driver
needs to be installed on the client machine. It’s a not a purely
platform independent because its use ODBC which is
depends on native libraries of the operating system on client
machine. Not suitable for applets because the ODBC driver needs to
be
installed on the client machine.
2. Type 2 Driver: Native-API Driver (Partly Java driver) The
JDBC type 2 driver uses the libraries of the database which is
available at client side and this driver converts the JDBC method
calls into native calls of the database so this driver is also
known as a Native-API driver.
Vidy
alank
ar
-
Prelim Question Paper Solution
19
Architecture Diagram:
Process: Java Application → JDBC APIs → JDBC Driver Manager →
Type 2 Driver → Vendor Client Database library APIs → Database
Advantage: There is no implantation of JDBC-ODBC Bridge so it’s
faster than a
type 1 driver; hence the performance is better as compare the
type 1 driver (JDBC-ODBC Bridge).
Disadvantage: On the client machine require the extra
installation because this
driver uses the vendor client libraries. The Client side
software needed so cannot use such type of driver in
the web-based application. Not all databases have the client
side library. This driver supports all JAVA applications except
applets.
3. Type 3 Driver: Network-Protocol Driver (Pure Java driver for
database Middleware) The JDBC type 3 driver uses the middle
tier(application server) between the calling program and the
database and this middle tier converts JDBC method calls into the
vendor specific database protocol and the same driver can be used
for multiple databases also so it’s also known as a
Network-Protocol driver as well as a JAVA driver for database
middleware.
Vidy
alank
ar
-
Vidyalankar : T.Y. B.Sc. (IT) – Adv. Java
20
Architecture Diagram:
Process: Java Application → JDBC APIs → JDBC Driver Manager →
Type 3
Driver → Middleware (Server)→ any Database Advantage: There is
no need for the vendor database library on the client
machine because the middleware is database independent and it
communicates with client.
Type 3 driver can be used in any web application as well as on
internet also because there is no any software require at client
side.
A single driver can handle any database at client side so there
is no need a separate driver for each database.
The middleware server can also provide the typical services such
as connections, auditing, load balancing, logging etc.
Disadvantage: An Extra layer added, may be time consuming. At
the middleware develop the database specific coding, may be
increase complexity.
4. Type 4 Driver: Native-Protocol Driver (Pure Java driver
directly connected to database) The JDBC type 4 driver converts
JDBC method calls directly into the vendor specific database
protocol and in between do not need to be converted any other
formatted system so this is the fastest way to communicate quires
to DBMS and it is completely written in JAVA because of that this
is also known as the “direct to database Pure JAVA driver”.
Vidy
alank
ar
-
Prelim Question Paper Solution
21
Architecture Diagram:
Process: Java Application → JDBC APIs → JDBC Driver Manager →
Type 4
Driver (Pure JAVA Driver) → Database Server
Advantage: It’s a 100% pure JAVA Driver so it’s a platform
independence. No translation or middleware layers are used so
consider as a faster
than other drivers. The all process of the
application-to-database connection can manage
by JVM so the debugging is also managed easily. Disadvantage:
There is a separate driver needed for each database at the client
side. Drivers are Database dependent, as different database vendors
use
different network protocols. Q.4(b) Explain the prepared
statement with suitable example. [5](A) Prepared Statements [2
Marks]
PreparedStatement object is used to send SQL statements to the
database.
This special type of statement is derived from a class,
Statement. Although PreparedStatement objects can be used for SQL
statements
with no parameters, they can also used with SQL statements that
take parameters.
The advantage to this is that in most cases, this SQL statement
is sent to the DBMS, where it is compiled. As a result, the
PreparedStatement object contains not just a SQL statement, but a
SQL statement that has been precompiled. This means that when the
PreparedStatement is executed, the DBMS can just run the
PreparedStatement SQL statement without having to compile it
first.
Vidy
alank
ar
-
Vidyalankar : T.Y. B.Sc. (IT) – Adv. Java
22
The advantage of using SQL statements that take parameters is
that you can use the same statement and supply it with different
values each time you execute it.
The syntax: [1 Marks] PreparedStatement objectname =
connctionObject.prepareStatement(SQLQrery) ;
For example PreparedStatement p =
conn.prepareStatement(queryString) ;
Where conn is the connection object.
Before executing the Preparedstatement, the host variables must
be bound to actual values with a set method.
Then execute the statement by calling object’s executeUpdate
method. p.executeUpdate();
Example [2 Marks] String sql = “select * from people where
firstname=? And lastname=?” ; preparedStatement ps = connection.
preparedStatement(sql); preparedStatement.setString(1, “John”);
preparedStatement.setString(2, “Smith”); ResultSet rs =
preparedStatement.executeQuery();
Q.4(c) Enlist the implicit objects of JSP. Explain any 4 of them
in detail. [5](A) [Listing 1 marks, Explanation of 4 objects 4
marks]
Following are the implicit objects of JSP 1. Request 2. Response
3. Out 4. Session 5. Application 6. Config 7. PageContext 8. Page
9. Exception 1. Request
The Request object provides access to all information associated
with a request including its source, the requested URL and any
headers, cookies or parameters associated with the request.
Vidy
alank
ar
-
Prelim Question Paper Solution
23
It encapsulates the request coming from the client and being
processed by the JSP.
The Request object is an instance of
javax.servlet.HttpServletRequest The following are the methods
available to the request object
Method Description
getParameters() Returns the value of a request parameter as a
String.
getParameterNames() Returns an Enumeration of String objets
containing the name of the parameters contained in this request
getParameterValues() Returns an array objects containing all the
values, the given request parameter has.
2. Response : This object represents the response sent back to
the user browser
as a result of processing the JSP page. It encapsulates the
response generated by the JSP. This is the response being sent back
to a client browser in response
to its request. The Response object is an instance of
javax.servlet.http.HttpServletResponse The following are the
methods available to the response object
Method Description addCookie() Adds the specified cookie to the
response. sendRedirect() Sends a temporary resirect response to the
client
using the specified redirect location URL.
3. Out : The Out object represents the output stream of the JSP
page, the
contents of which are being sent to a client browser. The out
object is the PrintWriter, which is used to send output to
the client. The following are the methods available to the out
object
Method Description clear() Clears the contents of the buffer and
throws an
exception if some data has already been written to the output
stream.
close() Flushes and then closes the output stream. print()
Prints the specified primitive data type such as
Object or String to the client.
Vidy
alank
ar
-
Vidyalankar : T.Y. B.Sc. (IT) – Adv. Java
24
4. Session: A session refers to the entire conversation between
a client and a
server. It allows accessing a client’s session data, managed by
the server. Sessions are created automatically. Sessions are used
to maintain state and user identity across multiple
page requests. The following are the methods available to the
session object
Method Description inNew() A session is considered to be new if
it is been
created by the server, but the clients has not yet acknowledged
joining the session.
invalidate() Discards the session, releasing any objects stored
as attributes.
getAttribute() Retrieves the object associated with the named
attribute.
Q.4(d) Write a jsp that accepts user-login details and forward
the result
either “Access Granted” or “Access Denied” to result.jsp. 1.
HTML 2. JSP 3. JSP
[5]
(A) Login.html [5 Marks]
J1.jsp
Vidy
alank
ar
-
Prelim Question Paper Solution
25
JSP Page Result.jsp JSP Page
Vidy
alank
ar
-
Vidyalankar : T.Y. B.Sc. (IT) – Adv. Java
26
Q.5 Attempt the following (any TWO) [10]Q.5(a) Enlist the
lifecycle phases of JSF. Explain the following phases in
detail. [5]
(A) [Listing 1 Marks, Explanation of 4 phases 4 marks]
The JSF lifecycle has the following six phases, which are
defined by the JSF specification : Restore view Apply Request
Values Process validations Update Model Values Invoke application
Render Response
These six phases show the order in which JSF typically processes
a FORM. Restore View : in this first phase of JSF life cycle, a
request comes through the
FacesServlet controller. When a request is made for a JSF page,
the JSF implementation t
the JSF framework controller uses the view ID to look up the
components for the current view. If the view does not already
exist, the JSF controller creates it. If the view already exists,
the JSF controller uses it. Te view contains all the GUI
components.
During this phase, the JSF implementation- Builds the view of
the page. Wires event handlers and validators to components in the
view
Vidy
alank
ar
-
Prelim Question Paper Solution
27
Saves the view in the FacesContext instance, which contains all
the information needed to process a single request.
This phase presents three view instances : new view, initial
view and postback.
New view - JSF builds the view of the Faces page and wires the
handlers and validators to components in the view and this view is
saves in the FAcesContext object.
Inital view - JSF creates an empty view. It will be populated as
the user causes events to occur. From an initial view, JSF advances
directly to the render response phase.
� Postback - , the view corresponding to the page already
exists, so it needs only to be restored
Apply Request Values the purpose of the apply request phase is
for each component to
retrieve current state. The components must first be retrieved
or created from the FacesContext object, followed by their
values.
If a component’s immediate event handling property is not set to
true, the values are just converted.
� If a component’s immediate event handling property is set to
true, the values are converted to the proper type and
validated.
Update Model Values It updates the actual values of the
server-side model by updating the
properties of managed beans. Only bean properties that are bound
to component’s value will be
updated. This phase happens after validation, so one can be sure
that the values
copied to the bean’s properties are valid.
Render Response In this phase, the view is displayed with all of
its components in their
current state.
Q.5(b) Explain the advantages of EJB. [5](A) Complete focus only
on Business Logic [5 Marks]
Enterprise Beans live and run in the server under the control of
an EJB container.
The EJB container provides all the big infrastructure services
such as Security, Concurrency, Transaction management, Networking,
Resource management, Persistence, Massaging and Customization
during deployment.
Vidy
alank
ar
-
Vidyalankar : T.Y. B.Sc. (IT) – Adv. Java
28
Developer can use these services with minimal effort and time,
thus making writing an enterprise bean as simple as writing a Java
class.
EJB model seperates system level services from the business
logic. This allows the server vendor to concentrate on system level
functionalities while the developer can concentrate more on only
the business logic for the domain specific application.
1. Reusable Components
Each EJB is a reusable building block. An EJB can be reused by
assembling them in several different
applications. For each application, making simple changes in
deployment descriptor without the source code can customize its 28
behavior with the underlying services.
2. Portable
EJB use Java language, which is portable across multiple
platforms. The components can run on any platform and are
completely portable
across any vendor’s EJB-compliant application server. The EJB
environment automatically maps the component to the
underlying vendor-specific infrastructure services. 3. Fast
building of Application
The EJB architecture simplifies building complex enterprise
applications.
With the component-based EJB architecture, the development,
enhancing the functionalities and maintenance of complex enterprise
applications becomes easier.
With its clear definition of roles and well defined interfaces,
the EJB architecture promotes and supports team-based development
and lessens the demands on individual developers.
Q.5(c) Write a session bean code specification that calculates
compound
interest. Assume the principal, terms and rate of interest is
entered bythe user and the input is passed through a servlet.
[5]
(A) //index.html < html > < body > < form method
= “post” action = “test” >, Principal amount < input type =
“text” name = “a” value = “ “ Size = “10” >, No of terms
Vidy
alank
ar
-
Prelim Question Paper Solution
29
< input type = “text” name = “b” value = “ “ Size = “10”
>, Rate of interest < input type = “text” name = “c” value =
“ “ Size = “10” >, < input type = “submit” value = “Compound
Interest”> < / form > < / body > // test.java
(servlet) import javax . servlet . *; import javax . servlet . http
. * ; import java . io. * ; public class test extends HttpServlet
< public void dopost (HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException < res.setContentType
(“text/html”); PrintWriter pw = res.getwriter) ; int i =
Integer.parseInt (req.getParameter (“0”)); int n = Integer.parseInt
(req.getParameter (“b”)); int r = Integer.parseInt
(req.getParameter (“c”)); compound C = new Compound ( );
pw.printInt compound intrest. t
-
Vidyalankar : T.Y. B.Sc. (IT) – Adv. Java
30
Q.5(d) Write a session bean code specification that calculates
compoundinterest. Assume the principal, terms and rate of interest
isentered by the user and the input is passed through a
servlet.
[5]
(A) import java.rmi.RemoteException; import
javax.ejb.SessionBean; import javax.ejb.SessionContext; /** This
class contains the implementation for the
`calculateCompoundInterest'
method exposed by this Bean. It includes empty method bodies for
the methods prescribe by the SessionBean interface; these don't
need to do anything in this simple example.
*/
public class InterestBean implements SessionBean { /**
Calculates the compound interest on the sum `principle', with
interest rate
per period `rate' over `periods' time periods. This method also
prints a message to standard output; this is picked up by the EJB
server and logged. In this way we can demonstrate that the method
is actually being executed on the server, rather than the
client.
*/ public double calculateCompoundInterest(double principle,
double rate, double periods) { System.out.println ("Someone called
`calculateCompoundInterest!'"); return principle * Math.pow(1+rate,
periods) - principle; } Q.6 Attempt the following (any TWO)
[10]Q.6(a) Explain the different roles of Action in struts
framework. [5](A) Action is the heart and soul of the Struct
framework. It processes input and
interacts with other layers of the application. [1 Marks]
Roles of Action [4 Marks] 1. Perform As a model
Action performs as a Model by encapsulating the actual work to
be done for a given request based on the input parameters.
Encapsulation is done using the execute() method. The code spec
inside this method should only hold the business logic to serve a
Request.
Vidy
alank
ar
-
Prelim Question Paper Solution
31
Code spec: public String execute() { setWelcomeMessage(MESSAGE +
getUserName()); return “SUCCESS”; }
2. Serves as a Data Carrier Action serves as a data carrier from
Request to the View. Action being the Model component of the
framework carries the
data around.. The data that it requires is held locally which
makes it easy to
access using JavaBeans properties during the actual execution of
the business logic.
3. Helps determine the results
Action determines the Result that will render the View that will
be returned in the request’s response. This is achieved by
returning a control string that selects the result that should be
rendered.
4. Single Or Multiple Results The most basic action performs the
required task and always results
a single result. An action can also return different results
depending on the complexity of the –business logic.
Q.6(b) Explain in brief MVC architecture with help of suitable
diagram. [5](A)
MVC architecture has three different sections – i) Model ii)
View iii) Controller
Vidy
alank
ar
-
Vidyalankar : T.Y. B.Sc. (IT) – Adv. Java
32
In the MVC design pattern, the application flow is mediate by a
Controller. The controller delegates HTTP request to an appropriate
handler. A Handler is a set of logic that is used to process the
request. In the
Strct framework, the handlers are called as Actions. The
handlers are tied to a Model and each handler acts as an adapter
or
bridge, between the Request and the Model. A handler or action
may use one or more JavaBeans or EJBs to perform the actual
business logic.
The Action gets any information out of the request necessary to
perform the desired business logic and then passes it to the
JavaBean or EJB.
Technically : Using web based data entry form information is
submitted to the server. The controller receives such requests and
to serve them calls the
appropriate handler i.e. Action. Action passes the request by
interacting with the application specific
model code. Model returns a result to inform the Controller
which output page to be
sent as a response. Information is passes between Model and View
in the form of special
JavaBeans. A powerful Tag Library allows reading and writing the
content of these
beans from the presentation layer without the need for any
embedded java code spec.
From the development point of view, structs :
> Provides a Controller > Facilitates writing templates to
form the View i.e. the presentation layer. > Facilitates writing
the Model code specs. A central configuration file called
struts.xml binds all these [Model,
View, Controller] together. Q.6(c) Explain web.xml and
struts.xml files. [5]
(A) Web.xml [2 ½ Marks] the web.xml web application descriptor
file represents the core of the
java web application, so it is appropriate that it is also part
of the core of Struct Framework
in this file, Struts defines I ts Filedispatcher, the Servler
filter class that initializes the Struts framework and handles all
requests. Vidy
alank
ar
-
Prelim Question Paper Solution
33
This filtr can contain initialization parameters that affect
what, if any, additional configuration files are loaded and how the
framework should behave.
Struts also provides an ActionContextCleanUp class that handles
special cleanup tasks when other filters need access to an
initialized Struts framework.
Key Initialization Parameters : Config - a comma delimited list
of XML configuration files to load. actionPac scan for actkages – a
comma delimited list of Java packages
Actions. configProviders - a comma delimited list of Java
classes that implement
the ConfigurationProvider interface that should be used for
building the configuration.
loggerFactory – The class name of the LoggerFactory
implementation. * - any other parameter are treated as framework
constants. Struts.xml [2 ½ Marks] The Struts framework uses this
configuration file to initialize its own
resources. These resources include – Interceptors that can
preprocess and postprocess a request. Action classes that can call
business logic and data access code. Results that can prepare views
using JavaServer Pages, Velocity and
FreeMarker templates. The struts.xml is the core configuration
file for the framework and it
should be present in the class path of web application. This
file allows to break big struts.xml file into cmall files and
configuration files to be included as needed. Example -----
----- ---- ----
Vidy
alank
ar
-
Vidyalankar : T.Y. B.Sc. (IT) – Adv. Java
34
Q.6(d) Explain the architecture of hibernate framework in
details. [5](A)
JTA – Java Transaction API JDBC – Java Database Connectivity
JNDI – Java Naming and Directory Interface
Configuration Object [4 Marks] This object represents a
configuration or properties file for hibernate.
It is usually created once during application initialization.
The configuration object reads the properties to establish a
database
connection. A Configuration object is spawned to create a
SessionFactory.
Session Factory The SessionFactory is created with the help of a
Configuration object
during the application start up. It serves as a factory for
spawning Session objects when required.
Typically, it is crated once and kept alive for later use. The
applications that require interacting with multiple databses,
multiple
SessionFactory objects are created.
Session Session objects are lightweight and inexpensive to
create. They provide
the main interface to perform actual database operations.
[1 Marks]
Vidy
alank
ar
-
Prelim Question Paper Solution
35
All the persistent objects are saved and retrieved with the help
of a Session object.
Typically, session objects are created as needed and destroyed
when not required.
Transaction A transaction represents a unit of work the
database. Any kind of modifications initiated via the session
object are placed
within a transaction. A session object helps creating a
Transaction object.
Transaction objects are used for a short time and are closed by
either committing or rejecting.
Query Persistent objects are retrieved using a Query object.
Query objects allow using SQL or Hibernate Query Language (HQL)
queries to retrieve the actual data from the database and create
objects.
Criteria Persistent objects can also be retrieved using a
Criteria object. Criteria uses an object/method means of
constructing and executing a
request to retrieve objects. 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 [1 Marks]
Grid Layout [2 Marks] 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 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.
Vidy
alank
ar
-
Vidyalankar : T.Y. B.Sc. (IT) – Adv. Java
36
Layout Design [1 Marks]
Sample Program or Code snippet [1 marks] import java.awt.*;
import java.applet.*; . /* */ public class gridLayoutDemo extends
Applet { static final int n = 4; public void init() { setLayout
(new GridLayout(n , n)); setFont (new Font(“SansSerif”, Font.BOLD,
24)); for(int i=0; i
-
Prelim Question Paper Solution
37
This type of software loading progress can be shown using the
Java component ProgressBar.
It is a simple component , just a rectangle that is partially
filled with color to indicate the progress of a software loading
operation.
By default, progress is indicated by a string “n%”. [2
Marks]
A ProgressBar Example [3 Marks] import java.awt.BorderLayout;
import java.awt.Container; import javax.swing.BorderFactory; import
javax.swing.JFrame; import javax.swing.JProgressBar; import
javax.swing.border.Border; public class ProgressSample { public
static void main(String args[]) { JFrame f = new
JFrame("JProgressBar Sample");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container content
= f.getContentPane(); JProgressBar progressBar = new
JProgressBar(); progressBar.setValue(25);
progressBar.setStringPainted(true); Border border =
BorderFactory.createTitledBorder("Reading...");
progressBar.setBorder(border); content.add(progressBar,
BorderLayout.NORTH); f.setSize(300, 100); f.setVisible(true); }
}
Q.7(c) Write a servlet application to find the sum of digits of
the number
entered by the user through the HTML form. [5]
(A) add.html
Vidy
alank
ar
-
Vidyalankar : T.Y. B.Sc. (IT) – Adv. Java
38
Number - Addition.java import java.io.*; import java.net.*;
import javax.servlet.*; import javax.servlet.http.*; public class
Addition extends HttpServlet {
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8"); PrintWriter
out = response.getWriter(); String n1=request.getParameter("t1");
//String n1="10"; int n2 = Integer.parseInt(n1);
try {
int i=0; int sum=0,tot, rem; int no=1; while (n2>0) { rem =
n2 % 10; tot = tot+ rem n2=n2/10; } out.println(tot);
} finally {
out.close(); }
}
Vidy
alank
ar
-
Prelim Question Paper Solution
39
Q.7(d) Explain the 2-tier and 3 t-tier models of JDBC. [5](A)
[Explanation of 2-tier 2 marks, Explanation of 3-tier 2 marks,
Diagrams 1 mark] Two-tier and Three-tier Processing Models The
JDBC API supports both two-tier and three-tier processing
models
for database access. Two –tier Model
Fig. 1: Two-tier Architecture for Data Access.
In the two-tier model, a Java applet or application talks
directly to the data source.
This requires a JDBC driver that can communicate with the
particular data source being accessed.
A user's commands are delivered to the database or other data
source, and the results of those statements are sent back to the
user.
The data source may be located on another machine to which the
user is connected via a network. This is referred to as a
client/server configuration, with the user's machine as the client,
and the machine housing the data source as the server.
The network can be an intranet, which, for example, connects
employees within a corporation, or it can be the Internet.
Three –Tier Model In the three-tier model, commands are sent to
a "middle tier" of
services, which then sends the commands to the data source. The
data source processes the commands and sends the results back
to
the middle tier, which then sends them to the user. MIS
directors find the three-tier model very attractive because the
middle tier makes it possible to maintain control over access
and the kinds of updates that can be made to corporate data.
Vidy
alank
ar
-
Vidyalankar : T.Y. B.Sc. (IT) – Adv. Java
40
Another advantage is that it simplifies the deployment of
applications. Finally, in many cases, the three-tier architecture
can provide performance advantages.
Fig. 2: Three-tier Architecture for Data Access. Q.7(e) Explain
with suitable example element of faces-
config.xml file JSF. [5]
(A) [Explanation of all elements 4 marks, Program 1 marks]
The 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 Element /index.xhtml The element contains the view
identifier bound to the view for which the containing navigation
rule is relevant. If no 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.
The Element
Vidy
alank
ar
-
Prelim Question Paper Solution
41
- - - - - -
The 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 that should be selected next.
The Element login The 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 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 was. The Element / Welcome.xhtml The element contains the
view identifier of the next view that must be displayed when this
navigation rule is matched. Example /pages/inputname.jsp sayHello
/pages/greeting.jsp sayGoodbye /pages/goodbye.jsp This code
specifies that view /pages/inputname.jsp has two outputs,
sayHello and sayGoodbye, associated with particular
pages.
Vidy
alank
ar
-
Vidyalankar : T.Y. B.Sc. (IT) – Adv. Java
42
Q.7(f) Explain the importance of mapping and show the creation
of mappingfile in hibernate framework.
[5]
(A) [Importance – 2marks, Creation - 3 marks] Mapping Mapping is
used to provide Hibernate with information to persist objects
to a relational database. Mapping files also provide support
features such as creating the
database schema from a collection of mapping files. Creation of
mapping file
In Hibernate, mapping a bean to a relational database is done by
creating a mapping file in XML.
Hibernate mapping files are used to specify how your objects
relate to database tables. To create basic mappings for properties
and associations, i. e. generate .hbm.xml files, Hibernate Tools
provide a basic wizard which you can display by selecting File →
New → Hibernate XML mapping file. At first you will be asked to
select a package or multiple individual classes to map. It is also
possible to create an empty file: do not select any packages or
classes and an empty .hbm file will be created in the specified
location. Using the depth control option you can define the
ependency depth used when choosing classes.
Hibernate XML Mapping File Wizard The next wizard page lists the
mappings to be generated. You can see the Customers, Orders,
Productlines and Products classes added under depth control
driving.
Vidy
alank
ar
-
Prelim Question Paper Solution
43
Mappings to be generated This wizard page display a preview of
the generated .hbm files.
Preview Generated Mapping Files Clicking the Finish button
creates the files.
Vidy
alank
ar