Sie sind auf Seite 1von 65

Q:1.Answer the following questions:1.Write a short note on Event Listener?

Explain the Working with


code specifications?(13-14)
These are objects that define methods to handle certain type of
events. An event source (for example a PushButton) can generate one
or more type of events, and maintain a list of event listeners for each
type of event.
An event source can register listeners by calling addXListener type of
methods.
For example a Button may register an object for handling ActionEvent
by calling addActionListener.
This object would then need to implement the listener interface
corresponding to ActionEvent, which is ActionListener.
So to set up the processing of events the following Working must be
done.
I. For the GUI component (like pushbutton) associate a listener object class
with the component by calling a method of type addXListener .
II. Define this listener object. It must implement the corresponding interface.
The name of interface is of type EventListener.
III. The object must define all the methods defined in the interface it is
implementing.

Example:import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Demo {
public Demo(){
JLabel text = new JLabel();
text.setVisible(true);
text.setBounds(50, 100, 200, 20);
JButton btn = new JButton("Click me");
btn.setVisible(true);
btn.setBounds(20, 20, 120, 20);

btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
if(arg0.getSource().equals(btn)){
text.setText("ActionEvent Performed!!");
}
}
});
JFrame f = new JFrame();
f.setVisible(true);
f.setSize(400, 400);
f.setLayout(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(btn);
f.add(text);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Demo d = new Demo();}}
-----------------------------------------------------------------------------------------------------------2.How does AWT create radio button?Explain with syntax and code
specification?(13-14)
JRadioButtons: This is normally used as one of a group of radio
buttons of which only one may be selected at a time. These are
grouped using a ButtonGroup and are usually used to select from a set
of mutually exclusive options.
It consists of a background rectangle and text and/or an icon. If it
includes an icon, the icon is used to visually reflect the current state of
the radio button.
Using the constructors listed below , radio buttons can be
created:
JRadioButton() : Creates an initially unselected radio button with no
set text. JRadioButton(Icon icon) : Creates an initially unselected
radio button with the specified image but no text.
JRadioButton(Icon icon, Boolean selected) : Creates a radio button
with the specified image and selection state, but no text.
JRadioButton(String text) : Creates an initially unselected radio
button with the specified text.
JRadioButton(String text, boolean selected) : Creates a radio
button with specified text and selection state.
JRadioButton(String text, Icon icon) : Creates a radio button that
has the specified text and image, and that is initially unselected.

JRadioButton(String text, Icon icon, boolean selected) : Creates


a radio button that has the specified text, image, and selection state.

Example:
import javax.swing.*;
import java.awt.*;
public class StudentBioData02
extends JFrame {
JLabel lbllang, lblstream;
JCheckBox cbeng, cbhin, cbmar;
JRadioButton rbart, rbcomm, rbsci;
ButtonGroup bg;
public StudentBioData02() {
lbllang = new JLabel("Languages Known");
lblstream = new JLabel("Stream");
cbeng = new JCheckBox("English", true);
cbhin = new JCheckBox("Hindi");
cbmar = new JCheckBox("Marathi");
rbart = new JRadioButton("Arts");
rbcomm = new JRadioButton("Commerce");
rbsci = new JRadioButton("Science");
bg = new ButtonGroup();
bg.add(rbart);
bg.add(rbcomm);
bg.add(rbsci);
Container con = getContentPane();
con.setLayout(new FlowLayout());
con.add(lbllang);
con.add(cbeng);
con.add(cbhin);
con.add(cbmar);
con.add(lblstream);
con.add(rbart);
con.add(rbcomm);
con.add(rbsci);
}
public static void main(String args[]) {
StudentBioData02 sbd = new StudentBioData02();
sbd.setSize(150, 200);
sbd.setVisible(true);}}
------------------------------------------------------------------------------------------------------------

3.what is default layout of the JFrame?Exlain the same?(13-14)


BorderLayout is the default layout manager for the content pane
of a JFrame, JWindow, JDialog, JInternalFrame, and JApplet.
BorderLayout : It is the class that enables specification, i.e. where on
the border of container each component should be placed. All areas
need not be filled. The size of the areas will depend on the components
they contain. Border Layout can be created using following
constructors

a. BorderLayout() : It creates a new border layout with no gap


between the
components.
b. BorderLayout(int hgap, int vgap) : It creates a border layout
with the
specified horizontal and vertical gap between
components.

Place components against any of the four borders of the container and
in the center.
The component in the center fills the available space.
You do not need specify all five areas of the container.
The component in the north region takes up the entire width of the
container along its top.
South does the same along the bottom.
The heights of north and south will be the preferred heights of the
added component.
The east and west areas are given the widths of the component each
contains, where the height is whatever is left in the container after
satisfying north's and south's height requirements.
Any remaining space is given to the component in the center region.
Constants used to specify areas: CENTER, EAST, NORTH, SOUTH, WEST

Example for Border Layout


import java.awt.*; import java.applet.*;
import java.util.*; /*<applet code="BorderDemo" width=300
height=100> </applet> */ public class BorderDemo extends
Applet {
public void init() {
setLayout(new BorderLayout()); add(new Button("This across the
top"),BorderLayout.NORTH); add(new Button("The Footer message
might go here"),BorderLayout.SOUTH); add(new
Button("Right"),BorderLayout.EAST); add(new
Button("Left"),BorderLayout.WEST); String msg=" This is border
layout"; add(new TextArea(msg),BorderLayout.CENTER); add(new
Button("new"),BorderLayout.CENTER); } }

-----------------------------------------------------------------------------------------------------------4.write a java AWT program that creates the following GUI(LOGIN


FRAME)?(13-14)
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class Demo extends Frame{
public Demo(){
Label ulbl = new Label("Username");
ulbl.setVisible(true);
ulbl.setBounds(10, 100, 80, 25);
TextField tf = new TextField();
tf.setVisible(true);
tf.setBounds(120, 100, 150, 25);
Label plbl= new Label("Password");
plbl.setVisible(true);
plbl.setBounds(10, 140, 80, 20);
TextField pwd = new TextField();
pwd.setVisible(true);
pwd.setBounds(120, 140, 100, 25);
Button btn = new Button("Login");
btn.setVisible(true);
btn.setBounds(20, 200, 120, 20);
Button cbtn = new Button("Cancel");
cbtn.setVisible(true);
cbtn.setBounds(150, 200, 120, 20);
setVisible(true);
setSize(400, 400);
setLayout(null);add(ulbl);add(tf);add(plbl);add(pwd);add(btn);add(c
btn);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}});}

public static void main(String[] args) {


Demo d = new Demo(); }}
5.explain the java deligation event model?what are the two steps of
using in java deligation event model?(14-15)
The modern approach to handling events is based on the delegation
event model. In this model, an event is sent to component form which
it originated. The component registers a listener object with the
program. The listener processes the event and then returns.
For e.g.: When you click a button, the action to be performed is
handled by an object registered to handle the button click event. The
following diagram illustrates the delegation event model

Every event has a corresponding listener interface that specifies the


methods that are required to handle the event. Event object are sent to
registered listeners. To enable a component to handle events, you
must register an appropriate listener for it.
Example:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Demo {
public Demo(){
JLabel text = new JLabel();
text.setVisible(true);
text.setBounds(50, 100, 200, 20);
JButton btn = new JButton("Click me");
btn.setVisible(true);
btn.setBounds(20, 20, 120, 20);
btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if(arg0.getSource().equals(btn)){
text.setText("ActionEvent Performed!!");

}} });
JFrame f = new JFrame();
f.setVisible(true);
f.setSize(400, 400);
f.setLayout(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(btn);
f.add(text);}
public static void main(String[] args) {
Demo d = new Demo();}}
6.Explain adapter classes and inner classes?(14-15)
Java inner class or nested class is a class i.e. declared inside the
class or interface.
We use inner classes to logically group classes and interfaces in one
place so that it can be more readable and maintainable.
Additionally, it can access all the members of outer class including
private data members and methods.
Syntax of Inner class
class Java_Outer_class{ //code class Java_Inner_class{ //code
}}
Adapter Class is used to overcome the problem of writing diffrernt
method of empty immplementation.
Normally, if we use event Listener.then we need to override all its
methods.
If we want to override only certain specific method, then in that case
EventListener can be replaced with EventAdapater Class.
Example:
import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;
public class Demo extends JFrame{
public Demo(){
JLabel ulbl = new JLabel("Hello world!!");
ulbl.setVisible(true);
ulbl.setBounds(10, 10, 100, 25);
JButton btn = new JButton("Click me");
btn.setVisible(true);
btn.setBounds(10, 50, 120, 20);
btn.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent e){
if(e.getSource().equals(btn)){
ulbl.setForeground(Color.red);}}});
setVisible(true);

setSize(200, 200);
setLayout(null);
add(ulbl);
add(btn);}
public static void main(String[] args) {
Demo d = new Demo();}}

7.Explain the following methods when working with Frame windows:


setSize,getSize,setTitle,setVisible,windowClosing(14-15)
setSize(); getSize(); (same)

example
import javax.swing.JFrame;
public class Main extends JFrame {
public static void main(String[] args) {
new Main();}
public Main() {
this.setSize(200, 100);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Hello World!");
this.setVisible(true);}}

WindowListener, WindowFocusListener, and WindowStateListener. All


three listeners handle WindowEvent objects. The methods in all three
event handlers are implemented by the abstract WindowAdapter class.
The following window activities or states can precede a window event:
Opening a window Showing a window for the first time.
Closing a window Removing the window from the screen.
Iconifying a window Reducing the window to an icon on the
desktop.
Deiconifying a window Restoring the window to its original
size.
Focused window The window which contains the "focus
owner".
Activated window (frame or dialog) This window is either the
focused window, or owns the focused window.
Deactivated window This window has lost the focus. For
more information about focus, see the AWT Focus Subsystem
specification.
Maximizing the window Increasing a window's size to the
maximum allowable size, either in the vertical direction, the
horizontal direction, or both directions.

