26
1 T.Y. B.Sc. (IT) : Sem. V Advanced Java Time : 2½ Hrs.] Prelim Question Paper Solution [Marks : 75 Q.1 Attempt the following (any TWO) [10] Q.1(a) What is the default layout of the frame? Explain the same. [5] (A) [Explanation 2 marks, Diagram 1 marks, Program 2 marks] BORDERLAYOUT is the default layout of the frame. It splits the container into five distinct sections where each section can hold one component. The five sections of the BorderLayout are known as NORTH, SOUTH, EAST, WEST and CENTER as shown in the diagram. To add a component to a BorderLayout, one needs to specify which section one wants it placed. JFrame frm1 = new JFrame(); JPanel op = new JPanel(); frm1 .add (op, BorderLayout.NORTH); Example import java.awt.*; import javax.swing.*; class BorderTest extends JFrame { public static void main(String[] args) { JFrame window = new BorderTest(); window.setVisible(true); } BorderTest() { //... Create components (but without listeners) JButton north = new JButton("North"); JButton east = new JButton("East"); JButton south = new JButton("South"); JButton west = new JButton("West"); JButton center = new JButton("Center"); //... Create content pane, set layout, add components JPanel content = new JPanel(); content.setLayout(new BorderLayout()); content.add(north , BorderLayout.NORTH); Vidyalankar

Adv Java. Soln - Vidyalankar Coaching Classesvidyalankar.org/file/bsc-it/Soln/Adv_Java_Soln.pdf · 1 T.Y. B.Sc. (IT) : Sem. V Advanced Java Time : 2½ Hrs.] Prelim Question Paper

  • Upload
    vungoc

  • View
    233

  • Download
    3

Embed Size (px)

Citation preview

Page 1: Adv Java. Soln - Vidyalankar Coaching Classesvidyalankar.org/file/bsc-it/Soln/Adv_Java_Soln.pdf · 1 T.Y. B.Sc. (IT) : Sem. V Advanced Java Time : 2½ Hrs.] Prelim Question Paper

1

T.Y. B.Sc. (IT) : Sem. V Advanced Java

Time : 2½ Hrs.] Prelim Question Paper Solution [Marks : 75 Q.1 Attempt the following (any TWO) [10]Q.1(a) What is the default layout of the frame? Explain the same. [5](A) [Explanation 2 marks, Diagram 1 marks, Program 2 marks]

BORDERLAYOUT is the default layout of the frame. It splits the container into five distinct sections where each section can hold one

component. The five sections of the BorderLayout are known as NORTH, SOUTH, EAST, WEST and

CENTER as shown in the diagram. To add a component to a BorderLayout, one needs to specify which section one wants it

placed.

JFrame frm1 = new JFrame(); JPanel op = new JPanel(); frm1 .add (op, BorderLayout.NORTH);

Example import java.awt.*; import javax.swing.*;

class BorderTest extends JFrame {

public static void main(String[] args) { JFrame window = new BorderTest(); window.setVisible(true); } BorderTest() { //... Create components (but without listeners) JButton north = new JButton("North"); JButton east = new JButton("East"); JButton south = new JButton("South"); JButton west = new JButton("West"); JButton center = new JButton("Center"); //... Create content pane, set layout, add components JPanel content = new JPanel(); content.setLayout(new BorderLayout()); content.add(north , BorderLayout.NORTH);

Vidyala

nkar

Page 2: Adv Java. Soln - Vidyalankar Coaching Classesvidyalankar.org/file/bsc-it/Soln/Adv_Java_Soln.pdf · 1 T.Y. B.Sc. (IT) : Sem. V Advanced Java Time : 2½ Hrs.] Prelim Question Paper

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

2

content.add(east , BorderLayout.EAST); content.add(south , BorderLayout.SOUTH); content.add(west , BorderLayout.WEST); content.add(center, BorderLayout.CENTER); //... Set window characteristics. setContentPane(content); setTitle("BorderTest"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }

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

Delegation event model consist of following three concepts which are used for handling the event : 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 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);

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 can be used to override their methods.

Event Handling Even the operations which are occurred when the components will get clicked or selected to handle each type of event java develops different event classes. Each event class has its specific condition and when that condition will occur the appropriate event will get generated. When the event will get generated the event object will get throw and to receive that object different receiving method can be used. A component can generated a particular event only when it is registered for that particular event.

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

Example : import java.awt.*; import java.awt.event.*; class testevent extends frame implements ActionListener { testevent( ) {

Vidyala

nkar

Page 3: Adv Java. Soln - Vidyalankar Coaching Classesvidyalankar.org/file/bsc-it/Soln/Adv_Java_Soln.pdf · 1 T.Y. B.Sc. (IT) : Sem. V Advanced Java Time : 2½ Hrs.] Prelim Question Paper

Prelim Question Paper Solution

3

setLayout (new FlowLayout( )); Label l = new Label (“select a color :”); Button b1 = new Button (“Red”); Button b2 = new Button (“Green”); Button b3 = new Button (“Blue”); b1.addActionListener (this); b2.addActionListener (this); b3.addActionListener (this); addWindowListener (new demo ( )); add (l); add (b1); add (b2); add (b3); setSize (200, 300); setTitle (“SSS”); setVisible (true); } public void actionPerformed (ActionEvent ae); { String s = ae.getActionCommand( ); Color c1 = new Color (255,0,0); Color c2 = new Color (0,255,0); Color c3 = new Color (0,0,255); if (s.equals (“Red”)) { setBackground (c1); } else if (s.equals (“Green”)) { setBackground (c2); else { setBackground (c3); } } class demo extends WindowAdapter { public void WindowCloasing (WindowEvent we); { System.exit (0); } } public static void main (string a[ ]) { testevent t = new testevent( ); } }

Vidyala

nkar

Page 4: Adv Java. Soln - Vidyalankar Coaching Classesvidyalankar.org/file/bsc-it/Soln/Adv_Java_Soln.pdf · 1 T.Y. B.Sc. (IT) : Sem. V Advanced Java Time : 2½ Hrs.] Prelim Question Paper

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

