Upload
others
View
11
Download
0
Embed Size (px)
Citation preview
1014/BSc/IT/TY/Pre_Pap/2014/Adv. Java 1
T.Y. B.Sc. (IT) : Sem. V Advanced Java
Time : 2½ Hrs.] Prelim Question Paper [Marks : 75
Q.1 Attempt the following (any TWO) [10]Q.1(a) Explain Checkbox with example. [5](A) Checkbox [2 mark]
1) Checkbox is a class which is used to create Checkbox in awt. 2) It’s constructors are : Checkbox( ); Checkbox (string s); Checkbox (string s, Boolean state); Checkbox (string s, Boolean state, Checkbox Group (b)); Here Checkbox Group is a class which is used to convert a checkbox into a radio button. Checkbox Group has following two methods : 1) get Selected Checkbox ( ); It is used to retrieve a selected Checkbox. 2) Set Selected Checkbox (Checkbox c); It is used to select an appropriate Checkbox. Methods of Checkbox : i) getLabel( ); It is used to retrieve name of the Checkbox.
ii) setLael(string s); It is used to set a new name on a Checkbox.
iii) getState( ); It is used to retrieve state of the Checkbox.
iv) setState(Boolean State); It is used to set a new state to a Checkbox.
Write a program to create a following window which consist of five Checkboxes, by clicking them the appropriate message should get changed. [3 mark]
Vidy
alank
ar Group (bup (
sed to convert a to convert
thods : ds :
cted Checkbox. d Checkbo Checkbox c); eckbox c);
n appropriate Checpropriate C
ox : ox :
to retrieve name to retrieve name
el(string s); el(string s); ed to set a ned to se
Vidyalankar : T.Y. B.Sc. (IT) – Adv. Java
2
import java.applet.*; import java.awt.event.*; import.java.awt.*; /* <applet code = test width = 200 height = 30> < /applet>/ public class test extends Applet implements ItemListener { Checkbox c1, c2, c3, c4, c5, public void init( ) { setLayout (new FlowLayout( )); c1 = new Checkbox (“Java”); c2 = new Checkbox (“Linux”); c3 = new Checkbox (“ASP”); c4 = new Checkbox (“ST”); c5 = new Checkbox (”NS”);
c1.addItem Listener (this); c2.addItem Listener (this); c3.addItem Listener (this); c4.addItem Listener (this); c5.addItem Listener (this);
add(c1); add(c2); add(c3); add(c4); add(c5); }
public void paint (Graphics g)
Java Linux ASP
ST NS Current Selection : Java : True Linux : False ASP : False ST : False NS : False
Vidy
alank
ar>
nts ts
c5,
new FlowLayout( )) FlowLayou Checkbox (“Java” Checkbox (“Ja
new Checkbox (“Lin Checkbox = new Checkbox ( = new Checkbox
c4 = new Checkbo = new Chec c5 = new Check c5 = new Ch
addIted
Prelim Paper Solution
3
{ string a = “Current Selection”; string b = “Java” + c1.getState( ); string c = “Linux” + c2.getState( ); string d = “ASP” + c3.getState( ); string e = “ST” + c4.getState( ); string f = “NS” + c5.getState( );
g.drawString (a, 10, 120); g.drawString (b, 10, 130); g.drawString (c, 10, 140); g.drawString (d, 10, 150); g.drawString (e, 10, 160); g.drawString (f, 10, 170); } public void itemStateChanged (Itemevent ie); { repaint( ); } }
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 : [4 mark] 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);
Vidy
alank
arevent ie); nt ie);
model. del. el
del consist of follodel consist of ft :
ion : Event is also : Event is aent is de3fined ent is de3fin particular sticul
an b
Vidyalankar : T.Y. B.Sc. (IT) – Adv. Java
4
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 [1 mark] 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 [4 mark]
Example : import java.awt.*; import java.awt.event.*; class testevent extends frame implements ActionListener { testevent( ) { 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);
Vidy
alank
are ev
eive that th
vent only when it i vent only when
ss.
*;
extends frame im extends frame tener ener
ent( ) nt( )
t (
Prelim Paper Solution
5
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( ); } }
Vidy
alank
ar
Green”)) en ))
ground (c2); round (c2);
setBackgroundsetBackgro } }
emo e
Vidyalankar : T.Y. B.Sc. (IT) – Adv. Java
6
Inner Class [1 mark] 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 [3 mark]
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); }
Vidy
alank
ar
FlowLayout( )); wLayout( )) Label (“select a coel (“select
b1 = new Button (“ 1 = new Buttoon b2 = new Buttoon b2 = new But
utton b3 = new Button b3 = new Bu
b1.addActionLb1.addA2.addAct
dA
Prelim Paper Solution
7
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); } 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 [2 mark] 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.
Vidy
alank
ar c3);
ndowClosing (WindClosing (W
tem.exit (0); tem.exit (0)
bic Static void c Static
ev
Vidyalankar : T.Y. B.Sc. (IT) – Adv. Java
8
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
Q.2(b) Explain JOptionPane in detail. [5](A) JOptionPane
1) It is use to create Option Pane or pop-up messages in case of swing. [1 mark]
2) It provides different static methods which are use to display different pop-ups. [4 mark] (a) ShowMessageDialog (Parent Window Object, String message) It is used to create a simple popup message with "OK" button.
V are Vidy
ala components Themponents Talank
ar Swing Compong Com
Swing Swing Comkaa Swing componeSwing compcomponents componenkaanendent endent They arThey
componcomananalaaally rectangular ily rectangularyae considered as considered as
omponents omponents idyare not used re not erations tionViV
Prelim Paper Solution
9
(b) ShowConfirmDialog(String message); It is used to display a confirmation message with 3 buttons "YES",
"NO" and "CANCEL". (c) ShowInputDialog(String message);
It is used to display a pop-up which is used to accept an input from the users
Q.2(c) Write a program to create a combobox, and add different items in
that combobox 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());
OK
Message
Yes
Message
No Cancel
OK
Message
Cancel
Vidy
alank
are);
to display a pop-u display a pos s
program to create program to cobox by accepbox by
wt.*; eve
aaaa
yalan
k
yalan
k
yal
yalK
sage
lalalanlan
Vidyalankar : T.Y. B.Sc. (IT) – Adv. Java
10
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) Write a program to create a table and perform addition and removal
of rows by accepting row no, using 2 buttons "Add" and "Remove". [5]
(A) import java.awt.*; import javax.swing.*; import java.awt.event.*; import javax.swing.table.*; class table extends JFrame implements ActionListener { JScrollPane jsp; DefaultTableModel dt; JTable j; JButton jb1,jb2; table()
Vidy
alank
arLOSE); E);
e)
ng args[]) gs[])
);
program to create program to cr accepting row acceptin
wt.*; ng
Prelim Paper Solution
11
{ Container c=getContentPane(); c.setLayout(new BorderLayout()); jb1=new JButton("Add Row"); jb2=new JButton("Remove Row"); String data[][]={{"1","sss","dadar"},{"2","akn","sion"},{"3","sdw","thane"}}; String colheads[]={"Id","Name","Address"}; dt=new DefaultTableModel(data,colheads); j=new JTable(dt); jsp=new JScrollPane(j); jb1.addActionListener(this); jb2.addActionListener(this); c.add(jsp,BorderLayout.CENTER); c.add(jb1,BorderLayout.NORTH); c.add(jb2,BorderLayout.SOUTH); setSize(1000,500); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public void actionPerformed(ActionEvent ae) { String s=ae.getActionCommand(); if(s.equals("Add Row")) { String a=JOptionPane.showInputDialog("Enter row number"); int m=Integer.parseInt(a); String b=JOptionPane.showInputDialog("Enter Id"); String c=JOptionPane.showInputDialog("Enter Name"); String d=JOptionPane.showInputDialog("Enter Address"); String e[]={b,c,d}; dt.insertRow(m,e); } else { String f=JOptionPane.showInputDialog("Enter row number to be deleted");
Vidy
alank
arH); H);
ation(JFrame.EXITJFrame.E
onPerformed(ActionPerformed(Ac
ae.getActionCommaae.getActionC
dd Row")
Vidyalankar : T.Y. B.Sc. (IT) – Adv. Java
12
int n=Integer.parseInt(f); dt.removeRow(n); } } public static void main(String args[]) { table t=new table(); } }
Q.3 Attempt the following (any TWO) [10]Q.3(a) Explain RequestDispatcher with example. [5](A) RequestDispatcher [ 2 mark]
<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.*; import java.io.*; public class test extends HttpServlet { public void doPost(HttpServletRequest Request, HttpServletResponse Response) throws IOException ServletException
username :
password :
Login
Vidy
alan
n </title> </head> title> </he
ost" action = "testt" action = "tb> b
"text" name = "u" text" name = "u" e = "password" name = "password = "submit" va = "subm
anka
r
ank
anka
rarkakakar
Login
anka
r
Prelim Paper Solution
13
{ 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 [2 mark] 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 session management with its techniques. [5](A) Session management techniques
1) Session Management is used by Servlet to store information about a particular client.
Vidy
alank
aruest.getRequest.getRequ
forward(request, rward(reques
pplication can be cication can b
ethod ethod equestDispatcher( questDispatcher(
stDispatchers is stDispatcherervlet ervlet
spatchede
Vidyalankar : T.Y. B.Sc. (IT) – Adv. Java
14
2) 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.
3) Apart from that Servlet also generate a Session ID to keep a trap for that session Memory.
4) Servlet Sends the SessionID to the client side. Application which will get stored inside the client machine.
5) Next time if the Same client wants to do the transaction with the same Servlet, then client will send request packet with session ID.
6) By retrieving the session ID, Servlet updates Session Memory for new transaction generater new SessionID & send it to the client.
7) To perform this mechanism following three techniques can be used. (a) Hidden formField :
It is used by the client to send a Session ID to the Servlet. It is in Hidden form & only Servlet can read it & Hence called as
Hidden form field. (b) Url rewriting :
It is used to send SessionID to the client. Servlet can put the SessionID inside response packet or it will
generate a special token to send a SessionID (c) Cookies :
By using cookie, a Servlet an send SessionID to the client machine.
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>
Roll No. :
Name :
Display
Vidy
alank
arsion ID to ID
et can read it & an read it
nID to the client. to the clie SessionID inside rsionID insi
token to send a Se oken to send
okie, a Servlet a a Servl
t purpose Servlet purpose Servds it to the client, ws it to the client
e, rogram to create rogram to cr
Name from Name licked
Prelim Paper Solution
15
<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( ); } }
Vidy
alank
art req, HttpServlet req, HttpSeret Exception Exception
xt/html"); html"); getWriter( ); etWriter( );
arseInt(req.getPaeInt(req.ge eq.getParameter("getParamet
The roll no. =" + roThe roll no. =" +n("<br>"); br>");
ntln("The name =" +ntln("The name ="pSession hs = req.ession hs = r
(hs.isNew( )) hs.isNew( ))
printl
Vidyalankar : T.Y. B.Sc. (IT) – Adv. Java
16
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> </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
Vidy
alank
arenn
">Bjarne Sarne="j">James Gosl>James G
mit"> t">
t.*; *; vlet.http.*; vlet.http.*;
test extends Httpst extends H
id doPost( doP
Prelim Paper Solution
17
{ 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> <input type="submit" value="Calculate"> </form> </body> </html> //calculate.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*;
Vidy
alank
ar content="text/htmtent="text/
action="calculate"> n="calculator</h1> h1>
Number</b> Number</b> e="number" name="="number" name
ter Second Numbter Second N type="number type="n
per
Vidyalankar : T.Y. B.Sc. (IT) – Adv. Java
18
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(); } } }
Vidy
alank
ar
"*")) )
a/b; /b;
n(
Prelim Paper Solution
19
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 { 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.
Vidy
alank
arn( j
ment("inset("i
println("Exceptionrintln("Excep
cter quong
Vidyalankar : T.Y. B.Sc. (IT) – Adv. Java
20
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
CharactersDescription
\ ' 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 ' and " can also be used.
Q.4(c) Explain transaction in JDBC. [5](A) c.setAutoCommit (false);
s.execut("insert into employ value ) s.execut("delete from employ ) s.executUpdate("update employ ) c.commit( ); ResultSet rs = s.executeQuery("select * from employee"); i) In case of JDBC the default value of commit protocol is true. ii) Which means all the transaction will get perform in the same order as
they are written in the JDBC application. iii) We can make the value of commit protocol as false with the help of
following method c.setAutoCommit (false); iv) It means all the transaction written after this will be kept hold and only
will get performed when we called the commit protocol. v) All the transaction because of this will execute simultaneously at a same
time.
Vidy
alank
are quote’; %> uote’; %> ouble quote’; %> ouble quote’; %
\ \ backslash’; %> backslash’; %ng % \ > scripting e % \ > script
aping < \ % scriptinng < \ % scr Escaping \$ dollar sscaping \$ dol
caping quote chaing quote also be used. be used.
ion in JDBC. in JDBC. mit (false); mit (false
nsert into employ nsert into empdelete from emdelete from
ate("updat("up
Prelim Paper Solution
21
vi) The major problem of using this transaction mechanism is that when 2 operations will get perform on the same record, sometime it will generate deadlock condition.
vii) To overcome this deadlock transaction mechanism uses rollback concept. viii)Because of rollback all the transaction will get undone and the operation
will get nullified.
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) (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.
RequestIf not
initialized
Response
Translation Compilation Loading
Initialization Instantiation
Request Processing
Destruction
Already Initializ
Client Vidy
alank
ar
s) the JSP c he JSP
JSP everything is aSP everything ss instead of an ht nstead of a
et is compiled to v s compiled t enerate class file nerate class
ed byte code is byte code
VidRequestues
ViVidyIf not If not
initializediniti
Viy
Vidy
VV
Vidyalankar : T.Y. B.Sc. (IT) – Adv. Java
22
(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
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.
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
Vidy
alank
ar
alan
alancess
event nn
e plete
VVe
e
yal
ResRespponse comonse co plete
dyVid
a
ViVid
Vidyrocess
VConvers
nka
Prelim Paper Solution
23
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 creted 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 sue in distributed architecture where the EJB’s can get store in multiple system in distributed manner.
Interoperability : EJB’s can be use 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.
Vidy
alank
arst o
lintsing of thostsing of t
ponses will get reses will get
.
independent, EJB endent, En business logic : business log
t time of on at time of on tion can able to moon can able to mo
ble Components : Eble Componend in another we in anot
componeb
Vidyalankar : T.Y. B.Sc. (IT) – Adv. Java
24
Q.5(c) Explain different types of EJB’S. [5](A) (i) Session bins
Session bins 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.
Vidy
alank
are int
s use to store use to storent & server for & server
ore the informatioe the inform bean are slower. bean are slowe
n bean an e bean which is an which
n between the clie between the hich they can Becahich they can Be
ngleton Session bengleton Sessis bean are reqs bean a
ve
Prelim Paper Solution
25
Q.5(d) Write a program to create a login application using JSF with builtinvalidation.
[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" xmlns:f="http://java.sun.com/jsf/core"> <h:head> <title>Login</title> </h:head> <h:body> <h:form> <h1>The Login Form</h1> <h:outputLabel for="txtName"> <h:outputText value="Name" /> </h:outputLabel> <h:inputText id="txtName" value="#{user.name}"> <f:validateRegex pattern="[a-z]+"/> </h:inputText> <h:outputLabel for="txtPassword"> <h:outputText value="Password" /> </h:outputLabel> <h:inputSecret id="txtPassword" value ="#{user.password}"> <f:validateRegex pattern="(.{6,20})" /> </h:inputSecret> <h:commandButton value="Login" action="#{user.verifyUser}"/> </h:form> </h:body> </html> //userbean.java import javax.faces.bean.*; @ManagedBean(name="user") public class userbean
Vidy
alank
ar" value="#{user.na alue="#{use
rn="[a-z]+"/> n="[a-z]+"/>
l for="txtPassword="txtPasswext value="Passworxt value="Pass
utLabel> utLabel>
:inputSecret id=":inputSecret tvalidateRegex alidateR
putSecre
Vidyalankar : T.Y. B.Sc. (IT) – Adv. Java
26
{ String name; String password; public void setname(String n) { name = n; } public String getname() { return name; } public void setpassword(String p) { password = p; } public String getpassword() { return password; } public String verifyUser() { if(name.equals("admin") && password.equals("sssssss")) { return "success"; } else { return "failure"; } } }
Vidy
alank
arord() )
rd;
String verifyUser()ring verifyUser()
me.equals("adme.equals
ess
Prelim Paper Solution
27
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 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.
Event
Controller
View
Model
Vidy
alank
ar to create multiple create mult
S is to separat is to sep
C contains followinntains folloent a data or colle a data or
the component wh he componen the some applicat the some applic
sp p ntroller: This comntroller: This. Servlet Servlet
r
Vidyalankar : T.Y. B.Sc. (IT) – Adv. Java
28
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=”UTF 8”?>
<hibernate configuration> <session factory> <property name=”hibernate.dialect”> org.hibernate.dialect.MySQLDialect</property>
Filter dispatcher
Action
http request
Invokereturn
Result
dispatchers
Struts Xml Client
Interception
Reads configurator
Vidy
alank
ar architecchit
MVC architecturC architec ontroller ontroller
ork as a view as a view owing core componng core co
behave like contro behave like coent.
the request it w request forward the requeard the re
ing a particular g a particuspatcher. spatcher.
it identifies appr t identifies apprtion by sending thtion by sendition: Action on: Ac
priate dt
Prelim Paper Solution
29
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
Vidy
alank
ar the name of the name of
r_classass It repre It r
ion.urlion.url It represe It repr
onnection.usernamonnection.use he database e datab
on
Vidyalankar : T.Y. B.Sc. (IT) – Adv. Java
30
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.
Fig. 1
Vidy
alank
arte when persistent when persist
cation. n. nto following diff nto following
eration. tion.
s used to establish s used to estas following 2 files ollowing 2
ernate. propertieernate. propertinformation about ormation ab
) hibernate (f.g. ) hibernate (particular darticul
ration
Prelim Paper Solution
31
(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.
(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) Write a program to implement single arithmetic calculator using awt
components. [5]
(A) import java.awt.*; import java.applet.*; import java.awt.event.*; /*<applet code=e5 width=200 height=300> </applet>*/ public class e5 extends Applet implements ActionListener { Label l1,l2; Button b1,b2,b3,b4; TextField t1,t2,t3; public void init() { setLayout(new FlowLayout()); l1=new Label("Number 1"); l2=new Label("Number 2"); b1=new Button("Add"); b2=new Button("Sub"); b3=new Button("Mul"); b4=new Button("Div"); t1=new TextField(10); t2=new TextField(10); t3=new TextField(10);
b1.addActionListener(this); b2.addActionListener(this); b3.addActionListener(this); b4.addActionListener(this);
calcc
t=300> 00>
t implements Actio implements A
; )
(new FlowLayout((new FlowLayel("Number 1""Numb
NumbeAd
Vidyalankar : T.Y. B.Sc. (IT) – Adv. Java
32
add(l1); add(t1); add(l2); add(t2); add(b1); add(b2); add(b3); add(b4); add(t3); } public void actionPerformed(ActionEvent ae) { String s=ae.getActionCommand(); int n1=Integer.parseInt(t1.getText()); int n2=Integer.parseInt(t2.getText()); int n; if(s.equals("Add")) { n=n1+n2; } else if(s.equals("Sub")) { n=n1-n2; } else if(s.equals("Mul")) { n=n1*n2; } else { n=n1/n2; } Integer I=new Integer(n); String p=I.toString(); t3.setText(p); } }
Vidy
alank
ar
als("Mul")) s("Mul"))
Prelim Paper Solution
33
Q.7(b) Write a program to meate a split pane in which left side of splitRane contains a list of plants and when user clicks on any planetname, its image should get displayed 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); }
Vidy
alank
arturn"}; n"};
ectionModel.SINGonModel.S
rth.jpg"); pg"); ("mercury.png"); mercury.png")
on("saturn.jpg"); on("saturn.jpg")
bel(i1); bel(i1);
tPane(JS
Vidyalankar : T.Y. B.Sc. (IT) – Adv. Java
34
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 { 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.
Client CGI web
Server
DB Server
http reg.
http res Vidy
alank
ar
woring. Also wirteg. Also w
Vientnt
yidyVidhttp reg.http reg.
http reht
Prelim Paper Solution
35
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 use at a time i.e. lack of resource
sharing. Q.7(d) Write a program to demonstrate use of JMenuBar, JMenu and
JMenuItem class in swing. [5]
(A) import javax.swing.*; import java.awt.*; import java.awt.event.*; class notepad2 extends JFrame implements ActionListener
DB Server
Clientweb
Server
http reg
http res
Vidy
alank
ar in web se web
ract with client asract with clien
e minimize perf minimize
lure can occure if e can occureecture does not usere does not
e e rocess are platfocess are p
plemented in C, C++plemented in C, C+It increase the ov increase theprocess get loaprocess getIt is very di is ver
k of s
Vidyalankar : T.Y. B.Sc. (IT) – Adv. Java
36
{ JMenuBar jm; JMenu jm1,jm2; JMenuItem m1,m2,m3,m4,m5,m6;; JTextArea jta; JScrollPane jsp; notepad2() { Container c=getContentPane(); c.setLayout(new BorderLayout()); jm=new JMenuBar(); jm1=new JMenu("File"); jm2=new JMenu("Edit"); m1=new JMenuItem("New"); m2=new JMenuItem("Open"); m3=new JMenuItem("Save"); m4=new JMenuItem("Exit"); m5=new JMenuItem("Foreground"); m6=new JMenuItem("Background"); jm1.add(m1); jm1.add(m2); jm1.add(m3); jm1.add(m4); jm2.add(m5); jm2.add(m6); jm.add(jm1); jm.add(jm2); jta=new JTextArea(); jsp=new JScrollPane(jta); m1.addActionListener(this); m2.addActionListener(this); m3.addActionListener(this); m4.addActionListener(this); m5.addActionListener(this); m6.addActionListener(this);
Vidy
alank
arnd"); nd");
round"); d");
m6); m6);
Prelim Paper Solution
37
c.add(jm,BorderLayout.NORTH); c.add(jsp,BorderLayout.CENTER); setSize(500,500); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public void actionPerformed(ActionEvent ae) { String s=ae.getActionCommand(); if(s.equals("New")) { jta.setText(""); } else if(s.equals("Open")) { JFileChooser jf1=new JFileChooser(); jf1.showOpenDialog(null); } else if(s.equals("Save")) { JFileChooser jf2=new JFileChooser(); jf2.showSaveDialog(null); } else if(s.equals("Exit")) { dispose(); } else if(s.equals("Foreground")) { JColorChooser jc1=new JColorChooser(); Color c1=jc1.showDialog(null,"Select Foreground",null); jta.setForeground(c1); } else { JColorChooser jc2=new JColorChooser(); Color c2=jc2.showDialog(null,"Select Foreground",null); jta.setBackground(c2); }
Vidy
alank
ar;
JFileChooser(); eChooser(g(null); null);
als("Exit")) s("Exit"))
Fo
Vidyalankar : T.Y. B.Sc. (IT) – Adv. Java
38
} public static void main(String args[]) { notepad2 n=new notepad2(); }
} 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; %>
Vidy
alank
ar which can be opera which can be o
%> %> %>
ava”%> %> ype = “text/html”% = “text/h
ve tag : e tag : o include the con o include the
JSP application. SP application
clude file = “ablude file
ve
Prelim Paper Solution
39
(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 %>
Q.7(f) Explain structure of hibernate mapping file. [5](A) <?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>
Vidy
alank
are jsp page. A commp page. A c
ovide some additioe some add
%>
of hibernate mapf hibernate m1.0” encoding=”UT1.0” encoding=”U
mapping> apping>
ame=”guestboome=”gue
am
Vidyalankar : T.Y. B.Sc. (IT) – Adv. Java
40
Elements: <hibernate mapping>….......</hibernate 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 length It represents maximum length of a column value
Vidy
alank
ar map
column which we wamn which w
of the column e column aximum length of aum length