example
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);}});
8.what are different layoutManager classes in Java?Explain
CardLayout with example?(14-15)
The LayoutManagers are used to arrange components in a particular
manner. LayoutManager is an interface that is implemented by all the
classes of layout managers. There are following classes that represents
the layout managers:
java.awt.BorderLayout,java.awt.FlowLayout,java.awt.GridLayo
ut,java.awt.CardLayout,java.awt.GridBagLayout,javax.swing.Bo
xLayout,javax.swing.GroupLayout,javax.swing.ScrollPaneLayou
t,javax.swing.SpringLayout etc.
The BorderLayout is used to arrange the components in five regions:
north, south, east, west and center. Each region (area) may contain
one component only. It is the default layout of frame or window.
The FlowLayout is used to arrange the components in a line, one after
another. It is the default layout of applet or panel.
The BoxLayout is used to arrange the components either vertically or
horizontally. For this purpose, BoxLayout provides four constants.

public static final int X_AXIS,Y_AXIS,LINE_AXIS,PAGE_AXIS.


The CardLayout class manages the components in such a manner
that only one component is visible at a time. It treats each component
as a card that is why it is known as CardLayout.
Classes
CardLayout(): creates a card layout with zero horizontal and vertical gap.
CardLayout(int hgap, int vgap): creates a card layout with the given
horizontal and vertical gap.
methods
public void next(Container parent): is used to flip to the next card
of the given container.
public void previous(Container parent): is used to flip to the
previous card of the given container.
public void first(Container parent): is used to flip to the first card
of the given container.
public void last(Container parent): is used to flip to the last card of
the given container.
public void show(Container parent, String name): is used to flip
to the specified card with the given name.
exmaple(for O/P create a window & button under it & above button
write Apple)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CardLayoutExample extends JFrame implements
ActionListener{
CardLayout card;
JButton b1,b2;
Container c;
CardLayoutExample(){
c=getContentPane();
card=new CardLayout(40,30);
c.setLayout(card);
b1=new JButton("Apple");
b2=new JButton("Boy");
b1.addActionListener(this);
b2.addActionListener(this);
c.add("a",b1);c.add("b",b2); }
public void actionPerformed(ActionEvent e) {
card.next(c); }
public static void main(String[] args) {
CardLayoutExample cl=new CardLayoutExample();
cl.setSize(400,400);
cl.setVisible(true);

cl.setDefaultCloseOperation(EXIT_ON_CLOSE); }}
9.Explain use of adapter classes with suitable example?(15-16)
An adapter class provides the default implementation of all methods
in an event listener interface. Adapter classes are very useful when
you want to process only few of the events that are handled by a
particular event listener interface. You can define a new class by
extending one of the adapter classes and implement only those events
relevant to you.
Example:
import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;
public class Demo extends JFrame{
public Demo(){
JLabel ulbl = new JLabel("Hello world!!");
ulbl.setVisible(true);
ulbl.setBounds(10, 10, 100, 25);
JButton btn = new JButton("Click me");
btn.setVisible(true);
btn.setBounds(10, 50, 120, 20);
btn.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent e){
if(e.getSource().equals(btn)){
ulbl.setForeground(Color.red);}}});
setVisible(true);
setSize(200, 200);
setLayout(null);
add(ulbl);
add(btn);}
public static void main(String[] args) {
Demo d = new Demo();}}

Adapter Class uses


Time consuming to define all interface methods.
WindowListener has seven methods.
Required to define all methods in interface.
Adapter class implements an interface.
Default implementation ({ }, empty body) for all methods.

10.Explain event delegation model?(15-16)(repeated).


11.Write AWT based java program that will read a String from user
and display the number of character in string?(15-16)
import java.awt.Frame;
import java.util.Scanner;
class Demo {
public Demo() {
String name;
System.out.println("Enter Name to read Length of String");
Scanner sc = new Scanner(System.in);
name = sc.nextLine();
System.out.println("The Lenght of " + name + " is:
"+name.length());}
public static void main(String[] args) {
Demo d = new Demo();}}
13.List various Event listener interfaces.explain any two?(15-16)
Changing the state of an object is known as an event. For example,
click on button, dragging mouse etc. The java.awt.event package
provides many event classes and Listener interfaces for event
handling.

A semantic event which indicates that a component-defined action


occurred. This high-level event is generated by a component (such as a
Button) when the component-specific action occurs (such as being
pressed). The event is passed to every ActionListener object that
registered to receive such events using the component's
addActionListener method is aclled Action Event.
addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
}
});
This event indicates a mouse action occurred in a component.
This low-level event is generated by a component object for
Mouse Events and Mouse motion events.

a mouse button is pressed

a mouse button is released

a mouse button is clicked (pressed and released)

a mouse cursor enters the unobscured part of component's


geometry

a mouse cursor exits the unobscured part of component's


geometry

a mouse is moved

the mouse is dragged

(Write MouseEvent Example)


Q:2.Answer the following questions:1.Explain the new feature of JFC?
The earlier versions of java were released with some simple libraries.
JDK1.2 was introduced with a new set of packages the java
foundation classes, or JFC that includes an improved user interface
called the swing components.
The JFC were developed, to address the shortcomings of AWT(Abstract
Windowing Toolkit). The development of JFC was unique. JFC 1.2 is an
extension of the AWT, not a replacement for it.
The JFC visual components extend the AWT container class. The
methods contained in the component and container classes that AWT
programmers are familiar with are still valid for JFC visual classes.

A Major Part of JFC is a new set of user Interface components called


Swing.

So,The features of JFC are as Follows: JFC is short for Java Foundation Classes, which encompass a group of
features for building graphical user interfaces (GUIs) and adding rich
graphics functionality and interactivity to Java applications. It is defined
as containing the features shown in the table below.