4

Inner Class 1) Inner class is used when we want our main class to get derived from Frame class. 2) In that case we create a new class called as inner class, place it inside the main class

and derived it from the appropriate adapter class, so that we can override a specific method from that adapter class.

Q.1(d) Explain Adapter Class with example. [5](A) Adapter Class

Example : import java.awt.*; import java.awt.event.*;

class testevent extends WindowAdapter implements ActionListener { Frame f; testevent( ) { f = new Frame( ); f.setLayout(new FlowLayout( )); Label l = new Label (“select a color:”); Button b1 = new Button (“Red”); Button b2 = new Button (“Green”); Button b3 = new Button (“Blue”); b1.addActionListener (this); b2.addActionListener (this); b3.addActionListener (this); f.addWindowListener (this); f.add(l); f.add(b1); f.add(b2); f.add(b3); f.setSize (200, 300); f.setTitle (“SSS”); f.setVisible (true); } Public void actionPerformed (ActionEvent ae) { String s = ae.getActionCommand( ); Color c1 = new Color (255,0,0); Color c2 = new Color (0,255,0); Color c3 = new Color (0,0,255); if (s.equals (“Red”)) { f.setBackground (c1); } else if (s equals (“Green”)) { f.setBackground (c2);

Vidyala

nkar

Page 5: Adv Java. Soln - Vidyalankar Coaching Classesvidyalankar.org/file/bsc-it/Soln/Adv_Java_Soln.pdf · 1 T.Y. B.Sc. (IT) : Sem. V Advanced Java Time : 2½ Hrs.] Prelim Question Paper

Prelim Question Paper Solution

5

} else { f.setBackground (c3); } } Public void WindowClosing (WindowEvent we) { System.exit (0); } Pubic Static void main (String a[ ]) { test event t = new testevent( ); } }

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. 3) If we want to override only certain specific method, then in that case EventListener can

be replaced with EventAdapter Class.

EventClass EventListener EventAdapter Class ActionEvent ActionListener ActionAdapter ItemEvent ItemListener ItemAdapter MouseEvent MouseListener MouseAdapter KeyEvent KeyListener KeyAdapter ComponentEvent ComponentListener ComponentAdapter ContainerEvent ContainerListener ContainerAdapter AdjustmentEvent AdjustmentListener AdjustmentAdapter TextEvent TextListener TextAdapter WindowEvent WindowListener WindowAdapter MouseWheelEvent MouseWheelListener MouseWheelAdapter

