Advance Java Question Paper and Solution Semester 5 November 2017
Advance Java Question Paper and Solution Semester 5 November 2017
Total Marks: 75
Java provides a special feature, called an adapter class that can simplify the creation of event
handlers in certain situations. An adapter class provides an empty implementation of all
methods in an event listener interface. Adapter classes are useful when you want to receive and
process only some of the events that are handled by a particular event listener interface.
You can define a new class to act as an event listener by extending one of the adapter classes
and implementing only those events in which you are interested.
Note that both of the event listener classes save a reference to the applet. This information is
provided as an argument to their constructors and is used later to invoke the showStatus( )
method.
// Demonstrate an adapter.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="AdapterDemo" width=300 height=100>
</applet>
*/
public class AdapterDemo extends Applet {
public void init() {
addMouseListener(new MyMouseAdapter(this));
addMouseMotionListener(new MyMouseMotionAdapter(this));
}
}
class MyMouseAdapter extends MouseAdapter {
AdapterDemo adapterDemo;
public MyMouseAdapter(AdapterDemo adapterDemo) {
this.adapterDemo = adapterDemo;
}
// Handle mouse clicked.
public void mouseClicked(MouseEvent me) {
adapterDemo.showStatus("Mouse clicked");
}
}
class MyMouseMotionAdapter extends MouseMotionAdapter {
AdapterDemo adapterDemo;
public MyMouseMotionAdapter(AdapterDemo adapterDemo) {
this.adapterDemo = adapterDemo;
}
// Handle mouse dragged.
public void mouseDragged(MouseEvent me) {
adapterDemo.showStatus("Mouse dragged");
}
}
As you can see by looking at the program, not having to implement all of the methods defined
by the MouseMotionListener and MouseListener interfaces saves you a considerable amount
of effort and prevents your code from becoming cluttered with empty methods. As an exercise,
you might want to try rewriting one of the keyboard input examples shown earlier so that it
uses a KeyAdapter.
b. Explain Delegation Event model. What are two steps in using the java delegation
event model?
The modern approach to handling events is based on the delegation event model, which
defines standard and consistent mechanisms to generate and process events. Its concept is
quite simple: a source generates an event and sends it to one or more listeners. In this scheme,
the listener simply waits until it receives an event. Once received, the listener processes the
event and then 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.
A user interface element is able to “delegate” the processing of an event to a separate piece of
code.
In the delegation event model, listeners must register with a source in order to receive an
event notification. This provides an important benefit: notifications are sent only to listeners
that want to receive them .Previously, an event was propagated up the
containment hierarchy until it was handled by a component. This required components to
receive events that they did not process, and it wasted valuable time.
3) Event Listeners
A listener is an object that is notified when an event occurs. It has two major
2 requirements.
First, 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.
Just follow these two steps:
Implement the appropriate interface in the listener so that it can receive the type of event
desired.
Implement code to register and unregister (if necessary) the listener as a recipient for the
event notifications.
A source may generate several types of events. Each event must be registered separately.
Also, an object may register to receive several types of events, but it must implement all of
the interfaces that are required to receive these events.
c. Explain the various Layout Managers available in AWT
BorderLayout
BoxLayout
The BoxLayout class puts components in a single row or column. It respects the
components' requested maximum sizes and also lets you align components
CardLayout
The CardLayout class lets you implement an area that contains different components at
different times. A CardLayout is often controlled by a combo box, with the state of the
combo box determining which panel (group of components) the CardLayout displays. An 6
alternative to using CardLayout is using a tabbed pane, which provides similar functionality
but with a pre-defined GUI.
FlowLayout
FlowLayout is the default layout manager for every JPanel. It simply lays out components in
a single row, starting a new row if its container is not sufficiently wide. Both panels in
CardLayoutDemo, shown previously, use FlowLayout.
GridBagLayout
GridLayout
GridLayout simply makes a bunch of components equal in size and displays them in the
requested number of rows and columns.
d. Write AWT based Java program that will read a string from user and display the length
of the string.
JColorChooser provides a pane of controls designed to allow a user to manipulate and select
a color.
Constructors
JColorChooser(): Creates a color chooser pane with an initial color of white.
JColorChooser(Color initialColor): Creates a color chooser pane with the specified initial
color.
Methods
Color getColor(): Gets the current color value from the color chooser.
void setColor(Color color): Sets the current color of the color chooser to the specified color.
void setColor(int c): Sets the current color of the color chooser to the specified color.
void setColor(int r, int g, int b): Sets the current color of the color chooser to the specified
RGB color.
JFC (Swing) is a huge set of components which includes labels, frames, tables, trees,
andstyled text documents. Almost all Swing components are derived from a single parent
called JComponent which extends the AWT Container class. Swing is a layer on top of
AWT rather than a substitution for it.
AWT Swing
AWT stands for Abstract windows Swing is also called as JFC’s (Java
toolkit. Foundation
classes).
AWT components are called Swings are called light weight
Heavyweight component. component because
swing components sits on the top of
AWT
components and do the work.
AWT components require java.awt Swing components require javax.swing
package. package.
AWT components are platform Swing components are made in purely
dependent. java and
they are platform independent.
This feature is not supported in AWT. We can have different look and feel in
Swing. Swing has many advanced
features like JTabel, Jtabbed pane which
is not available in AWT. Also. Swing
components are called "lightweight"
because they do not require a native OS
object to implement their functionality.
JDialog and JFrame are heavyweight,
because they do have a peer. So
components like JButton, JTextArea,
etc., are lightweight because they do not
have an OS peer.
With AWT, you have 21 "peers" (one With Swing, you would have only one
for each control and one for the peer, the operating system's window
dialog itself). A "peer" is a widget object. All of the buttons, entry fields,
provided by the operating system, etc. are drawn by the Swing package on
such as a button object or an entry the drawing surface provided by the
field object. window object. This is the reason that
Swing has more code. It has to draw the
button or other control and implement
its behavior instead of relying on the
host operating system to perform those
functions.
AWT is a thin layer of code on top of Swing is much larger. Swing also has
the OS. very much
richer functionality.
Using AWT, you have to implement a Swing has them built in.
lot of things yourself.
d. Explain Root Pane, Glass Pane, Layered Pane, Content Pane and Desktop Pane.
Swing offers some top-level containers such as - JApplet, JDialog, and JFrame. There are some
problems for mixing lightweight and heavyweight components together in Swing, we can't just
add anything but first, we must get something called a "content pane," and then we can add
Swing components to that.
JdesktopPane:
The concept of showing multiple windows inside a large frame is implemented using
Desktop pane. If we minimize the application frame, all of its windows are hidden at the same
time. In Windows environment, this is called as the multiple document interfaceor MDI. Using
it we can resize the internal frames inDesktop pane by dragging the resize corners.To achieve
this we have follow these steps:
1. We can use a regular JFrame window for the program.
2. Set the content pane of the JFrame to a JDesktopPane.
RequestDispatcher in Servlet
The RequestDispacher interface provides the facility of dispatching the request to another
resource it may be html, servlet or jsp.This interface can also be used to include the content
of antoher resource also. It is one of the way of servlet collaboration.
Subclass os ServletRequest allow the servlet to retrieve more protocol specific data.
Eg. HttpServletRequest :Defines an object to provide client request information to a servlet.
The servlet container creates a ServletRequest object and passes it as an argument to the
servlet's service method. A ServletRequest object provides data including parameter name and
values, attributes, and an input stream.
Methods
java.lang.Object getAttribute(java.lang.String name) Returns the value of the named attribute
as an Object, or null if no attribute of the given name exists.
java.util.Enumeration getAttributeNames() Returns an Enumeration containing the names of
the attributes available to this request.
java.lang.String getParameter(java.lang.String name) Returns the value of a request parameter
as a String, or null if the parameter does not exist.
java.util.Enumeration getParameterNames() Returns an Enumeration of String objects
containing the names of the parameters contained in this request.
java.lang.String[] getParameterValues(java.lang.String name) Returns an array of String
objects containing all of the values the given request parameter has, or null if the parameter
does not exist.
RequestDispatcher getRequestDispatcher(java.lang.String path) Returns a RequestDispatcher
object that acts as a wrapper for the resource located at the given path.
java.lang.String getServerName() Returns the host name of the server that received the request.
void removeAttribute(java.lang.String name) Removes an attribute from this request.
void setAttribute(java.lang.String name, java.lang.Object o) Stores an attribute in this request.
d. Write a servlet program to display the factorial of a given number.
4. Attempt any two of the following: 10
a. List and explain the Directive tags of JSP.
Directive Tag gives special instruction to Web Container at the time of page translation.
Directive tags are of three types: page, include and taglib.
Directive Description
<%@ page ... %> defines page dependent properties such as language, session,
errorPage etc.
The Page directive defines a number of page dependent properties which communicates with
the Web Container at the time of translation. Basic syntax of using the page directive is <%@
page attribute="value" %> where attributes can be one of the following :
• import attribute
• language attribute
• extends attribute
• session attribute
• isThreadSafe attribute
• isErrorPage attribute
• errorPage attribute
• contentType attribute
• autoFlush attribute
• buffer attribute
The include directive tells the Web Container to copy everything in the included file and
paste it into current JSP file. Syntax of include directive is:
The taglib directive is used to define tag library that the current JSP page uses. A JSP page
might include several tag library. JavaServer Pages Standard Tag Library (JSTL), is a
collection of useful JSP tags, which provides mahy commonly used core functionalities. It
has support for many general, structural tasks such as iteration and conditionals, readymade
tags for manipulating XML documents, internationalization tags, and for performing SQL
operations. Syntax of taglib directive is:
<%@ taglib prefix="prefixOfTag" uri="uriOfTagLibrary" %>
The prefix is used to distinguish the custom tag from other libary custom tag. Prefix is
prepended to the custom tag name. Every custom tag must have a prefix.
b. Explain JDBC architecture.
JDBC is a Java API for executing SQL statements and supports basic SQL functionality. The
JDBC (Java Database Connectivity) is an API that defines interfaces and classes for writing
database applications in Java by making database connections. It is a program designed to
access many popular database products on a number of operating system platforms.Using
JDBC we can send SQL, PL/SQL statements to almost any relational database. It provides
RDBMS access by allowing us to embed SQL inside Java code.
JDBC Architecture
The main function of the JDBC API is to provide a means for the developer to issue SQL
statements and process the results in a consistent, databaseindependently. JDBC provides
wealthy object-oriented access to databases by defining classes and interfaces that represent
objects such as:
•Database connections : (Short explanation Expected)
•SQL statements : (Short explanation Expected)
•Result Set: (Short explanation Expected)
•Database metadata: (Short explanation Expected)
•Prepared statements: (Short explanation Expected)
•Binary Large Objects (BLOBs): (Short explanation Expected)
•Character Large Objects (CLOBs): (Short explanation Expected)
•Callable statements : (Short explanation Expected)
•Database drivers: (Short explanation Expected)
•Driver manager: (Short explanation Expected)
The JDBC API uses a Driver Manager and databaseprecise drivers to provide clear
connectivity to heterogeneous databases. The JDBC driver manager ensures that the correct
driver is used to access each data source. The Driver Manager is capable of supporting
multiple concurrent drivers connected to multiple heterogeneous databases.
Layers of the JDBC Architecture
JavaServer Pages (JSP) is a serverside development technology that is used to create dynamic
web pages and applications. It is introduced after Java Servlets. With Servlets Java became a
full-fledged application server programming language. This is achieved by embedding Java
code into HTML, XML, DHTML, or other document types. When a client such as a web
browser makes a request to the Java application container, which is typically a web server,
the static page is converted behind the scenes, and displayed as dynamic content to the
viewer.
1 Advantage of JSP:
• The JSP serves all facilities of Java i.e. write once run anywhere.
• JSP is ideal for Web based Technology.
• The JSP pages are translated and compiled into JAVA Servlet but are easier to
develop than JAVA Servlet.
• The JSP uses simplified scripting language based syntax for embedding HTML
into JSP.
• JSP containers provide easy coding for accessing standard objects and actions.
• JSP acquire all the benefits provided by JAVA Servlets and web container
environment.
• The JSP use HTTP as default request /response communication model.
2: Disadvantage:
• The JSP implementation is normally causes for poor diagnostics.
• Difficult looping in jsp.
• The space used to store JSP page is comparatively more.
• The first time loading of JSP is little bit time consuming because JSP pages must
be compiled on the server when first accessed.
MVC Architecture
The MVC stands for Model, View, and Controller architecture. The MVC architecture
separates the business logic and application data from the presentation data to the user.MVC
is design pattern which allows a developer to write their applications in a specific format,
following the same directory structure, using the same configuration, allowing making unique
chain between the components & documents of the application.
Core parts of MVC architecture.
1) Model: The model object only represents the data of an application. The model object
knows about all the data that need to be displayed. The model is aware about all the
operations that can be applied to transform that object. The model represents enterprise data
and the business rules that govern access to and updates of this data. Model is not concern
about the presentation data and how that data will be displayed to the browser.
2) View: The view represents the presentation of the application. The view object refers to
the model. It uses the query methods of the model to obtain the contents and renders it. The
view is not dependent on the application logic. It remains same if there is any modification in
the business logic. It is the responsibility of the view's to maintain the consistency in its
presentation when the model (data or logic) changes.
3) Controller: Whenever the user sends a request for something then it always go through
the controller. The controller is responsible for intercepting the requests from view and passes
it to the model for the appropriate action. After the action has been taken on the data, the
controller is responsible for directing the appropriate view to the user. In GUI applications
the views and the controllers often work very closely together.
b. List various phases of JSF lifecycle. Explain in short.
JSF lifecycle
To understand how the framework treats the underlying request & Servlet API also how
Faces processes each request, we’ll go through the JSF request processing lifecycle. A Java
Server Faces page is represented by a tree of UI components, called a view. During the
lifecycle, the Java Server Faces implementation must build the view while considering state
saved from a previous submission of the page. When the client submits a page, the Java
Server Faces implementation performs several tasks, such as validating the data input of
components in the view and converting input data to types specified on the server side. The
Java Server Faces implementation performs all these tasks as a series of steps in the Java
Server Faces request response life cycle.
Facelets is commonly used term to refer to JavaServer Faces View Defination Framework
which is page declaration language developed for use with Java server Faces technology. The
concept of VDL introduced in JavaServer Faces 2.0 allows declaration of UI components in
different presentation technologies. Both JSP and facelets are considered different
inpmementation of VDL.
Facelet is built specifically for JavServer Faces. It is now theprefered technology for building
JavaServer Faces based applications and offers several advantages over using JSP
technology.
Facelets is a powerful but lightweight page declaration language that is used to build
JavaServer Faces views using HTML style templates and to build component trees. Facelets
features include the following:
• Facelets as presentation technology.
• Templatting and Composite Components through Faceltes.
• New HTML tags for easier page creation.
• Bookmarkability to generate hyperlinks based on component properties at render time .
• New components and event types for additional functionality.
• Resource registration and relocation using annotations.
• Implicit Navigation Rules if none are present in the application configuration resource files.
• Support for Bean Validation.
• Project Stage to describe the status of the application in the project lifecycle.
• Support for Ajax Integration.
Value Stack:Value Stack is nothing but stack of objects. The Value Stack is a storage
area that holds all of the data associated with the processing of a Request.
Accessing Value Stack :The Value Stack can be accessed by simply using the tags
provided for JSP.
•When the Value Stack Is queried for an attribute value, each stack element, in the
provided order, is asked whether it holds the queried property.
•If it holds the queried property, then the value is returned.
•If it does not hold the queried property, then the next element down is queried.
This continues until the last element in the stack is scanned.
c. Write a short on Interceptors in struts.
Interceptors
Interceptors allow developing code that can be run before and/or after the execution of an
action. A request is usually processed as follows:
•A user requests a resource that maps to an action
•The Struts 2 framework invokes the appropriate action to serve the request
If interceptors are written, available and configured, then:
•Before the action is executed the invocation could be intercepted by another
object
•After the action executes, the invocation could be intercepted again by another
object
Such objects who intercept the invocation are called Interceptors. Conceptually, interceptors
are very similar to Servlet Filters or the JDKs Proxy class. Interceptor Configuration:
Interceptors configured in the struts.xml file appear as:
<interceptors>
<interceptor name="test1" class="..."/>
<interceptor name=”test2" class="..."/>
</interceptors>
<action name="WelcomeSturts">
<interceptor-ref name=" test 1"/>
<interceptor-ref name=" test 2"/>
<result name="SUCCESS">/ Welcome.jsp</result>
<result name="ERROR">/ Error.jsp</result>
</action>
In above code two interceptors named test1 and test2 are defined. Both of these are them
mapped to the action named WelcomeSturts.
Interceptor Stack: We can bind Interceptor together using an Interceptor Stack which
can be referenced together. We can use the same set of interceptors multiple times. So,
instead of configuring a number of interceptors every time, an interceptor stack can be
configured with all the required interceptors held within. To use Intercept Stack we need
to modify the struts.xml file as follows:
<interceptors>
<interceptor name="test1" class="..."/>
<interceptor name= test2" class="..."/>
<interceptor-stack name="MyStack">
<interceptor-ref name=" test1"/>
<interceptor-ref name=" test2"/>
</interceptor-stack>
</interceptors>
<action name="WelcomeSturts " class="test.WelcomeSturts ">
<result name="SUCCESS">/ Welcome.jsp</result>
<result name="ERROR">/ Error.jsp</result>
</action>
In above code two interceptors named test1and test2 are defined and a stack
named MyStackgroup them both.The stack holding both these interceptors is then
mapped to the Action named WelcomeStruts.
Execution Flow of Interceptors: Interceptors are executed as follows:
1. The framework receives a request and decides on the action the URL maps to
2. The framework consults the application's configuration file, to discover which
interceptors should fire and in what sequence
3. The framework starts the invocation process by executing the first Interceptor in
the Stack
4. After all the interceptors are invoked, the framework causes the action itself to be
executed.
Hibernate uses the “hibernate.cfg.xml” file to create the connection & setup the required
environment.
This file contains information such as…..
1) Database Connection 2) Resource mapping
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration
DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<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:3306/Feedback
</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
</session-factory>
</hibernate-configuration>
Explaination:
1. hibernate.connection.driver_class: It is the JDBC connection class for the specific
database.
2. hibernate.connection.url: It is the full JDBC URL to the database.
3. hibernate.connection.username: It is the username used to connection the database.
4. hibernate.connection.password: It is the password used to authenticate the username.
5. hibernate.dialect: It is the name of SQL dialect for the database.
A check box is a control that is used when there are multiple options and multiple
selections to turn an option on or off. It consists of a small box that can either contain a
check mark or not.
CheckboxGroup
It is possible to create a set of mutually exclusive check boxes in which one and only one
check box in the group can be checked at any one time. These check boxes are often
called radio buttons. Check box groups are objects of type CheckboxGroup. Only the
default constructor is defined, which creates an empty group.
Methods:
Checkbox getSelectedCheckbox( ) : Reads the selected radio button option from group
void setSelectedCheckbox(Checkbox which): Selects radio button option of a group.
Example:
import java.applet.*;
import java.awt.*;
/*
<applet code="TCBCBG" width=200 height=150>
</applet>
*/
public class TCBCBG extends Applet {
Checkbox morning,noon,evening;
public void init() {
this.add(new Label("How will you pay for your pizza?"));
CheckboxGroup cbg = new CheckboxGroup();
this.add(new Checkbox("Visa", cbg, false));
this.add(new Checkbox("Cash", cbg, true)); // the default
this.add(new Label("Select Time Slots for Delivery"));
morning = new Checkbox("Morning", null, true);
noon = new Checkbox("Afternoon");
evening = new Checkbox("Evening");
this.add(morning);
this.add(noon);
this.add(evening);
}
}
A Web application exists as a structured hierarchy of directories. The root of this hierarchy
serves as the document root for files that are part of the application.
A special directory exists within the application hierarchy named “WEB-INF”. This directory
contains all things related to the application that aren’t in the document root of the application.
The WEB-INF node is not part of the public document tree of the application. No file contained
in the WEB-INF directory may be served directly to a client by the container. However, the
contents of the WEBINF directory are visible to servlet code using the getResource and
getResourceAsStream method calls on the ServletContext, and may be exposed using the
RequestDispatcher calls. Hence, if the Application Developer needs access, from servlet code,
to application specific configuration information that he does not wish to be exposed directly
to the Web client, he may place it under this directory. Since requests are matched to resource
mappings in a case-sensitive manner, client requests for ‘/WEB-INF/foo’, ‘/WEb-iNf/foo’, for
example, should not result in contents of the Web application located under /WEB-INF being
returned, nor any form of directory listing thereof.
Enterprise java beans are reusable modules of code that combine related tasks into well-
defined interface. These enterprise beans EJB components contain the method that executes
business logic and access data sources.
1: Session beans:
A) Stateful Session Beans: Stateful Session Beans are business objects having state, means
they can keep track of which calling client they are dealing with throughout a session and
thus access to the bean instance is strictly limited to “only one client at a time”. In the case of
concurrent access to a single bean is attempted anyway the container serializes those requests,
but via the @AccessTimeout annotation the container can throw an exception instead.
Stateful session beans' state may be persisted automatically by the container to free up
memory after the client hasn't accessed the bean for some time.
Example:
The hotel check out may be handled by a stateful session bean that would use its state to keep
track of where the customer is in the checkout process, possibly holding locks on the items
the customer is charged for services.
B) Stateless Session Beans: Stateless Session Beans are business objects that do not have
state associated with them. Access to a single bean instance is limited to only one client at a
time and thus concurrent access to the bean is banned. In case concurrent access to a single
bean is attempted anyway the container simply routes each request to a different instance.
Instances of Stateless Session beans are typically pooled. If a second client accesses a
specific bean right after a method call on it made by a first client has finished, it might get the
same instance. Example: Sending an Email to customer support may be handled by a
stateless bean since this is a oneoff operation and not part of a multistep process.
C) Singleton Session Beans: Singleton Session Beans are business objects having a global
shared state in a JVM. Concurrent access to the one and only bean instance can be controlled
by the container or by the bean itself. Container Managed concurrency can be tuned using the
@Lock annotation, that designates whether a read lock or a write lock will be used for a
method call. Also the Singleton Session Beans can explicitly request to be instantiated when
the EJB container starts up, using the @Startup annotation.
Examples: Loading a daily price list that will be the same for every user might be done with
a singleton session bean, since this will prevent the application having to do the same query
to a database over and over again.