Adv Java Soln
Adv Java Soln
V
Advanced Java
Time : 2½ Hrs.] Prelim Question Paper Solution [Marks : 75
r
ka
an
JFrame frm1 = new JFrame();
JPanel op = new JPanel();
frm1 .add (op, BorderLayout.NORTH);
al
Example
import java.awt.*;
import javax.swing.*;
dy
}
BorderTest()
{
//... Create components (but without listeners)
JButton north = new JButton("North");
JButton east = new JButton("East");
JButton south = new JButton("South");
JButton west = new JButton("West");
JButton center = new JButton("Center");
content.add(north , BorderLayout.NORTH);
1
Vidyalankar : T.Y. B.Sc. (IT) – Adv. Java
content.add(east , BorderLayout.EAST);
content.add(south , BorderLayout.SOUTH);
content.add(west , BorderLayout.WEST);
content.add(center, BorderLayout.CENTER);
r
Delegation event model consist of following three concepts which are used for handling the
event :
ka
1) Event
Definition : Event is also object.
i) Event is de3fined as the object which describe the state change of the particular
source.
ii) Event can be occur on multiple conditions like clicking on a button. Selecting a
Checkbox, Scrolling the scrollbars, etc.
2) Source
an
i) Definition : Source are the objects which generates a particular event.
ii) If we want a particular source should generate a particular event, in that case that
source should get registered with a specific event using following method :
addTypeListener (TypeListener tl);
al
3) EventListeners
i) EventListeners are those interfaces which contains different methods which are
used or get override to receive the event and take the corrective action on that
event.
ii) ActionListener, ItemListener, MouseListener, etc. are different interfaces which
dy
Event Handling
Even the operations which are occurred when the components will get clicked or selected to
handle each type of event java develops different event classes.
Each event class has its specific condition and when that condition will occur the
Vi
appropriate event will get generated. When the event will get generated the event object
will get throw and to receive that object different receiving method can be used.
A component can generated a particular event only when it is registered for that particular event.
2
Prelim Question Paper Solution
add (l);
add (b1);
add (b2);
add (b3);
r
setSize (200, 300);
ka
setTitle (“SSS”);
setVisible (true);
}
{
setBackground (c2);
else
{
setBackground (c3);
}
Vi
}
class demo extends WindowAdapter
{
public void WindowCloasing (WindowEvent we);
{
System.exit (0);
}
}
3
Vidyalankar : T.Y. B.Sc. (IT) – Adv. Java
Inner Class
1) Inner class is used when we want our main class to get derived from Frame class.
2) In that case we create a new class called as inner class, place it inside the main class
and derived it from the appropriate adapter class, so that we can override a specific
method from that adapter class.
r
{
Frame f;
ka
testevent( )
{
f = new Frame( );
f.setLayout(new FlowLayout( ));
Label l = new Label (“select a color:”);
an
Button b1 = new Button (“Red”);
Button b2 = new Button (“Green”);
Button b3 = new Button (“Blue”);
b1.addActionListener (this);
b2.addActionListener (this);
b3.addActionListener (this);
al
f.addWindowListener (this);
f.add(l);
f.add(b1);
dy
f.add(b2);
f.add(b3);
f.setSize (200, 300);
f.setTitle (“SSS”);
f.setVisible (true);
}
Vi
if (s.equals (“Red”))
{
f.setBackground (c1);
}
else if (s equals (“Green”))
{
f.setBackground (c2);
4
Prelim Question Paper Solution
}
else
{
f.setBackground (c3);
}
}
r
test event t = new testevent( );
}
ka
}
Adapter Class
1) Adapter class is used to overcome the problem of writing different methods of empty
implementation.
2) Normally if we use event listener, then we need to override all its methods.
an
3) If we want to override only certain specific method, then in that case EventListener can
be replaced with EventAdapter Class.
(A)
AWT Components Swing Components
1) AWT components are non java components Swing components are pure java components
2) They are platform dependent components They are platform independent components
3) They are non decorative components They are decorative. We can even place an
image on a component
4) They are normally rectangular in shape We can create different shape components
5) Those are considered as heavy weight Those are considered as light weight
components components
6) They are not used to perform complex They are used to perform complex
operations operations
7) Those classes are present in java.awt Those classes are present in javax.swing
package package
5
Vidyalankar : T.Y. B.Sc. (IT) – Adv. Java
import java.awt.event.*;
import java.awt.*;
import javax.swing.event.*;
import javax.swing.tree.*;
import javax.swing.*;
r
public class JTreeExample extends JFrame{
ka
public JTreeExample()
{
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DefaultMutableTreeNode everything = new
DefaultMutableTreeNode("Everything");
JTree avm = new JTree(everything);
an
DefaultMutableTreeNode animal = new
DefaultMutableTreeNode("Animal");
everything.add(animal);
animal.add(new DefaultMutableTreeNode("Cat"));
animal.add(new DefaultMutableTreeNode("Dog"));
animal.add(new DefaultMutableTreeNode("Fish"));
al
DefaultMutableTreeNode vegetable = new
DefaultMutableTreeNode("Vegetable");
everything.add(vegetable);
dy
vegetable.add(new DefaultMutableTreeNode("Onion"));
vegetable.add(new DefaultMutableTreeNode("Lettuce"));
vegetable.add(new DefaultMutableTreeNode("Carrot"));
fruits.add(new DefaultMutableTreeNode("Mango"));
fruits.add(new DefaultMutableTreeNode("Banabna"));
fruits.add(new DefaultMutableTreeNode("Guava"));
6
Prelim Question Paper Solution
Q.2(c) Write a program to create a combobox, and add different items in that [5]
combobox by accepting them from user.
(A) import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class combo extends JFrame implements ActionListener
{
JComboBox jc;
JButton jb;
JTextField jt;
combo()
{
Container c=getContentPane();
r
c.setLayout(new FlowLayout());
jc=new JComboBox();
ka
jb=new JButton("Add");
jt=new JTextField(10);
jb.addActionListener(this);
an
c.add(jc);
c.add(jt);
c.add(jb);
setSize(500,500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
al
public void actionPerformed(ActionEvent ae)
{
String s=jt.getText();
jc.addItem(s);
dy
}
public static void main(String args[])
{
combo cb=new combo();
}
}
Vi
Q.2(d) What is the purpose of tabbed panes? Explain with suitable example. [5]
(A) Purpose of TabbedPanes :
This component lets the user switch between a group of components by clicking on a tab
with a given title and/or icon.
Tabs are added to a TabbedPane object by using the addTab() or an insertTab()
methods.
Example:
import javax.swing.JTabbedPane;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JTabbedPaneDemo extends JFrame {
public static void main(String args[])
7
Vidyalankar : T.Y. B.Sc. (IT) – Adv. Java
{
JTabbedPaneDemo d = new JTabbedPaneDemo();
JTabbedPane p = new JTabbedPane();
p.addTab("Cities", new CitiesPanel());
p.addTab("Colors", new ColorsPanel());
d.add(p);
d.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
d.setSize(500,500);
d.setVisible(true);
}
}
class CitiesPanel extends JPanel
{
r
public CitiesPanel ()
{
ka
JButton b1 = new JButton("New York");
add(b1);
}
}
username :
password :
Login
Vi
<html>
<head>
<title> Servlet Application </title> </head>
<body>
<form method = "post" action = "test">
<b> Username </b>
<input type = "text" name = "u" value = " " size = "10">
<input type = "password" name = "p" value = " " size = "10">
<input type = "submit" value = "login">
</form>
</body>
</html>
//test.java
import javax.servlet.*;
import javax.servlet.http.*;
8
Prelim Question Paper Solution
import java.io.*;
public class test extends HttpServlet
{
public void doPost(HttpServletRequest Request,
HttpServletResponse Response) throws IOException
ServletException
{
response.setContentType("text/html?);
PrintWriter out = response.getWriter( );
String n = request.getParameter("u");
String p = request.getParameter("p");
out.print ln("H \ ");
if((n.equals("admin")) && (p.equals("admin")))
{
r
RequestDispatcher rd1 = request.getrequestDispatchers
("Welcome");
ka
rd1.include(request, response);
}
else
{
RequestDispatchers rd2 = request.getRequestDispatchers
("Errors");
}
an rd2.forward(request, response);
out.close( );
}
}
Request Dispatchers
al
1) Any Servlet application can be created as a request dispatcher by using following
method
getRequestDispatcher( );
2) RequestDispatchers is a class which is there inside the package javax.servlet
dy
9
Vidyalankar : T.Y. B.Sc. (IT) – Adv. Java
HttpServlet:
HttpServlet class is the direct subclass of Generic Servlet.
HttpServlet is protocol dependent. It handles only http protocol.
r
HttpServlet supports public void service(ServletRequest req,ServletResponse res ) and
protected void service(HttpServletRequest req,HttpServletResponse res).
ka
HttpServlet supports also
doGet(),doPost(),doPut(),doDelete(),doHead(),doTrace(),doOptions() etc.
An HTTP servlet usually does not override the service() method. Instead, it overrides
doGet() to handle GET requests and doPost() to handle POST requests.
An HTTP servlet can override either or both of these methods, depending on the type
of requests it needs to handle.
an
The service() method of HttpServlet handles the setup and dispatching to all the
doXXX() methods
al
dy
10
Prelim Question Paper Solution
</html>
//test.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
r
{
String answer=request.getParameter("java");
ka
if((answer.equals("d"))||(answer.equals("b")))
{
out.println("Wrong Answer");
}
else
{
}
an
out.println("Correct Answer");
}
finally
{
out.close();
al
}
}
}
Q.3(d) Develop servlet application of basic calculator (+, , *, /) using HttpServletRequest [5]
dy
and HttpServletResponse.
(A) //index.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
Vi
</head>
<body>
<form method="post" action="calculate">
<h1>Simple Calculator</h1>
<hr>
<b>Enter First Number</b>
<input type="number" name="n1" value="" size="2">
<p>
<b>Enter Second Number</b>
<input type="number" name="n2" value="" size="2">
<p>
<b>Enter Operation</b>
<input type="text" name="op" value="" size="2">
<p>
11
Vidyalankar : T.Y. B.Sc. (IT) – Adv. Java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class calculate extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
r
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
ka
try {
int a=Integer.parseInt(request.getParameter("n1"));
int b=Integer.parseInt(request.getParameter("n2"));
String op=request.getParameter("op");
int c;
if(op.equals("+"))
{
c=a+b;
an
}
else if(op.equals("-"))
{
c=a-b;
}
al
else if(op.equals("*"))
{
c=a*b;
}
dy
else
{
c=a/b;
}
out.println("The Result is "+c);
} finally {
Vi
out.close();
}
}
}
12
Prelim Question Paper Solution
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection c = DriverManager.getConnection("jdbc:odbc:sss");
PreparedStatement ps=c.prepareStatement("insert into student values(?,?)");
ps.setInt(1,10);
ps.setString(2,"SSS");
ps.execute();
ps.close();
c.close();
}
catch(Exception e)
{
System.out.println("Exception occur");
}
r
}
}
ka
Q.4(b) Explain character quoting convention in JSP [5]
(A) Character Quoting Conventions
Because certain character sequences are used to represent start and stop tags, the
developer sometimes need to escape a character so the JSP engine does not interpret it as
part of a special character sequence.
an
In scripting element, if the characters %> needs to be used, escape the greater than sign
with a backslash:
<% String message = “This is the %\ message” ; %>
The backslash before the expression acts as an escape character, informing the JSP engine
to deliver the expression verbatim instead of evaluating it.
al
There are a number of special constructs used in various cases to insert characters that
would otherwise be treated specially, they are as follows :
Escape Description
Characters
dy
backslash
Example
<% String message = ‘Escaping \’ single quote’; %>
<% String message = ‘Escaping \’ double quote’; %>
<% String message = ‘Escaping \ \ backslash’; %>
<% String message = ‘Escaping % \ > scripting end tag’’; %>
<% String message = ‘Escaping < \ % scripting start tag’’; %>
<% String message = ‘Escaping \$ dollar sign” ; %>
As an alternative to escaping quote characters, the character entities ' and " can
also be used.
13
Vidyalankar : T.Y. B.Sc. (IT) – Adv. Java
r
JDBC DB specific
calls calls
ka
JDBC T2
DB
Appl.
Native API
Native API
14
Prelim Question Paper Solution
(b) Compilation :
The generated servlet is compiled to validate the syntax.
The compilation generate class file to run on JVM.
(c) Loading :
The complied byte code is loaded in web container i.e. Web server.
If not
Request initialized
Client Translation Compilation Loading
Already
Initialized
Initialization Instantiation
Response
Request Processing
r
Destruction
ka
(d) Instantiation:
In this step, instance of the servlet class is created, so that it can handle
request.
(e) Initialization :
an
It can be done using jspInit( ). This is one time actively and after initialization,
the servlet is ready to process requests.
2) Request Processing : Entire initialization process is done to make the servlet available
in order to process the incoming request.
jspService( ) is the method that actually process the request.
al
3) Destroy : Whenever the server needs memory, the server removes the instance of the
servlet.
The jspDestory( ) can be called by the server after initialization and before or after
dy
request processing.
Faces Apply
Restore Process Process Process
response request
view event Validation event
values
Reader response
Faces Update
Render Process Invotie Process
response model
response Event application Event
values
Conversion error/render
15
Vidyalankar : T.Y. B.Sc. (IT) – Adv. Java
r
ii) If the rules does not match then the error message will get render to a client.
4. Update model values
ka
i) In this face the components from component tree will update the component
present inside the webserver.
ii) It is also called as baching a bear.
5. Invest application
i) In this face the application will get invest or execute to create responses.
ii) Also if they are multiple pages then lintsing of those page will also get done in this
phase.
6. Render response
an
In this phase the generated responses will get render i.e. provided to a client as a
response.
Portable Components : EJB components created inside one web server can be used in
another web server.
Reusable component : We can create on EJB only once and by storing it inside the web
server we can use it multiple time.
Reduces execution time: As EJB component are readymade component the user need not
to create this component every time, which reduces overall execution time.
Vi
Distributed deployment: EJB’s can be used in distributed architecture where the EJB’s
can get store in multiple system in distributed manner.
Interoperability : EJB’s can be used by multiple types of request, because the EJB has
concept of CORBA (common object request brother architecture) which converts
different type of request into common format.
16
Prelim Question Paper Solution
Q.5(d) Write a program using JSF to find square root of a number. [5]
(A) //index.xhtml
<?xml version='1.0' encoding='UTF-8' ?>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
r
<h:form>
<h:outputLabel for="txtName">
ka
<h:outputText value="Enter number:" />
</h:outputLabel>
<h:inputText id="txtName" value="#{user.number}">
</h:inputText>
<h:commandButton value="Square Root" action="#{user.calculate}"/>
</h:form>
</h:body>
</html>
an
//userbean.java
import javax.faces.bean.*;
@ManagedBean(name="user")
public class userbean
al
{
int number;
double root;
public int getnumber()
dy
{
return number;
}
public void setnumber(int a)
{
number=a;
Vi
}
public double getroot()
{
return root;
}
public void setroot(double b)
{
root=b;
}
public String calculate()
{
root=Math.sqrt(number);
return "success";
}
}
17
Vidyalankar : T.Y. B.Sc. (IT) – Adv. Java
//faces-config.xml
<?xml version='1.0' encoding='UTF-8'?>
<faces-config version="2.0">
<navigation-rule>
<from-view-id>/index.xhtml</from-view-id>
<navigation-case>
<from-outcome>success</from-outcome>
<to-view-id>/first.xhtml</to-view-id>
</navigation-case>
</navigation-rule>
</faces-config>
//first.xhtml
<?xml version='1.0' encoding='UTF-8' ?>
r
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
ka
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
<h:form>
<h:outputText value="Square root is= #{user.root} ">
</h:outputText>
</h:form>
an
</h:body>
</html>
Event
dy
Controller
View
Vi
Model
1. MVC architecture is normally use to create multiple views of the same application.
2. The basic intention of MVS is to separate application logic with presentation logic.
3. The architecture of MVC contains following 3 components.
Model: It represent a data or collection of multiple data use in MVC.
e.g. database
View: It is the component which is responsible for creating multiple views of the
some application.
e.g. jsp
Controller: This component is sue to control model as well as view.
e.g. Servlet
18
Prelim Question Paper Solution
4. Working
i) Whenever on event will occur for the use of MVC architecture, the event or the
request has been accepted by controller.
ii) Controller forward that request to model component, where model component retrieves
the appropriate date use for handling the data and send that data to controller.
Controller forwards that data to view which will create multiple views from that data.
Sometimes the data accepted by view is not sufficient to create the multiple views in
that case view can directly interact with model for getting that additional data.
r
Reads dispatchers
configurator
ka
Struts
Result
Client Xml
<hibernateconfiguration>
<sessionfactory>
Vi
<property name=”hibernate.connection.username”>
root</property>
<property name=”hibernate.connection.password”>
root</property>
<mapping resource=”guestbook.hbm.xml”/>
</sessionfactory>
</hibernateconfiguration>
19
Vidyalankar : T.Y. B.Sc. (IT) – Adv. Java
Elements:
hibernate.dialect It represents the name of the SQL dialect for the database
hibernate.connection.driver_class It represents the JDBC driver class for the specific
database
hibernate.connection.url It represents the JDBC connection to the database
hibernate.connection.username It represents the user name which is used to connect to
the database
hibernate.connection.password It represents the password which is used to connect to the
database
guestbook.hbm.xml It represents the name of mapping file
r
(A)
ka
an
Fig. 1
al
(1) The working of hibernate will state when persistent object i.e. POJO has been created
by the java application.
(2) Hibernate layer is divided into following different object which are use to perform
different operation.
dy
(i) Configuration :
(i) This object is used to establish a connection with the database.
(ii) It contains following 2 files
(a) hibernate. properties it is use to give some additional information about the
hibernate layer.
(b) hibernate (f.g. xml It is use to establish a connection with a particular
Vi
database.)
(iii) Configuration object is also use to create session factory.
(ii) Session factory :
(a) As the name suggest session factory is use to create different session objects.
(b) Session factory will created only once, but to perform multiple operation it will
create multiple session object.
(iii) Session :
It is generally use to receive a persistent object inside the hibernate layer.
Session object is responsible to create transaction object & perform appropriate
operation on persistent object.
(iv) Transaction :
It is the optional object which is use to represent unit of work.
It represent the starting & ending of the transaction on database.
20
Prelim Question Paper Solution
(v) Query :
(i) If we want to perform operations on database using SQL or hQl queries, then in
that case session object create query object.
(vi) Criteria :
If we want to perform operations on database using java methods then in that case
session create criteria object.
Grid Layout
r
A GridLayout object places components in a grid of cells. Each component takes all the
available space within its cell, and each cell is exactly the same size. If the GridLayoutDemo
ka
window is resized, the GridLayout object changes the cell size so that the cells are as large
as possible, given the space available to the container.
Layout Design
an
Sample Program or Code snippet
al
import java.awt.*;
import java.applet.*;
.
/*
dy
21
Vidyalankar : T.Y. B.Sc. (IT) – Adv. Java
Q.7(b) Write a program to create a split pane in which left side of split Pane contains a [5]
list of planet and when user clicks on any planet name, its image should get
displayed an right side.
(A) import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;
r
{
Container c=getContentPane();
ka
c.setLayout(new FlowLayout());
String s[]={"earth","mercury","saturn"};
jl=new JList(s);
jl.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
an
i1=new ImageIcon("earth.jpg");
i2=new ImageIcon("mercury.png");
i3=new ImageIcon("saturn.jpg");
j=new JLabel(i1);
jsp=new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
al
jsp.setLeftComponent(jl);
jsp.setRightComponent(j);
jl.addListSelectionListener(this);
dy
c.add(jsp);
setSize(500,500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Vi
}
public void valueChanged(ListSelectionEvent ls)
{
String p=(String)jl.getSelectedValue();
if(p.equals("earth"))
{
j.setIcon(i1);
}
else if(p.equals("mercury"))
{
j.setIcon(i2);
}
else
{
22
Prelim Question Paper Solution
j.setIcon(i3);
}
}
public static void main(String args[])
{
list l=new list();
}
}
Q.7(c) Explain CGI and its woring. Also wirte disadvantages of CGI. [5]
(A)
http reg.
web
Client CGI
Server
http res
r
DB
ka
Server
(i) CGI : Common gateway interface is responsible to provide dynamic response in case of
Three tire architecture.
(ii) Working :
When webserver accept request which require dynamic response web server
an
forward the request to CGI.
CGI is a program which accept the request & to handle that request create CGI.
Process & load that process inside the web server.
Now that process is responsible to provide dynamic response to the client.
Once this can be done web server destroy the process to free its memory.
(d) Three-tier architecture
al
http reg
web
Client
Server
http res
dy
DB
Server
(i) In this there exist three entity i.e. client, webserver & Database server.
(ii) Basically here server get distributed in web server & database server.
(iii) Web server is responsible to interact with client as well as database server.
Vi
23
Vidyalankar : T.Y. B.Sc. (IT) – Adv. Java
</navigation-rule>
The <navigation-rule> element represents an individual decision rule. This rule is accessed
when the default Navigation Handler is implemented. This rule helps make decisions on what
view to display next, based on the View ID being processed.
r
The <navigation-case> Element
ka
<navigation-case>
- - -
- - -
</navigation-case>
The <navigation-case> element describes a specific combination of conditions that must
match, for this case to be executed. It also describes the view id of the component tree
an
that should be selected next.
The <from-outcome> element contains a logical outcome string. This string is returned by
the execution of an application action method via an actionRef property of a UICommand
al
component.
If this element is specified, then this rule is relevant only if the outcome value matches this
element’s value.
If this element is not specified, then this rule is relevant no matter what the outcome value
dy
was.
Example
<navigation-rule>
<from-view-id>/pages/inputname.jsp</from-view-id>
<navigation-case>
<from-outcome>sayHello</from-outcome>
<to-view-id>/pages/greeting.jsp</to-view-id>
</navigation-case>
<navigation-case>
<from-outcome>sayGoodbye</from-outcome>
<to-view-id>/pages/goodbye.jsp</to-view-id>
</navigation-case>
</navigation-rule>
This code specifies that view /pages/inputname.jsp has two outputs, sayHello and
sayGoodbye, associated with particular pages.
24
Prelim Question Paper Solution
r
(b) Include directive tag :
It is use to include the contents of one JSP application inside the current JSP
ka
application.
e.g.
<%@ include file = “abc.jsp” %>
e.g.
<% = a%>
e.g.
<%
___
___ java code
___
>
25
Vidyalankar : T.Y. B.Sc. (IT) – Adv. Java
r
</class>
</hibernatemapping>
ka
Elements:
<hibernatemapping>….......</hibernatemapping>
It is the base tag which is used to write hibernate mapping file, which is used to map POJO
class with database table.
an
<class>….......</class>
It represents name of the class and database table which we want to map with each other.
It has 2 parameters:
name It represents name of the class
table It represents name of the database table
<property>….......</property>
al
It is used to write the property which we want to map with database column. It has 2
parameters:
name It represents name of the property
type It represents type of the property
dy
<column>….......</column>
It is used to write the database column which we want to map with java class property. It
has 2 parameters:
name It represents name of the column
length It represents maximum length of a column value
Vi
26