Q.2 Attempt the following (any TWO) [10]Q.2(a) Differentiate between AWT component and Swing Component. [5](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

components Those are considered as light weight components

6) They are not used to perform complex operations

They are used to perform complex operations

7) Those classes are present in java.awt package

Those classes are present in javax.swing package

Vidyala

nkar

Page 6: Adv Java. Soln - Vidyalankar Coaching Classesvidyalankar.org/file/bsc-it/Soln/Adv_Java_Soln.pdf · 1 T.Y. B.Sc. (IT) : Sem. V Advanced Java Time : 2½ Hrs.] Prelim Question Paper

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

6

Q.2(b) How can a Tree structure be created in Swing? Explain. [5](A) A tree structure is created in the following ways.

The node is represented in Swing API as TreeNode which is an interface. The interface MutableTreeNode extends this interface which represents a mutable node. Swing API provides an implementation of this interface in the form of DefaultMutableTreeNode class.

DefaultMutableTreeNode class is to be used to represent the node. This class is provided in the Swing API. This class has a handy add() method which takes in an instance of MutableTreeNode.

So, first root node is created. And then recursively nodes are added to that oot.

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

public class JTreeExample extends JFrame{ public JTreeExample() { this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); DefaultMutableTreeNode everything = new DefaultMutableTreeNode("Everything"); JTree avm = new JTree(everything); DefaultMutableTreeNode animal = new DefaultMutableTreeNode("Animal"); everything.add(animal); animal.add(new DefaultMutableTreeNode("Cat")); animal.add(new DefaultMutableTreeNode("Dog")); animal.add(new DefaultMutableTreeNode("Fish")); DefaultMutableTreeNode vegetable = new DefaultMutableTreeNode("Vegetable"); everything.add(vegetable); vegetable.add(new DefaultMutableTreeNode("Onion")); vegetable.add(new DefaultMutableTreeNode("Lettuce")); vegetable.add(new DefaultMutableTreeNode("Carrot"));

DefaultMutableTreeNode fruits = new DefaultMutableTreeNode("Fruits");

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

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

Vidyala

nkar

Page 7: Adv Java. Soln - Vidyalankar Coaching Classesvidyalankar.org/file/bsc-it/Soln/Adv_Java_Soln.pdf · 1 T.Y. B.Sc. (IT) : Sem. V Advanced Java Time : 2½ Hrs.] Prelim Question Paper

Prelim Question Paper Solution

7

Q.2(c) Write a program to create a combobox, and add different items in thatcombobox by accepting them from user.

[5]

(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(); c.setLayout(new FlowLayout()); jc=new JComboBox(); jb=new JButton("Add"); jt=new JTextField(10); jb.addActionListener(this); c.add(jc); c.add(jt); c.add(jb); setSize(500,500); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public void actionPerformed(ActionEvent ae) { String s=jt.getText(); jc.addItem(s); } public static void main(String args[]) { combo cb=new combo(); } }

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[])

Vidyala

nkar

Page 8: Adv Java. Soln - Vidyalankar Coaching Classesvidyalankar.org/file/bsc-it/Soln/Adv_Java_Soln.pdf · 1 T.Y. B.Sc. (IT) : Sem. V Advanced Java Time : 2½ Hrs.] Prelim Question Paper

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

8

{ JTabbedPaneDemo d = new JTabbedPaneDemo(); JTabbedPane p = new JTabbedPane(); p.addTab("Cities", new CitiesPanel()); p.addTab("Colors", new ColorsPanel()); d.add(p); d.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); d.setSize(500,500); d.setVisible(true); } } class CitiesPanel extends JPanel { public CitiesPanel () { JButton b1 = new JButton("New York"); add(b1); } } class ColorsPanel extends JPanel { public ColorsPanel () { JButton b1 = new JButton("Blue"); add(b1); } }

Q.3 Attempt the following (any TWO) [10]Q.3(a) Explain RequestDispatcher with example. [5](A) RequestDispatcher

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

username :