2.How can the user be made aware about the software loading
process?Which component is facilitating the same?Explain with code
specifications?****
3.How to divide frame window in two parts?Explain with code
specifications?
Yes, the frame window in Java can be divided in to two parts by using
JSplitPane
A JSplitPane displays two components, either side by side or one on top
of the other.
By dragging the divider that appears between the components, the
user can specify how much of the split pane's total area goes to each
component. You can divide screen space among three or more
components by putting split panes inside of split panes, as described in
Nesting Split Panes.
f you want to create a split pane with an arbitrary number of
components, you should check out Hans Muller's article,
MultiSplitPane: Splitting Without Nesting.
The continuousLayout property setting determines how the
split pane reacts when the user drags the divider.
false (the default), only the divider is redrawn when dragged.
true, the JSplitPane resizes and redraws the components on each side
of the divider as the user drags the divider.
Example:
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JSplitPane;
public class SwingSplitSample {
public static void main(String args[]) {
JFrame frame = new JFrame("JSplitPane Sample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JSplitPane splitPane = new JSplitPane();


splitPane.setOrientation(JSplitPane.HORIZONTAL_SPLIT);
frame.getContentPane().add(splitPane, BorderLayout.CENTER);
frame.setSize(300, 200);
frame.setVisible(true);
}
}

4.write down java swing program that creates the below mentioned
hierarchical tree data Structure? Science>BSCIT>--NS>--ST>-ASP.NET>--Advance Java>--Linux
5.Explain Root pane, Glass pane, Layered pane, Content Pane and
Desktop pane.
RootPane
Each top-level container relies on a reclusive intermediate container
called the root pane. The root pane manages the content pane and the
menu bar, along with a couple of other containers.
If you need to intercept mouse clicks or paint over multiple
components, you should get acquainted with root panes.
We've already discussed about the content pane and the optional
menu bar. The two other components that a root pane adds are a
layered pane and a glass pane.
The layered pane directly contains the menu bar and content pane,
and enables Zordering of other components you might add. The glass
pane is often used to intercept input events occuring over the top-level
container, and can also be used to paint over multiple components.
Syntax:
javax.swing.JRootPane Panes = new
javax.swing.JRootPane();
glassPane
The glassPane sits on top of all other components in the JRootPane.
This positioning makes it possible to intercept mouse events, which is

useful for dragging one component across another. This positioning is


also useful for drawing.
paintComponent

LayeredPane:
The layeredPane is the parent of all children in the JRootPane. It is an
instance of JLayeredPane, which provides the ability to add
components at several layers.
This capability is very useful when working with popup menus, dialog
boxes, and dragging -- situations in which you need to place a
component on top of all other components in the pane.
Syntax:
javax.swing.JLayeredPane jlp = new
javax.swing.JLayeredPane();
ContentPane:
Here's the code that is used to get a frame's content pane and add the
yellow label to it: frame.getContentPane().add(yellowLabel,
BorderLayout.CENTER);
As the code shows, you find the content pane of a top-level container
by calling the getContentPane method. The default content pane is a
simple intermediate container that inherits from JComponent, and that
uses a BorderLayout as its layout manager.
It's easy to customize the content pane -- setting the layout manager
or adding a border, for example. The getContentPane method returns a
Container object, not a JComponent object.

DesktopPane:
A container used to create a multiple-document interface or a virtual
desktop. You create JInternalFrame objects and add them to
the JDesktopPane.
JDesktopPane extends JLayeredPane to manage the potentially
overlapping internal frames. It also maintains a reference to an
instance of DesktopManager that is set by the UI class for the current
look and feel (L&F). Note that JDesktopPane does not support borders.
This class is normally used as the parent of JInternalFrames to provide
a pluggable DesktopManager object to the JInternalFrames.
The installUI of the L&F specific implementation is responsible for
setting the desktopManager variable appropriately.
When the parent of a JInternalFrame is a JDesktopPane, it should
delegate most of its behavior to the desktopManager (closing, resizing,
etc).

public class JDesktopPane


extends JLayeredPane

implements Accessible
4.DIFFERENCE BETWEEN JAVABEANS AND ENTERPRISE JAVABEANS

Enterprise JavaBeans can be used while:


developing the reusable business logic component in enterprise
application developing a fast growing distributed application, which is
scalable application supports transaction management to ensure the
integrity of the database application deals with variety of clients and
session management for thousands of clients
7.Explain JPopupMenu class With example.
An implementation of an item in a menu. A menu item is essentially a
button sitting in a list. When the user selects the "button", the action
associated with the menu item is performed. A JPopupMenu contained
in a JMenuItem performs exactly that function.
a popup window containing JMenuItems that is displayed when the
user selects an item on the JMenuBar. In addition to JMenuItems, a
JMenu can also contain JSeparators.
Syntax:
javax.swing.JPopupMenu jp = new javax,swing.JPopupMenu();
Example:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class SwingSplitSample {


public static void main(String args[]) {
JPopupMenu pmenu = new JPopupMenu("Title");
pmenu.setVisible(true);
JMenuItem copy = new JMenuItem("Copy");
pmenu.add(copy);
JMenuItem cut = new JMenuItem("Cut");
pmenu.add(cut);
JMenuItem paste = new JMenuItem("Paste");
pmenu.add(paste);
JButton button = new JButton("Click me");
button.setVisible(true);
button.setBounds(0, 0, 200, 25);
button.setComponentPopupMenu(pmenu);
pmenu.addSeparator();
paste.setEnabled(false);
JFrame frame = new JFrame("JPopupMenu");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
frame.setSize(300, 200);
frame.setVisible(true);
frame.add(pmenu);
frame.add(button);
}
}
10.What is use of JColorChooser ? write down the constructors and
methods of the same?
JColorChooser is a swing component and is the part of JFC>Swing with have
many methods and and constructrs in it.IT is very useful to make a
PhotoEditing softwares live Photoshop,picassa and many more etc.
uses:
IT is use for coloring the components .
it is also use for Photo Editing Software Purpose.
12.Explain JTree With Example?
Example
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
public class JTreeDemo {
public JTreeDemo(){
DefaultMutableTreeNode A = new
DefaultMutableTreeNode("A");
DefaultMutableTreeNode A1 = new
DefaultMutableTreeNode("A1");
A.add(A1);

DefaultMutableTreeNode A11 = new


DefaultMutableTreeNode("A11");
A1.add(A11);
DefaultMutableTreeNode A22 = new
DefaultMutableTreeNode("A22");
A1.add(A22);
DefaultMutableTreeNode A33 = new
DefaultMutableTreeNode("A33");
A1.add(A33);
DefaultMutableTreeNode B1 = new
DefaultMutableTreeNode("B1");
A.add(B1);
DefaultMutableTreeNode B22 = new
DefaultMutableTreeNode("B22");
B1.add(B22);
JTree tree = new JTree(A);
JScrollPane jsp = new JScrollPane(tree);
JFrame f = new JFrame("JTree Demo");
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(600, 600);
f.add(jsp);}
public static void main(String[] args) {
JTreeDemo jt = new JTreeDemo();}}
Q:3.Answer the following
1.Explain the reason why servlet is preferred over CGI?
Servlets are server side components that provides a mechanism for
developing server web applications for server side.
Earlier CGI was developed to provide server side Capabilities to the
web applications, But due to its Performance, Scalability and
Reusability issues, Servlets are preferred.
Java Servlets overcome all the issues of CGI ( Common Gateway
Interface ).
Servlets are built from ground up using Sun's Write one run anywhere
technology, java servlets provide excellent framework for server side
processing.
Web Developers can create fast & efficient server side applications
using java servlets and can run it on any web server which is servlet
compatible.
servlets run entirely inside the java Virtual Machine.
since servlets runs on server side, it does not check for Browser
Compatibility.

Servlets mainly have 5 Advantages over CGI, they are


Platform Independence, plays a major in the field where there are
numerous number of web servers available to choose from.
Servlets are written entirely in java, due to which they are platform
independent.
Servlets can run on any servlet enabled web-server.
Performance, Due to interpreted nature of java, programs written in
java are slow. But java servlets run very fast. it is because the way
servlets run on web server.
For any program Initialization takes significant amount of time in its life
cycle. But in case of servlets initialization takes place only once when it
receives the first request & remains in memory till times out or server
shuts down's.
Once servlet is initialized & loaded, to handle a new request it simply
creates a new thread and runs service method of servlet.
In case of CGI scripts, always a new process should be created to serve
a request.
Extensibility, Servlets are developed in java which is robust, welldesigned & Object oriented language which can be extended or
polymorphed into a new object
java servlets take all java's advantages to provide the ideal solution.
Safety, Java provides very good safety feature's like Memory
management, Exception handling etc.
Servlets inherit all these features & had emerged as a very powerful
web server extension.
Security, Since servlets are server side Components, it inherits the
security of server.
Servlets are also benefited with java security manager, provided by
web server.

b.Difference Between JSP and JSF

c.Difference between AWT and SWING

1b.Different Between ServletConfig and ServletContext


ServletConfig
ServletConfig available in javax.servlet.*; package
ServletConfig object is one per servlet class
Object of ServletConfig will be created during initialization process of
the servlet
This Config object is public to a particular servlet only
Scope: As long as a servlet is executing, ServletConfig object will be
available, it will be destroyed once the servlet execution is completed.
We should give request explicitly, in order to create ServletConfig
object for the first time
In web.xml <init-param> tag will be appear under <servlet-class>
tag
ServletContext
ServletContext available in javax.servlet.*; package
ServletContext object is global to entire web application
Object of ServletContext will be created at the time of web application
deployment
Scope: As long as web application is executing, ServletContext object
will be available, and it will be destroyed once the application is
removed from the server.
ServletContext object will be available even before giving the first
request

In web.xml <context-param> tag will be appear under <web-app>


tag

2.Explain the methods that RequestDispatcher interface does


consist of with the relevant code specification?
The RequestDispatcher 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 another resource
also. It is one of the way of servlet collaboration.
There are two methods defined in the RequestDispatcher interface.
Methods of RequestDispatcher interface:The RequestDispatcher interface provides two methods. They are:
public void forward(ServletRequest request,ServletResponse
response)throws ServletException,java.io.IOException:Forwards a
request from a servlet to another resource (servlet, JSP file, or HTML
file) on the server.
public void include(ServletRequest request,ServletResponse
response)throws ServletException,java.io.IOException:Includes the
content of a resource (servlet, JSP page, or HTML file) in the response.

As you see in the above figure, response of second servlet is sent to the
client. Response of the first servlet is not displayed to the user.

As you can see in the above figure, response of second servlet is included in
the response of the first servlet that is being sent to the client.
Syntax:- public RequestDispatcher getRequestDispatcher(String
resource);
In this example, we are validating the password entered by the user. If
password is servlet, it will forward the request to the WelcomeServlet,
otherwise will show an error message: sorry username or password error!. In
this program, we are cheking for hardcoded information. But you can check it
to the database also that we will see in the development chapter. In this
example, we have created following files:

index.html file: for getting input from the user.


Login.java file: a servlet class for processing the response. If password
is servet, it will forward the request to the welcome servlet.
WelcomeServlet.java file: a servlet class for displaying the welcome
message.
web.xml file: a deployment descriptor file that contains the information
about the servlet.
index.html
<form action="servlet1" method="post">
Name:<input type="text" name="userName"/><br/>
Password:<input type="password" name="userPass"/><br/>
<input type="submit" value="login"/>
</form>
---------------------------------------------------Login.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Login extends HttpServlet { public void
doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {


response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
String p=request.getParameter("userPass");
if(p.equals("servlet"){
RequestDispatcher rd=request.getRequestDispatcher("servlet2");
rd.forward(request, response); }
else{
out.print("Sorry UserName or Password Error!");
RequestDispatcher rd=request.getRequestDispatcher("/index.html");
rd.include(request, response); }}}
--------------------------------------------------------WelcomeServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class WelcomeServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n); }}
------------------------------------------------Web.xml
<web-app>
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>Login</servlet-class>
</servlet>
<servlet>
<servlet-name>WelcomeServlet</servlet-name>
<servlet-class>WelcomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>WelcomeServlet</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>

</welcome-file-list>
</web-app>
4.Explain the lifecycle phases of servlet?
Java Servlets are server-side Java program modules that process and
answer client requests and implement the servlet interface. It helps in
enhancing Web server functionality with minimal overhead,
maintenance and support.
A servlet acts as an intermediary between the client and the server. As
servlet modules run on the server, they can receive and respond to
requests made by the client. Request and response objects of the
servlet offer a convenient way to handle HTTP requests and send text
data back to the client.
it also possesses all the Java features such as high portability, platform
independence, security and Java database connectivity.
The web container maintains the life cycle of a servlet instance.
Let's see the life cycle of the servlet:
Servlet class is loaded.
Servlet instance is created.
init method is invoked.
service method is invoked.
destroy method is invoked.

there are three states of a servlet: new, ready and end. The servlet is
in new state if servlet instance is created. After invoking the init()
method, Servlet comes in the ready state. In the ready state, servlet
performs all the tasks. When the web container invokes the destroy()
method, it shifts to the end state.
1) Servlet class is loaded
The classloader is responsible to load the servlet class. The servlet
class is loaded when the first request for the servlet is received by the
web container.
2) Servlet instance is created
The web container creates the instance of a servlet after loading the
servlet class. The servlet instance is created only once in the servlet
life cycle.
3) init method is invoked
The web container calls the init method only once after creating the
servlet instance. The init method is used to initialize the servlet. It is
the life cycle method of the javax.servlet.Servlet interface. Syntax of
the init method is given below:
public void init(ServletConfig config) throws ServletException

