12259-CO6E-Advanced_Java_Programming
12259-CO6E-Advanced_Java_Programming
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
__________________________________________________________________________________________________
SUMMER – 12 EXAMINATION
Subject Code : 12259 Model Answer Page No : 1-24
Q.1
a) To check how many fonts are available on the computer system GraphicsEnvironment class is
used. To use the methods obtained by this class, GraphicsEnvironment reference is required. This
reference can be obtained by using getLocalGraphics environment () static method which is defined
by graphicsEnvironment. It is given by static GraphicsEnvironment getLocalGraphicsEnvironment ()
Method : string [] getAvailableFontFamilyName ()
for eg.
import java.applet.*;
import java.awt.*;
/*<applet code = "showFonts" width = 500 height = 400></applet>*/
public class showFonts extends Applet
{
public void paint(Graphics g)
{
String msg = "";
String FontList[];
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
FontList = ge.getAvailableFontFamilyNames();
/*for(int i = 0; i< FontList.length; i++)
{
msg = FontList[i] +"";
g.drawString(msg, 4, i*10);
}*/
int l = FontList.length;
showStatus("Number of Fonts"+l);
}
}
b) Checkbox is a control that is used to turn an option on or off. It consists of a small box that can
either contain a check mark or not. There is a label associated with each check box. That describes
what option the box represents. To use the setLabel () method, the object of checkbox should be
created using any constructor.
For eg.
The method getState() determines it the checkbox is checked (true) or unchecked (false). The method
return true or false.
c) scrollpanes – it provides a scrollable view of a light weight component. Horizontal & or vertical
scroll bars may be provided if necessary.
Tree – tree is a component that presents a hierarchical view of data. A user can expand or collapse
individual subtrees in the display.
d) Servlets are small programs that execute on the serverside of a web connection. genericSevlets
exists to allow the handling of request using any protocol. -1
Difference between GenericServlet & Httpservlet (Any three points from the following -3 marks)
GenericServlet HttpServlet
Reserved sockets
A socket is one end point of a two way communication between two programs running of the
network . a port is the physical connection to the network. When an object of socket is created it
requires a port number. Once connected , a higher level protocol ensures , which is dependent on
which port is being used. TCP/IP reserves the lower 1024 ports for specific protocols. These are
known as reserved sockets. Some of the reserved sockets are as follows:
DNS (Domain Naming services) – It is service internet uses to convert alphanumeric names such as
google.com ( or any other) to 32 bit binary IPV4 or 128-bit IPV6 address.
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
__________________________________________________________________________________________________
SUMMER – 12 EXAMINATION
Subject Code : 12259 Model Answer Page No : 3-24
i) getConnection () – this method from JDBC is the means of establishing a connection between
Url & database. When this method is calleds. the DriveManager searches a suitable driver
from the ones loaded at initialization. For eg:
Connection con;
Con= DriveManager.getConnection();
ii) createdStatement(): once a connection is obtained , user can interact with the data
database.theStatement interface defines methods that enable user to send SQL queries &
receive data from the database.
For eg.
Connection con;
Statement st;
St = con. createStatement();
Q2
a) Frame is a subclass of windows & has a title bar, menu bar, border & resizing corners.
i) import java.awt.*;
import java.awt.event.*;
frame.setSize(400,400);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
}
}
ii)
import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
CloseFrame(String title)
{
super(title);
addWindowListener(new MyWindowAdapter(this));
this.setSize(300,300);
this.setVisible(true);
}
class MyWindowAdapter extends WindowAdapter{
b)
import javax.swing.*;
/*<applet code = exam.class height = 300 width = 300></applet>*/
jcb.addItem("Font");
jcb.addItem("Font Style");
jcb.addItem("Font Size");
add(jcb);
}
}
It uses native c language library calls to translate JDBC calls to native client Library, it is
two tier architecture.
3. Native protocol pure java driver or DBMS protocol all java driver- this allows a direct call
from client machine to DBMS server. It is two tier architecture.
4. JDBC net pure Java Driver or DBMS independent network protocol Driver-JDBC calls
are translated by this Driver into a DBMS independent protocol & sent to a middle tier
code can contact a variety of data bases on behalf of the client. It is a three tier
architecture.
d)
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
Q 3 A)
i)
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class calc extends Applet implements ActionListener
{
TextField test1, test2, test3,test4;
Label l1,l2;
Button b1;
public void init()
{
test1=new TextField(8);
test2=new TextField(8);
test3=new TextField(8);
test4=new TextField(8);
l1= new Label("Enter marks of 3 subjects :");
l2=new Label("Average:");
b1= new Button("Find Average");
setLayout(new FlowLayout());
add(l1);
add(test1);
add(test2);
add(test3);
add(l2); add(test4);
add(b1);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
int t1,t2,t3;
float av;
t1= Integer.parseInt(test1.getText());
t2= Integer.parseInt(test2.getText());
t3= Integer.parseInt(test3.getText());
av=((t1+t2+t3)/3);
test4.setText(Float.toString(av));
}
}
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
__________________________________________________________________________________________________
SUMMER – 12 EXAMINATION
Subject Code : 12259 Model Answer Page No : 8-24
All these methods throw unknownHostException if they are unable to resolve the hostname.
Q4 b) 01 mark each
Ans :
A Resultset object maintain a cursor pointing to its current row of data. For navigating
through database records following methods of Resultset object can be used.
Comidering „rs‟ as the Resultset object .
i) rs.first () – moves the cursor to the first row in the Resultset object.
ii) rs.last() – moves the cursor to the last row in the Resultset object.
iii) rs.next () – moves the cursor down one row from its current position.
iv) rs.previous () – moves the cursor to the previous row in the Resultset object.
Q4 c) Illustrate the use of accept() and close() methods of serversocket with suitable example.
Ans: ServerSocket class is used to create server socket for listening to client request.
Methods:
i) Socket accepts () – it makes server socket to listen the client connection & accept it.
Q4 d)
Ans: A Tree is a component that presents a hierarchical view of the data. It can be expanded or
collapsed in its individual subtrees. Trees are implemented in Swing by JTree class. The
DefaultMutableTreeNode class represents a node in the tree. One of its constructors is as below:
DefaultMutableTreeNode(Object obj) where obj is the object to be enclosed in the tree node.
To create hierarchy of tree nodes, add() method of DefaultMutableTreeNode can be used. Its syntax
is void add(DefaultMutableTreeNode childobj) 02 marks
Example 02 marks(any other example can be considered)
Example :
import javax.swing.*;
import javax.swing.tree.*;
import java.awt.*;
This class of java.net enables to implement streams to read & write the contents of
URL.
It is a super class & represents the link between URL & Application over the n/w. you
can use URL Connection to inspect the properties of the remote object.
import java.io.*;
class url8_5
URLConnection u2=u1.openConnection();
String ct=u2.getContentType();
System.out.println("Content type:"+ct);
InputStream ip=u2.getInputStream();
int c;
while((c=ip.read())!=-1)
System.out.print((char)c);
import java.io.*;
class urltest1
String s1 = ul.getProtocol();
String s2 = ul.getFile();
String s3 = ul.getHost();
int n=ul.getPort();
}
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
__________________________________________________________________________________________________
SUMMER – 12 EXAMINATION
Subject Code : 12259 Model Answer Page No : 15-24
1. URL Rewriting :
With URL rewriting ,you append a taken or identifier to the URL of the next servlet.
You can send parameter name/value pairs using following format:
When the user clicks the hyperlinks, the parameter name/value pairs will be passed to
the server.
From a servlet, you can use Https servletRequest interfaces getparameter method to
obtain a parameter value.
request.getparameter(name1);
2. Hidden Fields:
Another technique for managing user sessions is by passing a taken as the value for an
HTML hidden field you can read the value viewing the HTML source code.
3. Cookies:
A cookie is stored on client & contains stale information.
Cookies are valuable for tracking , user sessions. A cookie can store users name,
address & other information.
Servlet can add information in the form of cookie with addcookie() method of
HttpServletResponse interface. This data get included in the header of httpResponse
that is send to the browser. The names & values of cookies are stored on client
machine.
4. Session Objects:
A session can be created with the help of getsession () method of HTTPServletRequest. It
returns HttpSession object.
A session stale is shared among all the servlet that are associated with a particular
client.
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
__________________________________________________________________________________________________
SUMMER – 12 EXAMINATION
Subject Code : 12259 Model Answer Page No : 16-24
Httpsession object can be used to store & retrieve information about the user who is
visiting the site.
An Httpsession object uses a cookie or URL rewriting to send a token to the client. If
cookies are used to convey session identifiers, the client browser are required to accept
cookies.
The session identifier is used to associate a user with a session object in the server.
Any four techniques for each technique 1 marks
iv) Servlet Life cycle:
Three methods are central to the life cycle of a servlet . these are :
1. Init()
2. Service()
3. Destroy()
They are implemented by every servlet & are invoked at specific times by server.
First assume that a user enters a URL to a web browser. The browser then generates an
HTTP request for this URL. This request is then sent to the appropriate server.
This Http request is received by the web server. The server maps this request to a
particular servlet. The servlet is dynamically retrieved & loaded into the address space of
the server.
The server invokes init() method of the sorvlet . this method is invoked is invoked
only when the servlet is first loaded into memory. Using init() method , the
initialiazation parameter can be pass to the servlet to configure itself.
Then, the server invokes the service() method of the servlet . this method is called to
process the Http request. It may also formulate an Http response for the client.
The server remains in the servers address space & is available to process any other
Http request received from clients.
When server decides to unload servlet from its memory, it calls destroy() method . it
relinquish any resource such as file handles that are allocated for the servlet.
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
__________________________________________________________________________________________________
SUMMER – 12 EXAMINATION
Subject Code: 12259 Model Answer Page No : 17-24
Cookies are valuable for tracking , user sessions. A cookie can store users name,
address & other information.
Information of each cookie includes name, value, expiration date, path, domain etc.
When a browser stores your passwords & users ID‟s they are also used to store
preferences of start pages.
An online ordering system could be developed using cookies that would remember
what a person wants to busy.
(03 marks)
import javax.servlet.*;
import javax.servlet.http.*;
PrintWriter pr;
pr=res.getWriter();
res.setContentType("text/html");
Cookie[] c=req.getCookies();
(03 marks)
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
__________________________________________________________________________________________________
SUMMER – 12 EXAMINATION
Subject Code : 12259 Model Answer Page No : 18-24
{
for(int i=0;i<c.length;i++)
Cookie c3=c[i];
String nm=c3.getName();
String vl=c3.getValue();
pr.println("<big>"+nm+"="+vl);
else
<html>
<body>
<form method=”post” action=http://localhost:8080/examples/servlet/exp17_1>
Enter Username:<br>
<input type=”text” name=”username”><br>
Enter password:<br>
<input type=”password” name=”pswd”><br>
<br>
<input type =”submit” value=”submit”>
</form></body>
</html>
(any other valid example can be considered)
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
__________________________________________________________________________________________________
SUMMER – 12 EXAMINATION
Subject Code : 12259 Model Answer Page No : 19-24
The executeUpdate () method of the statement object enables you to execute SQl
update statement such as delete, insert & update.
The method takes a string containing the SQL update statement & returns an integer
that determine how many records were affected by SQL statement.
For update , insert & delete the records first establish connection , between application
& database.
After establishing connection , create the object of statement interface & call the
createStatement() method using object of connection interface.
After creating statement object , the SQL statement can be used for insert, delete &
updare the records.
For execute the above statement, executeUpdate() method can be used as:
st.executeUpdate(s1);
st.executeUpdate(s2);
St.executeUpdate(s3);
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
__________________________________________________________________________________________________
SUMMER – 12 EXAMINATION
Subject Code : 12259 Model Answer Page No : 20-24
Q.6 a)
import java.sql.*;
public class test2
{
public static void main(String[] args)
{
Connection con;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("connection has been successfully established");
}
catch (Exception e)
{
}
try
{
String str="jdbc:odbc:Mobile";
con=DriverManager.getConnection(str," "," ");
Statement st=con.createStatement();
st.executeUpdate("insert into t1 values('ABC',2356,2390,'50MB')");
st.executeUpdate("insert into t1 values('TATA',2556,3390,'2GB')");
st.executeUpdate("insert into t1 values('ABC',2356,1390,'90MB')");
st.executeUpdate("insert into t1 values('Nokia',1356,12390,'1GB')");
st.executeUpdate("insert into t1 values('ABC',2350,23900,'3GB')");
ResultSet rs=st.executeQuery("select * from t1 where company like 'ABC'");
System.out.println("Mobiles belongs to ABC Company");
int n=rs.getMetaData().getColumnCount();
for(int i=1;i<=n;i++)
{
System.out.print(rs.getMetaData().getColumnLabel(i)+'\t');
}
System.out.println();
while(rs.next())
{
for(int i=1;i<=n;i++)
{
System.out.print(rs.getString(i)+'\t');
}
System.out.println();
}
System.out.println();
ResultSet rs1=st.executeQuery("select * from t1 order by cost");
System.out.println("Records in ascending order");
int n1=rs1.getMetaData().getColumnCount();
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
__________________________________________________________________________________________________
SUMMER – 12 EXAMINATION
Subject Code : 12259 Model Answer Page No : 21-24
for(int i=1;i<=n1;i++)
{
System.out.print(rs1.getMetaData().getColumnLabel(i)+'\t');
System.out.println();
while(rs1.next())
{
for(int i=1;i<=n1;i++)
{
System.out.print(rs1.getString(i)+'\t');
}
System.out.println();
}
con.close();
}
catch (SQLException e)
{
System.out.println(e);
}
}
}
Q 6 b)
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class testapp extends JApplet implements ItemListener
{
String msg=" ";
JComboBox jc;
JList jl;
JLabel jb;
String country[]={"India","Australia","USA","SriLanka","Pakistan"};
String capital[]={"Delhi","Perth","NewYork","Columbo","Karachi"};
public void init()
{
//Container cnt=getContentPane();
setLayout(new FlowLayout());
jb=new JLabel("test");
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
__________________________________________________________________________________________________
SUMMER – 12 EXAMINATION
Subject Code : 12259 Model Answer Page No : 22-24
jc=new JComboBox(country);
jl=new JList(capital);
add(jc);
add(jl);
add(jb);
jc.addItemListener(this);
}
Q.6 c) 04 marks
i) httppost.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class httppost extends HttpServlet
{
public void doPost(HttpServletRequest req,HttpServletResponse res)throws
IOException,ServletException
{
PrintWriter pr;
pr=res.getWriter();
res.setContentType("text/html");
String username=req.getParameter("username");
String password=req.getParameter("password");
pr.println("<b> Username : "+username+"<br>");
pr.println("Password :" +password);
pr.close();
}
}
Post.html
<html>
<head></head>
<body>
<form method="post" action="http://localhost:8080/examples/servlet/httppost">
Enter Username : <br>
<input type="text" name="username"><br>
Enter Password : <br>
<input type="password" name="password"><br>
<br>
<input type="submit" value="Submit">
</form>
</body>
</html>
ii) 04 marks
httpget.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class httpget extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)throws
IOException,ServletException
{
PrintWriter pr;
pr=res.getWriter();
res.setContentType("text/html");
String username=req.getParameter("username");
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
__________________________________________________________________________________________________
SUMMER – 12 EXAMINATION
Subject Code : 12259 Model Answer Page No : 24-24
String password=req.getParameter("password");
pr.println("<b> Username : "+username+"<br>");
pr.println("Password :" +password);
pr.close();
}
}
get.html
<html>
<head></head>
<body>
<form method="get" action="http://localhost:8080/examples/servlet/httpget">
Enter Username : <br>
<input type="text" name="username"><br>
Enter Password : <br>
<input type="password" name="password"><br>
<br>
<input type="submit" value="Submit">
</form>
</body>
</html>