password :

Login

Vidyala

nkar

Page 9: Adv Java. Soln - Vidyalankar Coaching Classesvidyalankar.org/file/bsc-it/Soln/Adv_Java_Soln.pdf · 1 T.Y. B.Sc. (IT) : Sem. V Advanced Java Time : 2½ Hrs.] Prelim Question Paper

Prelim Question Paper Solution

9

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"))) { RequestDispatcher rd1 = request.getrequestDispatchers ("Welcome"); rd1.include(request, response); } else { RequestDispatchers rd2 = request.getRequestDispatchers ("Errors"); rd2.forward(request, response); } out.close( ); } } Request Dispatchers 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 3) RequestDispatcher can be created for following 2 reasons. (a) To include the contains of RequestDispatcher into the current Servlet application

for that purpose we are using include( ); of RequestDispatcher. (b) To forward the control from current servlet application to any requestDispatcher

servlet. For that purpose we are using forward(); of RequestDistpacher.

Q.3(b) Explain the generic servlet and HTTP servlet. [5](A) Generic Servlet:

GenericServlet class is direct subclass of Servlet interface. Generic Servlet is protocol independent.It handles all types of protocol like http, smtp,

ftp etc. Generic Servlet only supports service() method.It handles only simple request . public void service(ServletRequest req,ServletResponse res ). A generic servlet should override its service() method to handle requests as appropriate

for the servlet. The service() method accepts two parameters: a request object and a response object.

The request object tells the servlet about the request, while the response object is used to return a response.

Vidyala

nkar

Page 10: Adv Java. Soln - Vidyalankar Coaching Classesvidyalankar.org/file/bsc-it/Soln/Adv_Java_Soln.pdf · 1 T.Y. B.Sc. (IT) : Sem. V Advanced Java Time : 2½ Hrs.] Prelim Question Paper

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

10

Generic Servlet only supports service() method.

Generic Servlet Request Handling

HttpServlet: HttpServlet class is the direct subclass of Generic Servlet. HttpServlet is protocol dependent. It handles only http protocol. HttpServlet supports public void service(ServletRequest req,ServletResponse res ) and

protected void service(HttpServletRequest req,HttpServletResponse res). HttpServlet supports also

doGet(),doPost(),doPut(),doDelete(),doHead(),doTrace(),doOptions() etc. An HTTP servlet usually does not override the service() method. Instead, it overrides

doGet() to handle GET requests and doPost() to handle POST requests. An HTTP servlet can override either or both of these methods, depending on the type

of requests it needs to handle. The service() method of HttpServlet handles the setup and dispatching to all the

doXXX() methods

HTTP servlet request handling

Q.3(c) Develop simple servlet question-answer application to demonstrate use of HttpServletRequest and HttpServletResponse interfaces.

[5]

(A) //index.jsp <html> <head> <title>Welcome To SSS's Quiz Contest</title> </head> <body> <h1 align="center">Welcome To SSS's Quiz Contest</h1> <form method="post" action="test"> <b>Who developes Java</b> <br> <input type="radio" name="java" value="d">Dennis Ritchie <input type="radio" name="java" value="b">Bjarne Straunstrup <input type="radio" name="java" value="j">James Goslin <br> <input type="submit" value="Submit"> </form> </body>

Vidyala

nkar

Page 11: Adv Java. Soln - Vidyalankar Coaching Classesvidyalankar.org/file/bsc-it/Soln/Adv_Java_Soln.pdf · 1 T.Y. B.Sc. (IT) : Sem. V Advanced Java Time : 2½ Hrs.] Prelim Question Paper

Prelim Question Paper Solution

11

</html>

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

public class test extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { String answer=request.getParameter("java"); if((answer.equals("d"))||(answer.equals("b"))) { out.println("Wrong Answer"); } else { out.println("Correct Answer"); } } finally { out.close(); } } }

Q.3(d) Develop servlet application of basic calculator (+, , *, /) using HttpServletRequest and HttpServletResponse.

[5]

(A) //index.jsp <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </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>

Vidyala

nkar