4) service method is invoked

The web container calls the service method each time when request
for the servlet is received. If servlet is not initialized, it follows the first
three steps as described above then calls the service method. If servlet
is initialized, it calls the service method. Notice that servlet is initialized
only once. The syntax of the service method of the Servlet interface is
given below:
public void service(ServletRequest request, ServletResponse
response)
throws ServletException, IOException
5) destroy method is invoked
The web container calls the destroy method before removing the
servlet instance from the service. It gives the servlet an opportunity to
clean up any resource for example memory, thread etc. The syntax of
the destroy method of the Servlet interface is given below:
public void destroy()
7.Explain GenericServlet with its constructors and methods.
GenericServlet class implements Servlet, ServletConfig and Serializable
interfaces. It provides the implementation of all the methods of these
interfaces except the service method.
GenericServlet class can handle any type of request so it is protocolindependent.
You may create a generic servlet by inheriting the GenericServlet class
and providing the implementation of the service method.
There are many methods in GenericServlet class. They are as follows:
public void init(ServletConfig config) is used to initialize the
servlet.
public abstract void service(ServletRequest request,
ServletResponse response) provides service for the incoming
request. It is invoked at each time when user requests for a servlet.
public void destroy() is invoked only once throughout the life cycle
and indicates that servlet is being destroyed.
public ServletConfig getServletConfig() returns the object of
ServletConfig.
public String getServletInfo() returns information about servlet
such as writer, copyright, version etc.
public void init() it is a convenient method for the servlet
programmers, now there is no need to call super.init(config)
public ServletContext getServletContext() returns the object of
ServletContext.

public String getInitParameter(String name) returns the


parameter value for the given parameter name.
public Enumeration getInitParameterNames() returns all the
parameters defined in the web.xml file.
public String getServletName() returns the name of the servlet
object.
public void log(String msg) writes the given message in the servlet
log file.
public void log(String msg,Throwable t) writes the explanatory
message in the servlet log file and a stack trace.
Constructor: GenericServlet() Does Nothing
import java.io.*; import javax.servlet.*;
public class First extends GenericServlet{ public void
service(ServletRequest req,ServletResponse res) throws
IOException,ServletException{ res.setContentType("text/html");
PrintWriter out=res.getWriter(); out.print("<html><body>");
out.print("<b>hello generic servlet</b>");
out.print("</body></html>"); }}
9.Explain the ServletRequest and ServletResponse interface of
Servlet?
ServletRequest Interfaces:An object of ServletRequest is used to provide the client request information
to a servlet such as content type, content length, parameter names and
values, header informations, attributes etc.

ServletResponse Interface:The ServletResponse interface contains various methods that enable a


servlet to respond to the client requests. A servlet can send the response
either as character or binary data. The PrintWriter stream can be used to
send character data as servlet response, and ServletOutputStream stream to
send binary data as servlet response. Here are the methods of
ServletResponse interface:

10. Explain session management with its techniques.

(A) Session management techniques