Page 12: Adv Java. Soln - Vidyalankar Coaching Classesvidyalankar.org/file/bsc-it/Soln/Adv_Java_Soln.pdf · 1 T.Y. B.Sc. (IT) : Sem. V Advanced Java Time : 2½ Hrs.] Prelim Question Paper

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

12

<input type="submit" value="Calculate"> </form> </body> </html> //calculate.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class calculate extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); 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; } else if(op.equals("-")) { c=a-b; } else if(op.equals("*")) { c=a*b; } else { c=a/b; } out.println("The Result is "+c); } finally { out.close(); } } }

Q.4 Attempt the following (any TWO) [10]Q.4(a) Write a program using Prepared Statement to add record in student table

containing roll number and name. [5]

(A) import java.sql.*; public class Main { public static void main(String[] args) { try

Vidyala

nkar

Page 13: Adv Java. Soln - Vidyalankar Coaching Classesvidyalankar.org/file/bsc-it/Soln/Adv_Java_Soln.pdf · 1 T.Y. B.Sc. (IT) : Sem. V Advanced Java Time : 2½ Hrs.] Prelim Question Paper

Prelim Question Paper Solution

13

{ 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"); } }

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

Description

\ ' A single quote in attribute that uses single quotes. \ '' A double quote in an attribute that uses double quotes. \ \ A backslash in an attribute that uses backslash.

% \ > Escaping the scripting end tag with a backslash. < \ % Escaping the scripting start tag with a backslash. \ $ Escaping the dollar sign [dollar sign is used to start an EL expression] with a

backslash Example

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

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

Vidyala

nkar

Page 14: Adv Java. Soln - Vidyalankar Coaching Classesvidyalankar.org/file/bsc-it/Soln/Adv_Java_Soln.pdf · 1 T.Y. B.Sc. (IT) : Sem. V Advanced Java Time : 2½ Hrs.] Prelim Question Paper

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

14

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

Type 1 : (JDBC ODBC Bridge Driver) Advantage : (i) Free of cost (ii) Easy to implement

Disadvantage : (i) Slow (ii) Only can be used with Microsoft DataBase. Type 2 : (Native API) Advantage : Faster than T1

Disadvantage : Native API Burdens the work. Type 3 : (Network Protocol) Advantage : Security/Most Secured

Disadvantage : It is slower than T2 and T4. Type 4 : (DataBase Protocol) Advantage : Fastest among all Disadvantage : Costliest

Q.4(d) Explain life cycle of JSP. [5](A) LIFECYCLE OF JSP

1) Instantiation : When a web container receives a JSP request, it checks for the JSP’s servlet instance. If no servlet instance is available then the web container creates the servlet instance using following steps. (a) Translation :

Web container translates (converts) the JSP code into a servlet code. After this stage there is no JSP everything is a servlet. The resultant is a java class instead of an html page (JSP page)

JDBC Appl.

T1

ODBC

Drivers DB

JDBC calls

ODBC calls

DB specific calls

JDBC Appl.

T2

DB

JDBC calls

DB specific calls

Native API

JDBC Appl.

T3

MS DB

JDBC calls

Middleware server specific calls

DB specific calls

JDBC Appl.

T4

DB

JDBC calls

DB specific calls

Native API Vidyala

nkar

Page 15: Adv Java. Soln - Vidyalankar Coaching Classesvidyalankar.org/file/bsc-it/Soln/Adv_Java_Soln.pdf · 1 T.Y. B.Sc. (IT) : Sem. V Advanced Java Time : 2½ Hrs.] Prelim Question Paper

Prelim Question Paper Solution

15

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

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

request.

(e) Initialization : 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. 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

request processing. Q.5 Attempt the following (any TWO) [10]Q.5(a) Explain JSF life cycle. [5](A) JSF life cycle

Request If not

initialized

Response

Translation Compilation Loading

Initialization Instantiation

Request Processing

Destruction

Already Initialized

Client

Restore view

Apply request values

Process event

Process Validation

Process event

Response complete

Response complete

Render response

Response complete

Faces response

Invotie application

Process Event

Update model values

Faces response

Reader response

Response complete

Process Event

Conversion error/render

Validation error /response

Vidyala

nkar

Page 16: Adv Java. Soln - Vidyalankar Coaching Classesvidyalankar.org/file/bsc-it/Soln/Adv_Java_Soln.pdf · 1 T.Y. B.Sc. (IT) : Sem. V Advanced Java Time : 2½ Hrs.] Prelim Question Paper

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

16

JSP lifecycle consist of following phases 1. Restore view :

i) In this face the appropriate view are created for a particular request and will get sotre in “Facescontext” object.

ii) Also different component will get retrieve from webserver and component tree can be generated.

2. Apply request values i) In this the local values of the components will get changed with the request value

i.e. request will get apply on component tree. ii) If any error occur then the error message will get store inside “Facescontext”

object. 3. Process validation

i) In this the local values of the component will get checked with the validation rule registered for a components.

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

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

In this phase the generated responses will get render i.e. provided to a client as a response.

Q.5(b) Explain advantages of EJB. [5](A) Advantages of EJB Apart from platform independent, EJB has following advantages.

More focus on business logic : In industry because of use EJB the development time of on application can be reduce, so that the organization can able to more focus on business logic.

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.

Distributed deployment: EJB’s can be used in distributed architecture where the EJB’s can get store in multiple system in distributed manner.

Interoperability : EJB’s can be used by multiple types of request, because the EJB has concept of CORBA (common object request brother architecture) which converts different type of request into common format.

Q.5(c) Explain different ways of accessing EJB’s [5](A) EJB’s can be used or accessed in following 2 ways :

(a) No Interface View In this case, there is no any interface or software which can be used to access a

particular bean. For accessing a bean, we can call public method of a Bean using which a Bean can be

used.

Vidyala

nkar

Page 17: Adv Java. Soln - Vidyalankar Coaching Classesvidyalankar.org/file/bsc-it/Soln/Adv_Java_Soln.pdf · 1 T.Y. B.Sc. (IT) : Sem. V Advanced Java Time : 2½ Hrs.] Prelim Question Paper

Prelim Question Paper Solution

17

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

Q.5(d) Write a program using JSF to find square root of a number. [5](A) //index.xhtml

<?xml version='1.0' encoding='UTF-8' ?> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html"> <h:head> <title>Facelet Title</title> </h:head> <h:body> <h:form> <h:outputLabel for="txtName"> <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> //userbean.java import javax.faces.bean.*; @ManagedBean(name="user") public class userbean { int number; double root; public int getnumber() { return number; } public void setnumber(int a) { number=a; } public double getroot() { return root; } public void setroot(double b) { root=b; } public String calculate() { root=Math.sqrt(number); return "success"; } }

Vidyala

nkar

Page 18: Adv Java. Soln - Vidyalankar Coaching Classesvidyalankar.org/file/bsc-it/Soln/Adv_Java_Soln.pdf · 1 T.Y. B.Sc. (IT) : Sem. V Advanced Java Time : 2½ Hrs.] Prelim Question Paper

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

18

//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' ?> <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> <h:form> <h:outputText value="Square root is= #{user.root} "> </h:outputText> </h:form> </h:body> </html>

Q.6 Attempt the following (any TWO) [10]Q.6(a) Explain MVC architecture. [5](A) MVC architecture

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

Event

Controller

View

Model Vidyala

nkar

Page 19: Adv Java. Soln - Vidyalankar Coaching Classesvidyalankar.org/file/bsc-it/Soln/Adv_Java_Soln.pdf · 1 T.Y. B.Sc. (IT) : Sem. V Advanced Java Time : 2½ Hrs.] Prelim Question Paper

Prelim Question Paper Solution

19

4. Working i) Whenever on event will occur for the use of MVC architecture, the event or the

request has been accepted by controller. ii) Controller forward that request to model component, where model component retrieves

the appropriate date use for handling the data and send that data to controller. Controller forwards that data to view which will create multiple views from that data. Sometimes the data accepted by view is not sufficient to create the multiple views in that case view can directly interact with model for getting that additional data.

Q.6(b) Explain any 3 core components of struts framework. [5](A) Core Components of struts Framework

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

struts are resemble with MVC architecture. i) Filter dispatcher will behave like controller ii) Action will work as Model iii) Result and Result type will work as a view Struts framework contain following core component

i) Filter dispatcher: It behave like controller which is use to accept request from the client. Once it accept the request it will search an appropriate action component to