Session Management is used by Servlet to store information about a
particular client.
When a new client sends a request for a Servlet, Servlet will create a
session Memory to store a transaction information about a that
particular client.
Apart from that Servlet also generate a Session ID to keep a trap for
that session Memory.
Servlet Sends the SessionID to the client side. Application which will
get stored inside the client machine.
Next time if the Same client wants to do the transaction with the same
Servlet, then client will send request packet with session ID.
By retrieving the session ID, Servlet updates Session Memory for new
transaction generater new SessionID & send it to the client.
To perform this mechanism following three techniques can be used.
(a) Hidden formField : x It is used by the client to send a Session ID to
the Servlet. x It is in Hidden form & only Servlet can read it & Hence
called as Hidden form field.
(b) Url rewriting : x It is used to send SessionID to the client. x Servlet
can put the SessionID inside response packet or it will generate a
special token to send a SessionID
(c) Cookies : x By using cookie, a Servlet an send SessionID to the
client machine. x For that purpose Servlet will create a new cookie for
Session ID & sends it to the client, with the help of response packet
Header.
For example, Write a program to create a client side application which
is used to accept Roll No. and Name from user. It should also have a
button named "display" which when clicked should send those value to
the servlet. Servlet application should accept them display them on
web browser.
client side application <html> <head> <title> Servlet Application
</title> </head> <body> <form method = "get" action = "test">
<b> Roll No. </b> <input type = "number" name = "r" value = " " size
= "10"> <b> Name </b> <input type = "text" name = "n" value = " "
size = "10)> <input type = "submit" value = "Display"> </form>
</body> </html>
server side application import java.io.*; import javax.servlet.*;
import javax.servlet.http.*; public class test extends HttpServlet
{ public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException, Servlet Exception
{ res.setContentType("text/html"); PrintWriter pw = res.getWriter( );
int roll = Integer.parseInt(req.getParameter("r")); String name =
req.getParameter("n"); pw.println ("The roll no. =" + roll);
pw.println("<br>"); pw.println("The name =" + name); HttpSession

hs = req.getSession(true); if(hs.isNew( )) { pw.println("Session is


new"); } else { pw.println("session is old"); pw.println("session id
=" + hs.getId( )); pw.println("Creationtime =" + hs.getId( ));
pw.println("Lastaccessed time =" + hs.getLastAccessedTime"); }
pw.cloase( ); }}
11.What is Servlet? What are different tasks Caried out by servlets?
Servlet technology is used to create web application, it is robust and
scalable because of java language. Before Servlet, CGI (Common
Gateway Interface) scripting language was popular as a server-side
programming language.
There are many interfaces and classes in the servlet API such as
Servlet, GenericServlet, HttpServlet, ServletRequest, ServletResponse
etc.
Servlet can be described in many ways, depending on the context.
Servlet is a technology i.e. used to create web application.
Servlet is an API that provides many interfaces and classes including
documentations.
Servlet is an interface that must be implemented for creating any
servlet.
Servlet is a class that extend the capabilities of the servers and
respond to the incoming request. It can respond to any type of
requests.
Servlet is a web component that is deployed on the server to create
dynamic web page.
Servlet containers are also known as web container, for example
Tomcat. Some of the important tasks of servlet container are:
Communication Support: Servlet Container provides easy way of
communication between web client (Browsers) and the servlets and
JSPs. Because of container, we dont need to build a server socket to
listen for any request from web client, parse the request and generate
response. All these important and complex tasks are done by container
and all we need to focus is on business logic for the applications.
Lifecycle and Resource Management: Servlet Container takes care
of managing the life cycle of servlet. From the loading of servlets into
memory, initializing servlets, invoking servlet methods and to destroy
them. Container also provides utility like JNDI for resource pooling and
management.
Multithreading Support: Container creates new thread for every
request to the servlet and provide them request and response objects
to process. So servlets are not initialized for each request and saves
time and memory.

JSP Support: JSPs doesnt look like normal java classes but every JSP
in the application is compiled by container and converted to Servlet
and then container manages them like other servlets.
Miscellaneous Task: Servlet container manages the resource pool,
perform memory optimizations, execute garbage collector, provides
security configurations, support for multiple applications, hot
deployment and several other tasks behind the scene that makes a
developer life easier.

12.List various classes of servlet API. Write the purpose of each?


There are many classes in javax.servlet package. They are as follows:
GenericServlet Defines a generic, protocol-independent
servlet.
ServletContextAttributeEvent This is the event class for
notifications about changes to the attributes of the servlet
context of a web application.
ServletContextEvent This is the event class for notifications
about changes to the servlet context of a web application.
ServletInputStream Provides an input stream for reading
binary data from a client request, including an efficient readLine
method for reading data one line at a time.
ServletOutputStream
Provides an output stream for
sending binary data to the client.
ServletRequestAttributeEvent This is the event class for
notifications of changes to the attributes of the servlet request in
an application.
ServletRequestEvent Events of this kind indicate lifecycle
events for a ServletRequest.
ServletRequestWrapper Provides a convenient
implementation of the ServletRequest interface that can be
subclassed by developers wishing to adapt the request to a
Servlet.
ServletResponseWrapper Provides a convenient
implementation of the ServletResponse interface that can be
subclassed by developers wishing to adapt the response from a
Servlet.
13.List various Interfaces of servlet API. Write the purpose of each?
Filter
A filter is an object that performs filtering tasks on either the
request to a resource (a servlet or static content), or on the response from a
resource, or both.
FilterChain
A FilterChain is an object provided by the servlet container
to the developer giving a view into the invocation chain of a filtered request
for a resource.

FilterConfig
A filter configuration object used by a servlet container to
pass information to a filter during initialization.
RequestDispatcher Defines an object that receives requests from the
client and sends them to any resource (such as a servlet, HTML file, or JSP
file) on the server.
Servlet
Defines methods that all servlets must implement.
ServletConfig A servlet configuration object used by a servlet container
to pass information to a servlet during initialization.
ServletContext Defines a set of methods that a servlet uses to
communicate with its servlet container, for example, to get the MIME type of
a file, dispatch requests, or write to a log file.
ServletContextAttributeListener
Implementations of this interface
receive notifications of changes to the attribute list on the servlet context of
a web application.
ServletContextListener
Implementations of this interface receive
notifications about changes to the servlet context of the web application they
are part of.
ServletRequest Defines an object to provide client request information to a
servlet.
ServletRequestAttributeListener
A ServletRequestAttributeListener
can be implemented by the developer interested in being notified of request
attribute changes.
ServletRequestListener
A ServletRequestListener can be implemented
by the developer interested in being notified of requests coming in and out of
scope in a web component.
ServletResponse
Defines an object to assist a servlet in sending a
response to the client.
SingleThreadModel Deprecated. As of Java Servlet API 2.4, with no direct
replacement.
Q:4.Answer the following questions
1.Explain the components of JDBC.
JDBC has following components :
1. JDBC API

Using JDBC API ,frontend java applications can execute query


and fetch data from connected database. JDBC API can also connect
with multiple application with same database or same application
with multiple Databases which can be reside in different
computers(distributed environment).

2. JDBC Driver Manager

' Driver Manager' of JDBC interface defines 'objects' which is


used to connect java application with 'JDBC Driver'.' Driver Manager'
manages the all the 'JDBC Driver' loaded in client's system.
'Driver Manager' load the most appropriate driver among all the
Drivers for creating a connection.
DriverManager.getConnection();
3. JDBC Test Suite

JDBC Test Suite is used to check compatibility of a JDBC driver


with J2EE platform. It also check whether a Driver follow all the
standard and requirements of J2EE Environment .
4.JDBC-ODBC BRIDGE

The ODBC bridge or drivers should be installed on work site for


proper working of this component .The JDBC Driver contact to the
ODBC Driver for connection to the database.
The ODBC Driver is already installed or come as default driver in
windows for pcs .In Windows 'Datasource' name can be create using
control panel >administrative tools>Data Sources (ODBC).AFTER
Creating 'datasource' ,connectivity of 'datasource' to the 'database'
can be check .
Using this "data source", you can connect JDBC to ODBC.

2.Write an exhaustive note on "PreparedStatement". Attach code


to support your answer?
The PreparedStatement interface extends the Statement interface,
which gives you added functionality with a couple of advantages
over a generic Statement object.
This statement gives you the flexibility of supplying arguments
dynamically.
Since JDBC PreparedStatement is pre-compiled, we cant use it with
IN clause. Rather than going back to Statement, there are some
alternative approaches that we can use to get over this
shortcomings of Prepared Statement.
Use the when you plan to use the SQL statements many times. The
PreparedStatement interface accepts input parameters at runtime.
Methods:public void setInt(int paramIndex, int value) sets the integer value
to the given parameter index.
public void setString(int paramIndex, String value)
sets the
String value to the given parameter index.
public void setFloat(int paramIndex, float value) sets the float
value to the given parameter index.

public void setDouble(int paramIndex, double value)


sets the
double value to the given parameter index.
public int executeUpdate() executes the query. It is used for create,
drop, insert, update, delete etc.
public ResultSet executeQuery() executes the select query. It
returns an instance of ResultSet.
Example:import java.sql.*;
class InsertPrepared{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1
521:xe","system","oracle");
PreparedStatement stmt=con.prepareStatement("insert into Emp
values(?,?)");
stmt.setInt(1,101);//1 specifies the first parameter in the query
stmt.setString(2,"Ratan");
int i=stmt.executeUpdate();
System.out.println(i+" records inserted");
con.close();
}catch(Exception e){ System.out.println(e);} }}
output:-SR
Name
101 Ratan
3.Enlist the implicit objects of JSP. Explain any 4 of them in detail.
JavaServer Pages (JSP) is a technology that helps software
developers create dynamically generated web pages based on
HTML, XML, or other document types. Released in 1999 by Sun
Microsystems, JSP is similar to PHP and ASP, but it uses the Java
programming language.
There are 9 jsp implicit objects. These objects are created by the
web container that are available to all the jsp pages.
The available implicit objects are out, request, config, session,
application etc.

Out: This is used for writing content to the client (browser). It has several
methods which can be used for properly formatting output message to the
browser and for dealing with the buffer.
Request: The main purpose of request implicit object is to get the data on a
JSP page which has been entered by user on the previous JSP page. While
dealing with login and signup forms in JSP we often prompts user to fill in
those details, this object is then used to get those entered details on an
another JSP page (action page) for validation and other purposes.
Response: It is basically used for modfying or delaing with the response
which is being sent to the client(browser) after processing the request.
Session: It is most frequently used implicit object, which is used for storing
the users data to make it available on other JSP pages till the user session is
active.
Application: This is used for getting application-wide initialization
parameters and to maintain useful data across whole JSP application.
Exception: Exception implicit object is used in exception handling for
displaying the error messages. This object is only available to the JSP pages,
which has isErrorPage set to true.
Page: Page implicit object is a reference to the current Servlet instance
(Converted Servlet, generated during translation phase from a JSP page). We
can simply use this in place of it. Im not covering it in detail as it is rarely
used and not a useful implicit object while building a JSP application.
pageContext: It is used for accessing page, request, application and
session attributes.
Config: This is a Servlet configuration object and mainly used for accessing
getting configuration information such as servlet context, servlet name,
configuration parameters etc.

5.What is JDBC driver Explain types of JDBC drivers.


JDBC Driver is a software component that enables java application
to interact with the database.There are 4 types of JDBC drivers:
JDBC-ODBC bridge driver
Native-API driver (partially java driver)
Network Protocol driver (fully java driver)
Thin driver (fully java driver)
JDBC-ODBC bridge driver
The JDBC-ODBC bridge driver uses ODBC driver to connect to the
database. The JDBC-ODBC bridge driver converts JDBC method calls
into the ODBC function calls. This is now discouraged because of thin
driver.
Advantage:-easy to use.can be easily connected to any database.
Disadvantages:
Performance degraded because JDBC method call is converted into the
ODBC function calls.
The ODBC driver needs to be installed on the client machine.
Native-API driver
The Native API driver uses the client-side libraries of the database. The
driver converts JDBC method calls into native calls of the database API.
It is not written entirely in java.
Advantage:-performance upgraded than JDBC-ODBC bridge driver.
Dis-Adv:-The Native driver needs to be installed on the each client
machine.
The Vendor client library needs to be installed on client machine.
Network Protocol driver
The Network Protocol driver uses middleware (application server)
that converts JDBC calls directly or indirectly into the vendor-specific
database protocol. It is fully written in java.
Advantages:-No client side library is required because of
application server that can perform many tasks like auditing, load
balancing, logging etc.
Dis-Adv:-Network support is required on client machine.
Requires database-specific coding to be done in the middle tier.
Thin Driver
The thin driver converts JDBC calls directly into the vendor-specific
database protocol. That is why it is known as thin driver. It is fully
written in Java language.
Adv-Better performance than all other drivers.
No software is required at client side or server side.
Dis-Adv-Drivers depends on the Database.

6.Explain the JDBC architecture.

JDBC is a core part of the Java platform and is an API specification


developed by Sun Microsystems. The JDBC architecture supports
two-tier and three-tier processing models for accessing a database.
In the two-tier model, a Java applet or application communicates
directly to the data source.
The JDBC driver enables communication between the application
and the data source. When a user sends a query to the data source,
the answers for those queries are sent back to the user in the form
of results.
The data source may not always be a single machine located at a
single place. It can be located on a different machine on a network
to which a user is connected.
This is known as a client/server configuration, where the users
machine acts as a client and the machine having the data source
running acts as the server. The network connection can be intranet
or Internet.
In the three-tier model, the users commands or queries are sent to
middle-tier services, from which the commands are again sent to
the data source.
The results are sent back to the middle tier, and from there to the
user. This type of model is found very useful by management
information system directors, as it makes it simple to maintain
access control and make updates to corporate data.
Application deployment also becomes easy and provides
performance benefits. The middle tier is usually written in C or C++.

The JDBC driver manager is a traditional backbone of the JDBC


architecture, which specifies objects for connecting Java
applications to a JDBC driver.
The JDBC Test Suite helps to ensure that the JDBC drivers will run
the program. The JDBC-ODBC Bridge software offers JDBC access via
the open database connectivity drivers.

7.What are the advantages and disadvantages of java server


pages?
Advantage of JSP:
JSP are translated and compiled into JAVA servlets but are easier to
develop than JAVA servlets.
JSP have all advatages of Java i.e write once run anywhere
JSP uses simplified scripting language based syntax for embedding
HTML into JSP.
JSP containers provide easy way for accessing standard objects and
actions.
JSP reaps all the benefits provided by JAVA servlets and web container
environment, but they have an added advantage of being simpler and
more natural program for web enabling enterprise developer
JSP use HTTP as default request /response communication paradigm and
thus make JSP ideal as Web Enabling Technology.
Disadvantages of JSP:
1. As JSP pages are translated to servlets and compiled, it is difficult
to trace errors occurred in JSP pages.
2. JSP pages require double the disk space to hold the JSP page.
3. JSP pages require more time when accessed for the first time as
they are to be compiled on the server.
8.List various directives of JSP. Explain any two
The jsp directives are messages that tells the web container how to
translate a JSP page into the corresponding servlet.
There are three types of directives:
page directive
include directive
taglib directive
Syntax:<%@ directive attribute="value" %>
JSP page directive:The page directive defines attributes that apply to an entire JSP page.
Syntax of JSP page directive:<%@ page attribute="value" %>
JSP include directive

The include directive is used to include the contents of any resource it


may be jsp file, html file or text file. The include directive includes the
original content of the included resource at page translation time (the jsp
page is translated only once so it will be better to include static resource).
Advantage of Include directive:Code Reusability
Syntax of include directive:<%@ include file="resourceName" %>
Example of include directive:In this example, we are including the content of the header.html file. To
run this example you must create an header.html file.
<html>
<body>
<%@ include file="header.html" %>
Today is: <%= java.util.Calendar.getInstance().getTime() %>
</body>
</html>
JSP Taglib directive
The JSP taglib directive is used to define a tag library that defines many
tags. We use the TLD (Tag Library Descriptor) file to define the tags. In the
custom tag section we will use this tag so it will be better to learn it in
custom tag.
Syntax JSP Taglib directive:<%@ taglib uri="uriofthetaglibrary" prefix="prefixoftaglibrary"
%>
Example of JSP Taglib directive:In this example, we are using our tag named currentDate. To use this tag
we must specify the taglib directive so the container may get information
about the tag.
<html>
<body>
<%@ taglib uri="http://www.javatpoint.com/tags" prefix="mytag"
%> <mytag:currentDate/> </body>
</html>
Write the purpose of the following JDBC classes
DriverManager
The DriverManager class acts as an interface between user and drivers. It
keeps track of the drivers that are available and handles establishing a
connection between a database and the appropriate driver. The
DriverManager class maintains a list of Driver classes that have registered
themselves by calling the method DriverManager.registerDriver().
ResultSet

The object of ResultSet maintains a cursor pointing to a row of a table.


Initially, cursor points to before the first row.But we can make this object
to move forward and backward direction by passing either
TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE in
createStatement(int,int) method as well as we can make this object as
updatable by:
Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
Statement
The Statement interface provides methods to execute queries with the
database. The statement interface is a factory of ResultSet i.e. it provides
factory method to get the object of ResultSet.
PreparedStatement
The PreparedStatement interface is a subinterface of Statement. It is used
to execute parameterized query.
Let's see the example of parameterized query:
String sql="insert into emp values(?,?,?)";
Connection
A Connection is the session between java application and database.
The Connection interface is a factory of Statement,
PreparedStatement, and DatabaseMetaData i.e. object of Connection
can be used to get the object of Statement and DatabaseMetaData.
The Connection interface provide many methods for transaction
management like commit(), rollback() etc.
Q:5.Answer the following questions
1.Enlist the lifecycle phases of JSF. Explain the following phases in
detail.
Restore View
Apply Request Values
Update Model Values
Render Response
JavaServer Faces (JSF) is a Java specification for building componentbased user interfaces for web applications. It was formalized as a standard
through the Java Community Process and is part of the Java Platform,
Enterprise Edition.
JSF application lifecycle consist of six phases which are as follows
Restore view phase
Apply request values phase; process events
Process validations phase; process events
Update model values phase; process events
Invoke application phase; process events
Render response phase

Phase 1: Restore view


JSF begins the restore view phase as soon as a link or a button is clicked and
JSF receives a request.
During this phase, the JSF builds the view, wires event handlers and
validators to UI components and saves the view in the FacesContext
instance. The FacesContext instance will now contains all the information
required to process a request.
Phase 2: Apply request values
After the component tree is created/restored, each component in component
tree uses decode method to extract its new value from the request
parameters. Component stores this value. If the conversion fails, an error
message is generated and queued on FacesContext. This message will be
displayed during the render response phase, along with any validation errors.
If any decode methods / event listeners called renderResponse on the
current FacesContext instance, the JSF moves to the render response phase.
Phase 4: Update model values
After the JSF checks that the data is valid, it walks over the component tree
and set the corresponding server-side object properties to the components'
local values. The JSF will update the bean properties corresponding to input
component's value attribute.
If any updateModels methods called renderResponse on the current
FacesContext instance, the JSF moves to the render response phase.
Phase 6: Render response
During this phase, the JSF asks container/application server to render the
page if the application is using JSP pages. For initial request, the components
represented on the page will be added to the component tree as the JSP
container executes the page. If this is not an initial request, the component
tree is already built so components need not to be added again. In either
case, the components will render themselves as the JSP container/Application
server traverses the tags in the page.
After the content of the view is rendered, the response state is saved so that
subsequent requests can access it and it is available to the restore view
phase.

2.How does JSF application get executed ? Explain.


The lifecycle of a JavaServer Faces application begins when the client
makes an HTTP request for a page and ends when the server responds
with the page, translated to HTML.
The lifecycle can be divided into two main phases, execute and render.
The execute phase is further divided into subphases to support the
sophisticated component tree.
This structure requires that component data be converted and
validated, component events be handled, and component data be
propagated to beans in an orderly fashion.
A JavaServer Faces page is represented by a tree of components, called
a view. When the client requests a page, the JavaServer 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 JavaServer Faces implementation performs all these tasks as a
series of steps in the JavaServer Faces request-response lifecycle

The request-response lifecycle handles two kinds of requests: initial


requests and postbacks. An initial request occurs when a user makes a
request for a page for the first time. A postback request occurs when a
user submits the form contained on a page that was previously loaded
into the browser as a result of executing an initial request.
When the lifecycle handles an initial request, it executes only the
Restore View and Render Response phases, because there is no user
input or action to process. Conversely, when the lifecycle handles a
postback, it executes all of the phases.

The JavaServer Faces application lifecycle execute phase


contains the following subphases:
Restore View Phase
Apply Request Values Phase
Process Validations Phase
Update Model Values Phase
Invoke Application Phase
Render Response Phase

3.Explain the advantages of EJB?


EJB provide developers architectural independence
EJB insulates developers from the underlying middleware, since the only
environment an EJB developer sees is the Java environment. It also helps the
EJB server/container vendor to change and make improvements on the
underlying middleware layer without affecting a users existing enterprise
applications.
WORA for server side components
Since EJB is based on Java technology, both the developer and the user are
guaranteed that their components are Write Once, Run Anywhere (WORA).
As long as an EJB Server faithfully conforms to the EJB specification, any EJB
application should run within that server.
EJB establishes Roles for Application Development
The EJB specification assigns specific roles for project participants charged
with enterprise application development utilizing EJB.
The server vendor can take care of providing support for complex system
services and make available an organized framework for a Bean to execute
in, without assistance from Bean developers.
EJB provides Distributed Transaction support
EJB provides transparency for distributed transactions. This means that a
client can begin a transaction and then invoke methods on Beans present
within two different servers, running on different machines, platforms or JVM.
It helps create Portable and Scalable solutions
Beans conforming to the EJB API will install and run in a portable fashion on
any EJB server.
It provides of vendor specific enhancements
Since the EJB specification provides a lot of flexibility for the vendors to
create their own enhancements, the EJB environment may end being feature
rich.
4.Explain the model view architecture?
MVC Architecture: The user can provide his own data-model for a
component by subclassing the Model class or by implementing the
appropriate interface. The ModelViewController (MVC) architecture is used

consistently throughout the swing component set. The view and controller
parts of the architecture are combined in the component.

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. x Model: It
represent a data or collection of multiple data use in MVC. e.g. database x
View: It is the component which is responsible for creating multiple views of
the some application. e.g. jsp x Controller: This component is sue to control
model as well as view. e.g. Servlet
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 retrives the appropriate date use for handling the data and send
that data to controller.
Controller forwards that data to view which will create multiple views from
that data. Sometimes the data accepted by view is not sufficient to create
the multiple views in that case view can directly interact with model for
getting that additional data.

5.Explain Different types of Session beans?


(i) Session beans Session beans are the beans which can requested by
particular client i.e. they can perform their work only after getting the client
request.
Characteristic of session bean
(1) They are short live beans
(2) They are transaction oriented
(3) They cannot be created by using a data from database, but they have the
ability to make changes in database.
(4) They can be stateful or stateless bean.
(5) They are synchronous in nature.
(6) They can be accessed with the help of home interface.
Types of session bean
(1) Statefull session bean Those are the bean which is use to store the
conversational information between the client & server for that they
maintain a state in which they can store the information. Because of that
state, the processing of this bean are slower.
(2) Stateless session bean Those are the bean which is not use to store the
conversational information between the client & server for that they not
maintain a state which they can Because of that.
(3) Singleton Session bean This bean are requested by multiple client
simultaneously.
(ii) Message driven bean Message driven bean can be use by generating the
appropriate event or a message by java messaging system.
Characteristics
(1) They are short live beans
(2) They are transaction oriented.
(3) They cannot be created by using a data from database, but they have the
ability to make changes in database.
(4) They are stateless.
(5) They are asynchronous.
(6) They does not use any home interface.
6.Enumerate the benifits of enterprise beans?
EJB is defined as an architecture for the development and deployment of
component-based, robust, highly scalable business applications. By using
EJB, you can write scalable, reliable, and secure applications without writing
your own complex distributed component framework.
Component portability - The EJB architecture provides a simple,
elegant component container model. Java server components can be
developed once and deployed in any EJB-compliant server.
Architecture independence - The EJB architecture is independent of
any specific platform, proprietary protocol, or middleware
infrastructure. Applications developed for one platform can be
redeployed on other platforms.

Developer productivity - The EJB architecture improves the


productivity of application developers by standardizing and automating
the use of complex infrastructure services such as transaction
management and security checking. Developers can create complex
applications by focusing on business logic rather than environmental
and transactional issues.
Customization - Enterprise bean applications can be customized
without access to the source code. Application behavior and runtime
settings are defined through attributes that can be changed when the
enterprise bean is deployed.
Multitier technology - The EJB architecture overlays existing
infrastructure services.
Versatility and scalability - The EJB architecture can be used for
small-scale or large-scale business transactions. As processing
requirements grow, the enterprise beans can be migrated to more
powerful operating environments.

What is facelet? write the features of facelets?


Facelets is the view declaration language (aka view handler) for JSF. It
is the replacement for JSP, which is now retained only for backward
compatibility. New features introduced in version 2 of the JSF
specification, such as composite components and Ajax, are only
exposed to page authors using facelets.
Key benefits of facelets include a powerful templating system, reuse
and ease of development, better error reporting (including line
numbers), and designer-friendliness.
Q:6.Answer the followings.
1.Explain the different roles of Action in Struts frameworks?
ROLES OF ACTION
Perform as a Model and determines single/multiple Results.
Action act as a Model by encapsulating the business logic within the
execute( )
method.
Action determines the Result that will render the View to be returned as
response.
It returns the control string that selects the appropriate result as configured.
E. g. : execute() method of email validation application
public ActionForward execute(ActionMapping mapping, ActionForm
form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
bean1 b1=(bean1)form;

String m = b1.getEmail();
if (m==null ||m.equals("") || m.indexOf("@") == -1) {
return mapping.findForward(FAILURE);}
else{
return mapping.finForward("SUCESS");
}}
(B) Serve as Data Carrier
Action serves as data carrier from request to the view, where data get stored
as JavaBean
properties. It allows accessing the data locally during the execution of
business logic.
Java bean code specifications to store the username and email from HTTP
request is :
private String username;
private String email;
public String getEmail() {
return email;}
public void setEmaiL(String email) {
this.email = email;}
public String getUsername() {
return username;}
public void setUsername(String username) {
this.username = username;}
What is HibernateTemplate class?
When Spring and Hibernate integration started, Spring ORM provided
two helper classes HibernateDaoSupport and HibernateTemplate. The
reason to use them was to get the Session from Hibernate and get the
benefit of Spring transaction management.
However from Hibernate 3.0.1, we can use SessionFactory
getCurrentSession() method to get the current session and use it to get
the spring transaction management benefits.
If you go through above examples, you will see how easy it is and
thats why we should not use these classes anymore.
One other benefit of HibernateTemplate was exception translation but
that can be achieved easily by using @Repository annotation with
service classes, shown in above spring mvc example.
This is a trick question to judge your knowledge and whether you are
aware of recent developments or not.
3.Explain the importance of mapping and show the creation of
mapping file in hibernate framework?...
Mapping File of hibernate application (hbm.xml)
Mapping file is the heart of hibernate application.

Every ORM tool needs this mapping, mapping is the mechanism of


placing an object properties into columns of a table.
Mapping can be given to an ORM tool either in the form of an XML or in
the form of the annotations.
The mapping file contains mapping from a pojo class name to a table
name and pojo class variable names to table column names.
While writing an hibernate application, we can construct one or more
mapping files, mean a hibernate application can contain any number of
mapping files.
generally an object contains 3 properties like
Identity (Object Name)
State (Object values)
Behavior (Object Methods)
Syntax of Mapping.xml
<hibernate-mapping><class name="POJO class name" table="table
name in database">
<id name="variable name" column="column name in database"
type="java/hibernate type"/>
<property name="variable1 name" column="column name in
database" type="java/hibernate type" />
<property name="variable2 name" column="column name in
database" type="java/hibernate type" /></class></hibernatemapping>
Configuration:
Configuration is the file loaded into an hibernate application when working
with hibernate, this configuration file contains 3 types of information..
Connection Properties
Hibernate Properties
Mapping file name(s)
We must create one configuration file for each database we are going to use,
suppose if we want to connect with 2 databases, like Oracle, MySql, then
we must create 2 configuration files.No. of databases we are using =
That many number of configuration files
We can write this configuration in 2 ways
xml
By writing Properties file. We dont have annotations here, actually
in hibernate 1, 2.x we defined this configuration file by writing
.properties file, but from 3.x xml came into picture.
so, finally
Mapping > xml, annotations
Configuration > xml, .properties (old style)
Syntax of Configuration:<hibernate-configuration><session-factory><!-- Related to the
connection START -->

<property name="connection.driver_class">Driver Class Name </property>


<property name="connection.url">URL </property>
<property name="connection.user">user </property>
<property name="connection.password">password</property>
<!-- Related to the connection END -->
<!-- Related to hibernate properties START -->
<property name="show_sql">true/false</property>
<property name="dialet">Database dialet class</property>
<property name="hbm2ddl.auto">create/update or what ever</property>
<!-- Related to hibernate properties END--><!-- Related to mapping
START-->
<mapping resource="hbm file 1 name .xml" / >
<mapping resource="hbm file 2 name .xml" / ><!-- Related to the
mapping END -->
</session-factory></hibernate-configuration>
4.Explain the Architecture of hibernate framework in details?

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


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.
Transaction : It is the optional object which is use to represent unit of work.
It represent the starting & ending of the transaction on database.
(v) Query : (i) If we want to perform operations on database using SQL or
hQl queries, then in that case session object create query object.
(vi) Criteria : If we want to perform operations on database using java
methods then in that case session create criteria object.
5.Explain Structure of hibernate.cfg.xml file?
<?xml version=1.0 encoding=UTF_8?>
<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/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>
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
6.Explain interceptors in struts?

Interceptors are used to implement cross-cutting concerns, such as


logging, auditing, and security, from the business logic.
The specification is not entirely new, as the concept already existed in
the EJB 3.0 specification. However, it is now abstracted at a higher
level so that it can be more generically applied to a broader set of
specifications in the platform.
Interceptors do what their name impliesthey intercept invocations
and life-cycle events on an associated target class. Basically, an
interceptor is a class whose methods are invoked when business
methods on a target class are invoked,
life-cycle events such as methods that create/destroy the bean occur,
or an EJB timeout method occurs. The CDI specification defines a typesafe mechanism for associating interceptors to beans using interceptor
bindings.
We need to define an interceptor binding type in order to intercept a
business method. We can do this by specifying the
@InterceptorBinding meta-annotation:
@InterceptorBinding @Retention(RUNTIME)
@Target({METHOD,TYPE}) public @interface Logging { }
@Target defines the program element to which this interceptor can be
applied. In this case, the annotation @Logging can be applied to a
method or a type (class, interface, or enum).
The interceptor is implemented as follows: @Interceptor @Logging
public class LoggingInterceptor { @AroundInvoke public
Object log(InvocationContext context) throws Exception
{ String name = context.getMethod().getName(); String
params = context.getParameters().toString(); //. . . return
context.proceed(); } }
Adding the @Interceptor annotation marks this class as an interceptor,
and @Log ging specifies that this is an implementation of the earlier
defined interceptor binding type.
@AroundInvoke indicates that this interceptor method interposes on
business methods. Only one method of an interceptor may be marked
with this annotation. InvocationContext provides context information
about the intercepted invocation and operations and can be used to
control the behavior of the invocation chain.
Name of the business method invoked and the parameters passed to
it can be retrieved from the context. This interceptor may be attached
to any managed bean: @Logging public class SimpleGreeting { //. . . }
Alternatively, we can log individual methods by attaching the
interceptor: public class SimpleGreeting { @Logging public String
greet(String name) { }}
You can define multiple interceptors using the same interceptor
binding. By default, all interceptors are disabled.

They need to be explicitly enabled and ordered via the @Priority


annotation, along with a priority value on the interceptor class:
@Priority(Interceptor.Priority.APPLICATION+10) @Interceptor
@Logging public class LoggingInterceptor { //. . . }

7.Classification of session beans in details OR Types of session


beans ?
A session bean encapsulates business logic that can be invoked
programmatically by a client over local, remote, or web service client
views. To access an application that is deployed on the server, the
client invokes the session beans methods. The session bean performs
work for its client, shielding it from complexity by executing business
tasks inside the server.
A session bean is not persistent. (That is, its data is not saved to a
database.)
Types of Session Beans
Session beans are of three types: stateful, stateless, and singleton.
Stateful Session Beans
The state of an object consists of the values of its instance variables. In
a stateful session bean, the instance variables represent the state of a
unique client/bean session. Because the client interacts (talks) with
its bean, this state is often called the conversational state.
As its name suggests, a session bean is similar to an interactive
session. A session bean is not shared; it can have only one client, in
the same way that an interactive session can have only one user.
When the client terminates, its session bean appears to terminate and
is no longer associated with the client.
Stateless Session Beans
A stateless session bean does not maintain a conversational state with
the client. When a client invokes the methods of a stateless bean, the
beans instance variables may contain a state specific to that client but
only for the duration of the invocation.
Because they can support multiple clients, stateless session beans can
offer better scalability for applications that require large numbers of
clients. Typically, an application requires fewer stateless session beans
than stateful session beans to support the same number of clients.
A stateless session bean can implement a web service, but a stateful
session bean cannot.
Singleton Session Beans
A singleton session bean is instantiated once per application and exists
for the lifecycle of the application. Singleton session beans are
designed for circumstances in which a single enterprise bean instance
is shared across and concurrently accessed by clients.

Singleton session beans offer similar functionality to stateless session


beans but differ from them in that there is only one singleton session
bean per application, as opposed to a pool of stateless session beans,
any of which may respond to a client request.
Like stateless session beans, singleton session beans can implement
web service endpoints.

8.When to Use Session Beans


Stateful session beans are appropriate if any of the following conditions
are true.
The beans state represents the interaction between the bean and a
specific client.
The bean needs to hold information about the client across method
invocations.
The bean mediates between the client and the other components of
the application, presenting a simplified view to the client.
Behind the scenes, the bean manages the work flow of several
enterprise beans.
To improve performance, you might choose a stateless session bean if
it has any of these traits.
The beans state has no data for a specific client.
In a single method invocation, the bean performs a generic task for all
clients. For example, you might use a stateless session bean to send
an email that confirms an online order.
The bean implements a web service.
Singleton session beans are appropriate in the following
circumstances.
State needs to be shared across the application.
A single enterprise bean needs to be accessed by multiple threads
concurrently.
The application needs an enterprise bean to perform tasks upon
application startup and shutdown.
The bean implements a web service.
9.What is Value Stack? Explain.
The Value Stack is a set of several objects stored in a specific oreder
that holds all the data
associated with the processing of request in struts Frame work based
application.
Before an Action execute() method is called for business processing,
Framework moves all the data to the value stack for request
processing.


Four

Framework Manipulates the value stack during Action execution,


render the result and Send the response page.
ValueStack Objects:
Temporary objects are created during the execution of page.
Example-The current iteration value is looped over a JSP tag etc.
Model Object is used in a stut application,the current Model Object is
placed on the value stack before the action execution.
Action Object, Is the current Action objects being executed.
Named Objects, It includes application ,Session,request,attributes
and parameters and refers to the corresponding servlet scopes.

Accessing the Value Stack


The Stack can be accessed via tags provided for JSP,Velocity of Freemarker.
ValueStack objects can be accessed inside the Action as:
ActionContext.getContext().getValueStack();
ValueStack Methods to manipulate the objects are:
Object findValue(String expr):Find the value by evaluating the give
expression against the stack
void setValue(String expr, Object value):Set a property on a bean
in the stack with the given expression
Object peek():Get the object on the top of Stack without changing
the stack.
Object pop():Get the Objects on the top of the Stack and remove it
from the stack.
void push(Object o):Put the Ojbect onto the top of the Stack.
int size():Set the Number of Objects in the stack.

10.What is purpose of Hibernate Mapping?


<?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>
</class>
</hibernate_mapping>
Elements:
<hibernate-mapping>.......</hibernat-mapping> It is the base tag
which is used to write hibernate mapping file, which is used to map POJO
class with database table.
<class>.......</class> It represents name of the class and database table
which we want to map with each other. It has 2 parameters:
name-It represents name of the class
table-It represents name of the database table
<property>.......</property> It is used to write the property which we
want to map with database column. It has 2 parameters:
name-It represents name of the property
type- It represents type of the property
<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
lenght- It represents maximum length of a column value
11.Struts 2 Architecture and Flow
The architecture and flow of struts 2 application, is combined with many
components such as Controller, ActionProxy, ActionMapper, Configuration
Manager, ActionInvocation, Inerceptor, Action, Result etc.
Here, we are going to understand the struts flow by 2 ways:
struts 2 basic flow
struts 2 standard architecture and flow provided by apache
struts
Struts 2 basic flow
Let's try to understand the basic flow of struts 2 application by this
simple figure:

struts 2 basic flow


User sends a request for the action
Controller invokes the ActionInvocation
ActionInvocation invokes each interceptors and action
A result is generated
The result is sent back to the ActionInvocation
A HttpServletResponse is generated
Response is sent to the user
Struts 2 standard flow (Struts 2 architecture)
Let's try to understand the standard architecture of struts 2 application
by this simple figure:

User sends a request for the action


Container maps the request in the web.xml file and gets the class
name of controller.
Container invokes the controller (StrutsPrepareAndExecuteFilter or
FilterDispatcher). Since struts2.1, it is StrutsPrepareAndExecuteFilter.
Before 2.1 it was FilterDispatcher.
Controller gets the information for the action from the ActionMapper
Controller invokes the ActionProxy
ActionProxy gets the information of action and interceptor stack from
the configuration manager which gets the information from the
struts.xml file.
ActionProxy forwards the request to the ActionInvocation
ActionInvocation invokes each interceptors and action
A result is generated
The result is sent back to the ActionInvocation
A HttpServletResponse is generated

Response is sent to the user

Q:7.Answer the followings.


1.What is CheckBoxGroup ?Explain with Example.
CheckBoxGroup is used to cfreate a set of mutually exclusive check
boxes in which only on e check Box in the group can be checked at a
time.
CheckBoxes created with grouping are known as radio buttons.
To create a set of Mutually exclusive checkboxes or radio buttons:
Define the group to which all the check boxes belong to.
Construct the Check boxes by specifying the group.
CheckBox groups are Object of Types CheckGroup.
import java.applet.Applet;
import java.awt.Checkbox;
import java.awt.CheckboxGroup;
/*
<applet code="CreateRadioButtonsExample" width=200 height=200>
</applet>
*/public class CreateRadioButtonsExample extends Applet{
public void init(){
CheckboxGroup lngGrp = new CheckboxGroup();
//if you
create checkboxes and add to group,they become radio buttons
Checkbox java = new Checkbox("Java", lngGrp, true);
Checkbox cpp = new Checkbox("C++", lngGrp, true);
Checkbox vb = new Checkbox("VB", lngGrp, true);
//add radio buttons
add(java);add(cpp);add(vb);}}

2.Explain JScrollPane and JScrollBar with Example?


JScrollPane is a Lieghtweight container that can be used to provide horizontal
and vertical scrollbars associated with any other components.
JScrollPane() constructor
JScrollPane()
JScrollPane(Component child)
JScrollPane(Component child,int verticalscroll,int horizontalscroll)
The Vertical and horizontal Scroll input can be:
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED

JScrollPane.VERTICAL_SCROLLBAR_NEVER
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER
Corner Component
void setCorner(String cornerlocation, Compnent c):the components
can be placed in the corners of a JScrollPane Object. Valid Corner
Locations are:
JScrollPane.LOWER_LEFT_CORNER
JScrollPane.LOWER_RIGHT_CORNER
JScrollPane.UPPER_LEFT_CORNER
JScrollPane.UPPER_RIGHT_CORNER
Example:
import java.awt.BorderLayout;
import javax.swing.*;
public class ScrollList extends JFrame {
JScrollPane scrollpane;
public ScrollList() {
super("JScrollPane Demonstration");
setSize(300, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
String categories[] = { "Household", "Office", "Extended Family",
"Company (US)", "Company (World)", "Team", "Will",
"Birthday Card List", "High School", "Country", "Continent",
"Planet" };
JList list = new JList(categories);
scrollpane = new JScrollPane(list);
getContentPane().add(scrollpane, BorderLayout.CENTER);}
public static void main(String args[]) {
ScrollList sl = new ScrollList();
sl.setVisible(true);}}
2.What are the different types of enterprise beans?Explain.
There are two main types of EJBs
1- Session Beans
2- Message Driven Beans
1- Session Beans
A session bean encapsulates business logic that can be invoked
programmatically by a client over local, remote, or web service client
views. A session bean is not persistent, means its data is not saved to
a database. EJB Session Beans has three types which are
Stateful Session Bean

In stateful session bean, the state of an object consists of the values of


its instance variables. In a stateful session bean, the instance variables
represent the state of a unique client / bean session.
Stateless Session Bean
In EJB stateless session bean conversational state is not maintained
with client. When a client invokes the methods of a stateless bean, the
beans instance variables may contain a state specific to that client but
only for the duration of the invocation.
Single tone Session Bean
A singleton session bean is instantiated once per application and exists
for the whole lifecycle of the java application. A single enterprise bean
instance is shared across all the applications clients and it is
concurrently accessed by clients
2- Message Driven Bean (MDB)
Message Driven Beans ( MDBs ) also known as Message Beans.
Message Driven Beans are business objects whose execution is
triggered by messages instead of by method calls.
3.What is OGNL?Exlain the execution flow of OGNL.
The Object-Graph Navigation Language (OGNL) is a powerful expression
language that is used to reference and manipulate data on the ValueStack.
OGNL also helps in data transfer and type conversion.
The OGNL is very similar to the JSP Expression Language. OGNL is
based on the idea of having a root or default object within the context.
The properties of the default or root object can be referenced using the
markup notation, which is the pound symbol.
As mentioned earlier, OGNL is based on a context and Struts builds an
ActionContext map for use with OGNL. The ActionContext map consists
of the following:
application - application scoped variables
session - session scoped variables
root / value stack - all your action variables are stored here
request - request scoped variables
parameters - request parameters
atributes - the attributes stored in page, request, session and
application scope
4.What is purpose of WEB-INF file?Explain.
The WEB-INF directory is part of the directory structure that defines a
particular "Web application". The WEB_INF directory contains resources
pertaining to the Web application including a web.xml file. Also contained in
the WEB-INF directory are the following:

A deployment descriptor file, called web.xml

A "lib" directory, designated for JAR files that are automatically added
to the Web application's classpath at runtime.
A "classes" directory designated for any classes needed by the
application that are not in a JAR file.
Any client classes for EJBs packaged in .jar files.
DefaultWebApp/WEB-INF/web.xml
The DefaultWebApp/WEB-INF/web.xml file is the Web application
deployment descriptor that configures the Web application.
DefaultWebApp/WEB-INF/weblogic.xml
The DefaultWebApp/WEB-INF/weblogic.xml file is the WebLogic-specific
deployment descriptor file that defines how named resources in the
web.xml file are mapped to resources residing elsewhere in WebLogic
Server. This file is also used to define JSP and HTTP session attributes.
DefaultWebApp/WEB-INF/classes
The DefaultWebApp/WEB-INF/classes directory contains server-side
classes such as HTTP servlets and utility classes.
DefaultWebApp/WEB-INF/lib
The DefaultWebApp/WEB-INF/lib directory contains JAR files used by
the Web application, including JSP tag libraries.
6.List and Explain different types of Enterprise beans?
EJB stands for Enterprise Java Beans. EJB is an essential part of a J2EE
platform. J2EE platform have component based architecture to provide multitiered, distributed and highly transactional features to enterprise level
applications.
EJB provides an architecture to develop and deploy component based
enterprise applications considering robustness, high scalability and high
performance. An EJB application can be deployed on any of the application
server compliant with J2EE 1.3 standard specification.
There are two main types of EJBs
1- Session Beans
2- Message Driven Beans
1- Session Beans
A session bean encapsulates business logic that can be invoked
programmatically by a client over local, remote, or web service client
views. A session bean is not persistent, means its data is not saved to
a database. EJB Session Beans has three types which are
Stateful Session Bean
In stateful session bean, the state of an object consists of the values of
its instance variables. In a stateful session bean, the instance variables
represent the state of a unique client / bean session.
Stateless Session Bean

In EJB stateless session bean conversational state is not maintained


with client. When a client invokes the methods of a stateless bean, the
beans instance variables may contain a state specific to that client but
only for the duration of the invocation.
Single tone Session Bean
A singleton session bean is instantiated once per application and exists
for the whole lifecycle of the java application. A single enterprise bean
instance is shared across all the applications clients and it is
concurrently accessed by clients
2- Message Driven Bean (MDB)
Message Driven Beans ( MDBs ) also known as Message Beans.
Message Driven Beans are business objects whose execution is
triggered by messages instead of by method calls.

Das könnte Ihnen auch gefallen