forward the request. For selecting a particular action component, “Struts.xml” helps Filterdispatcher. Once it identifies apprompriate action, Filterdispatcher invoke the action by sending

the request. ii) Action: Action will behave like model and hence it has the appropriate dta use to

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

(A) <?xml version=”1.0” encoding=”UTF8”?>

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

</sessionfactory> </hibernateconfiguration>

Filter dispatcher

Action

http request

Invokereturn

Result

dispatchers

Struts Xml Client

Interception

Reads configurator

Vidyala

nkar

Page 20: Adv Java. Soln - Vidyalankar Coaching Classesvidyalankar.org/file/bsc-it/Soln/Adv_Java_Soln.pdf · 1 T.Y. B.Sc. (IT) : Sem. V Advanced Java Time : 2½ Hrs.] Prelim Question Paper

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

20

Elements: hibernate.dialect It represents the name of the SQL dialect for the database

hibernate.connection.driver_class It represents the JDBC driver class for the specific database

hibernate.connection.url It represents the JDBC connection to the database

hibernate.connection.username It represents the user name which is used to connect to the database

hibernate.connection.password It represents the password which is used to connect to the database

guestbook.hbm.xml It represents the name of mapping file

Q.6(d) Explain hibernate architecture in detail. [5](A) (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.

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

Fig. 1

Vidyala

nkar

Page 21: Adv Java. Soln - Vidyalankar Coaching Classesvidyalankar.org/file/bsc-it/Soln/Adv_Java_Soln.pdf · 1 T.Y. B.Sc. (IT) : Sem. V Advanced Java Time : 2½ Hrs.] Prelim Question Paper

Prelim Question Paper Solution

21

(v) Query : (i) If we want to perform operations on database using SQL or hQl queries, then in

that case session object create query object.

(vi) Criteria : If we want to perform operations on database using java methods then in that case session create criteria object.

Q.7 Attempt the following (any THREE) [15]Q.7(a) What are the different types of layout in Java? Explain GridLayout. [5](A) 1. FlowLayout 2. BorderLayout 3. GridLayout

4. CardLayout 5. BoxLayout 6. GridBagLayout 7. Grid Layout Grid Layout A GridLayout object places components in a grid of cells. Each component takes all the available space within its cell, and each cell is exactly the same size. If the GridLayoutDemo window is resized, the GridLayout object changes the cell size so that the cells are as large as possible, given the space available to the container.

Layout Design

Sample Program or Code snippet import java.awt.*; import java.applet.*; . /* <applet code=”SimpleKey” width=300 height=300> </applet> */ public class gridLayoutDemo extends Applet { static final int n = 4; public void init() { setLayout (new GridLayout(n , n)); setFont (new Font(“SansSerif”, Font.BOLD, 24)); for(int i=0; i<n; i++) { for(j=0; j<n; j++) { int k =i*n+j; if (k > 0) add(new Button (“ ”+ k)); } } } }

Vidyala

nkar

Page 22: Adv Java. Soln - Vidyalankar Coaching Classesvidyalankar.org/file/bsc-it/Soln/Adv_Java_Soln.pdf · 1 T.Y. B.Sc. (IT) : Sem. V Advanced Java Time : 2½ Hrs.] Prelim Question Paper

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

22

Q.7(b) Write a program to create a split pane in which left side of split Pane contains a list of planet and when user clicks on any planet name, its image should getdisplayed an right side.

[5]

(A) import javax.swing.*; import java.awt.*; import javax.swing.event.*; class list extends JFrame implements ListSelectionListener { JSplitPane jsp; ImageIcon i1,i2,i3; JList jl; JLabel j; list() { Container c=getContentPane(); c.setLayout(new FlowLayout()); String s[]={"earth","mercury","saturn"}; jl=new JList(s); jl.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); 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); jsp.setLeftComponent(jl); jsp.setRightComponent(j);

jl.addListSelectionListener(this); c.add(jsp); setSize(500,500); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } 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 {

Vidyala

nkar

Page 23: Adv Java. Soln - Vidyalankar Coaching Classesvidyalankar.org/file/bsc-it/Soln/Adv_Java_Soln.pdf · 1 T.Y. B.Sc. (IT) : Sem. V Advanced Java Time : 2½ Hrs.] Prelim Question Paper

Prelim Question Paper Solution

23

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)

(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

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

(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. (iv) Although this architecture minimize performance delay it has following

disadvantage. (v) Disadvantage

(i) Single point failure can occure if the webserver get failed. (ii) This architecture does not use to provide dynamic response.

(vi) Disadvantage CGI process are platform dependent process because they are implemented in C,

C++ pearl. It increase the overhead of webserver because every time a new process get

loaded & unloaded from web server. It is very difficult to implement CGI programming.

Lack of scalablity if the number of client will get increase. Lack of security. It uses lots of webserver resources. Only one resource can be used at a time i.e. lack of resource sharing.

Client CGI web

Server

DB Server

http reg.

http res

DB Server

Client web

Server

http reg

http res

Vidyala

nkar

Page 24: Adv Java. Soln - Vidyalankar Coaching Classesvidyalankar.org/file/bsc-it/Soln/Adv_Java_Soln.pdf · 1 T.Y. B.Sc. (IT) : Sem. V Advanced Java Time : 2½ Hrs.] Prelim Question Paper

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

24

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

</navigation-rule> The <navigation-rule> element represents an individual decision rule. This rule is accessed when the default Navigation Handler is implemented. This rule helps make decisions on what view to display next, based on the View ID being processed. The <from-view-id> Element <from-view-id> /index.xhtml </from-view-id> The <from-view-id> element contains the view identifier bound to the view for which the containing navigation rule is relevant. If no <from-view> element is specified, then this rule automatically applies to navigation decisions on all views. Since this element is not specified, a value of “*” is assumed, which means that this navigation rule applies to all views.

The <navigation-case> Element <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 that should be selected next.

The <from-outcome> Element <from-outcome> login </from-outcome> The <from-outcome> element contains a logical outcome string. This string is returned by the execution of an application action method via an actionRef property of a UICommand component. If this element is specified, then this rule is relevant only if the outcome value matches this element’s value. If this element is not specified, then this rule is relevant no matter what the outcome value was. The <to-view-id> Element <to-view-id> / Welcome.xhtml </to-view-id> The <to-view-id> element contains the view identifier of the next view that must be displayed when this navigation rule is matched. 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.

Vidyala

nkar

Page 25: Adv Java. Soln - Vidyalankar Coaching Classesvidyalankar.org/file/bsc-it/Soln/Adv_Java_Soln.pdf · 1 T.Y. B.Sc. (IT) : Sem. V Advanced Java Time : 2½ Hrs.] Prelim Question Paper

Prelim Question Paper Solution

25

Q.7(e) Explain different types of JSP tags. [5](A) JSP tags / JSP elements

JSP tags are normally use to embed java code inside the JSP page. Following are various type of JSP tags (A) Directive tag

It has three types (a) Page directive tag

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

(b) Include directive tag :

It is use to include the contents of one JSP application inside the current JSP application. e.g. <%@ include file = “abc.jsp” %>

(c) taglib directive tag :

Inside the JSP application, if we want to use some other tag apart from html & JSP then the tag server or the tag library can be be included using taglib directive tag. e.g.: <%@taglib uri = “www.w3.org”%>

(d) Declaration tag

It is use to declare a particular variable inside the JSP application. e.g. <%! int a = 2; %>

(e) Expression tag It is use to display the value of a particular variable or an expression on a web browser. e.g. <% = a%>

(c) Script let

It is use to write java code as it is inside the JSP page as it is written in java application. e.g. <%

___ ___ java code ___

>

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

Vidyala

nkar

Page 26: Adv Java. Soln - Vidyalankar Coaching Classesvidyalankar.org/file/bsc-it/Soln/Adv_Java_Soln.pdf · 1 T.Y. B.Sc. (IT) : Sem. V Advanced Java Time : 2½ Hrs.] Prelim Question Paper

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

26

Q.7(f) Explain structure of hibernate mapping file. [5](A) <?xml version=”1.0” encoding=”UTF8”?>

<hibernatemapping>

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

<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 length It represents maximum length of a column value

Vidy

alank

ar