0% found this document useful (0 votes)
55 views24 pages

12259-CO6E-Advanced_Java_Programming

The document provides model answers for a summer examination conducted by the Maharashtra State Board of Technical Education, covering various topics in Java programming, including GraphicsEnvironment, Checkbox, Servlets, JDBC, and GUI components. It includes code examples and explanations for different Java concepts, such as creating GUI elements, handling events, and database connectivity. Additionally, it discusses the InetAddress class and methods for navigating ResultSet objects in database operations.

Uploaded by

ashwini
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
55 views24 pages

12259-CO6E-Advanced_Java_Programming

The document provides model answers for a summer examination conducted by the Maharashtra State Board of Technical Education, covering various topics in Java programming, including GraphicsEnvironment, Checkbox, Servlets, JDBC, and GUI components. It includes code examples and explanations for different Java concepts, such as creating GUI elements, handling events, and database connectivity. Additionally, it discusses the InetAddress class and methods for navigating ResultSet objects in database operations.

Uploaded by

ashwini
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 24

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION

(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);
}
}

Marking scheme 1½ marks for explanation remaining for program

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.

Checkbox c1 = new checkbox ();


c1 setLabel(“new Label”);

The method getState() determines it the checkbox is checked (true) or unchecked (false). The method
return true or false.

For eg. c1.getState();


2 marks for each method
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
__________________________________________________________________________________________________
SUMMER – 12 EXAMINATION
Subject Code : 12259 Model Answer Page No : 2-24

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.

2 marks for each swing control.

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

1 it is protocol independent 1 it is protocol dependent


2 can handle all types of protocol. 2 can handle only Http specific protocol.
3 it belong to javax servlet package 3 it belong to javax.servlet http package
4 it is an abstract class which extends object & 4 it is an abstract class which extends
implements servlet, servlet config & GenericServlet & implements java.io.serializable
java.io.serializable interfaces. interfaces.
5 it overrides service() method. It does not 5 it adds the support to doGet() &
contain doGet () & doPost() methods. doPost(),doHead(),doPut(),doOptions(),doDelete()
& doTrace() methods.

e) two marks for each:

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:

Port number protocol(services)


21 FTP
23 Telnet
25 email
79 Finger
80 HTTP
119 netnews
(Any two of the above examples)

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

f) ( Two marks for each method)

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

public class AwtCloseButtonEvent{


public static void main(String[] args){
Frame frame = new Frame("Close Operation Frame");

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;

public class CloseFrame extends Frame{


MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
__________________________________________________________________________________________________
SUMMER – 12 EXAMINATION
Subject Code : 12259 Model Answer Page No : 4-24

CloseFrame(String title)
{
super(title);
addWindowListener(new MyWindowAdapter(this));
this.setSize(300,300);

this.setVisible(true);
}
class MyWindowAdapter extends WindowAdapter{

CloseFrame myWindow = null;


MyWindowAdapter(CreateWindowWithEventsExample myWindow){
this.myWindow = myWindow;
}

public void windowClosing(WindowEvent e)


{
myWindow.setVisible(false);
}
}

public static void main(String[] args)


{
CloseFrame myWindow =
new CloseFrame("Window with event Example");
}
}
Or Any other example based on above mentioned concept.

b)

import javax.swing.*;
/*<applet code = exam.class height = 300 width = 300></applet>*/

public class exam extends JApplet


{
public void init()
{
JTabbedPane jtp = new JTabbedPane();
jtp.add("Font", new FontPanel());

jtp.add("Effects", new EffectsPanel());


jtp.add("Spacing", new SpacingPanel());
getContentPane().add(jtp);
}
}
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
__________________________________________________________________________________________________
SUMMER – 12 EXAMINATION
Subject Code : 12259 Model Answer Page No : 5-24

class FontPanel extends JPanel


{
public FontPanel()
{
JComboBox jcb = new JComboBox();

jcb.addItem("Font");
jcb.addItem("Font Style");
jcb.addItem("Font Size");
add(jcb);

}
}

class EffectsPanel extends JPanel


{
public EffectsPanel()
{
JCheckBox jcb1 = new JCheckBox("Subscript");
add(jcb1);
JCheckBox jcb2 = new JCheckBox("Superscript");
add(jcb2);
JCheckBox jcb3 = new JCheckBox("Strike");
add(jcb3);
JCheckBox jcb4 = new JCheckBox("Shadow");
add(jcb4);
}
}

class SpacingPanel extends JPanel


{
public SpacingPanel()
{
String[] data = {"Spacing","Position Margin"};
JList jl = new JList(data);
add(jl);
}
}

Or any other program based on above mentioned concept.

c) JDBC driver types

1. JDBC – ODBC bridge driver


The bridge translates JDBC method calls into ODBC function calls. It is two-tier
architecture.
2. Native API – partly java driver or (Native Library – to java drivers)
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
__________________________________________________________________________________________________
SUMMER – 12 EXAMINATION
Subject Code : 12259 Model Answer Page No : 6-24

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

/*<applet code = exam1.class height = 300 width = 300></applet>*/

public class exam1 extends Applet implements ActionListener


{
TextField t1, t2, t3;
Button b1;
public void init()
{
t1 = new TextField(10);
t2 = new TextField(10);
t3 = new TextField(10);
b1 = new Button("Change Color");
add(t1);
add(t2);
add(t3);
add(b1);
b1.addActionListener(this);
}

public void actionPerformed(ActionEvent e)


{
int r = Integer.parseInt(t1.getText());
int g = Integer.parseInt(t2.getText());
int b = Integer.parseInt(t3.getText());
Color c = new Color(r, g, b);
setBackground(c);
}
}
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
__________________________________________________________________________________________________
SUMMER – 12 EXAMINATION
Subject Code : 12259 Model Answer Page No : 7-24

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

/*<applet code=calc height=200 width=200>


</applet>*/
Logic=3 marks, syntax =3 Marks , design=2 marks

Q3 b) Give the use of following methods of connection and statement interface.


i) createStatement()
it is the method of connection interface . it creates a statement object for sending SQL
statement to database.
Ex.:
Statement st = con.createStatement();
03 marks
ii) executeQueruy()
It is the method of Statement interface. It executes an SQL statement that returns a single
Resultset object.
Syntax:
Resultset rs = st. executeQuery(“select…..”);
03 Marks
iii) getResultset ()
It is the method of statement interface . It returns the current result as Resultset object.
Eg:
Resultset rs = st.getResultset();
02 marks
Q3 c)
import java.awt.*;
public class MenuTest extends Frame
{
MenuTest(String title)
{
super(title);
MenuBar mb=new MenuBar();
Menu file=new Menu("File");
Menu edit=new Menu("Edit");
Menu view=new Menu("View");
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
__________________________________________________________________________________________________
SUMMER – 12 EXAMINATION
Subject Code : 12259 Model Answer Page No : 9-24

MenuItem nw=new MenuItem("New");


MenuItem open=new MenuItem("Open");
file.add(nw);
file.add(open);
mb.add(file);
mb.add(edit);
mb.add(view);
setMenuBar(mb);
}

public static void main(String arg[])


{
MenuTest obj=new MenuTest("My Frame");
obj.setSize(200,400);
obj.setVisible(true);
}
}
Logic=3 marks, syntax =3 Marks , design=2 marks

Q 4 a) What is InetAddress ? Explain factory methods if InetAddress.


Ans: All the classes required for network programming in java can be imported through java.net
package.
For identifying the IP address of a computer, java.net provides a major class as InetAddress. This
class can be used to obtain IP Address & domain name . this ip Address can then be used by other
networking classes while specifying the address of destination & source for data packets.
InetAddress class has no visible constructor for creating an object of InetAddress class one of the
available factory methods can be used. Factory methods are the conventions where by static methods
in class return an instance of class. (01 mark each)
Commonly used InetAddress factory methods are:
i) static InetAddress getLocalHost()

- Return the InetAddress object that represents Local host.


ii) Static InetAddress getByName (string hostname)

- Return InetAddress object for a host name passed to it.


iii) Static InetAddress[] getAllByName(string hostname)
- Returns an array of InetAddress that represents all of the address that a particular name
resolves to .
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
__________________________________________________________________________________________________
SUMMER – 12 EXAMINATION
Subject Code : 12259 Model Answer Page No : 10-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.

ii) void close () – it is used to close server socket connection. 02 marks


Example showing use of (i) accept () & (ii) close () methods of ServerSocketclass.

/* server side program*/


Import java.net.*;
Import java.io.*;
class serverside
{
Public static void main(String args[]) throws IOException
{
ServerSocket skt = new ServerSocket(1200);
Socket st = skt.accept();
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
__________________________________________________________________________________________________
SUMMER – 12 EXAMINATION
Subject Code : 12259 Model Answer Page No : 11-24

InputStream is = st.get InputStream();


BufferedReader br = new bufferedReader(new InputStreamReader(is));
String s = br.readLine();
System.out.println(“Client sent:”+s);
St.close();
Skt.close();
}
}
Example 02 marks(any other example can be considered)

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

public class tree extends JApplet


{
JTree tree;
public void init()
{
DefaultMutableTreeNode t= new DefaultMutableTreeNode("IF");
DefaultMutableTreeNode a=new DefaultMutableTreeNode("Java");
t.add(a);
DefaultMutableTreeNode b= new DefaultMutableTreeNode ("Adv java");
a.add(b);
Container cnt = getContentPane();
cnt.setLayout(new FlowLayout());
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
__________________________________________________________________________________________________
SUMMER – 12 EXAMINATION
Subject Code : 12259 Model Answer Page No : 12-24

tree =new JTree(t);


JScrollPane js = new JScrollPane (tree);
cnt.add(js);
cnt.add(tree);
}
}

/*<applet code="tree" height=150 width=150>


</applet>*/
Q 4 e)
import java.awt.*;
import javax.swing.*;
public class jcombo extends JApplet
{
JComboBox jcb;
String st[]={"mouse","keyboard","battery","UPS","Stabilizer"};
public void init()
{
setLayout(new FlowLayout());
jcb=new JComboBox(st);
add(jcb);
}
}
/*<applet code=jcombo height=200 width=200>
</applet>*/
Logic 2 marks syntax 2 marks (any other logic can be considered)

Q 5 a) Attempt any three of the following:


i) URL Connection class:

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.

An object of URLConnection class can be created using openConnection() of URL


object.
02 marks
Example: Program to read content of Html file from URL print on screen.
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
__________________________________________________________________________________________________
SUMMER – 12 EXAMINATION
Subject Code : 12259 Model Answer Page No : 13-24
Example 2 marks
import java.net.*;

import java.io.*;

class url8_5

public static void main(String args[])throws MalformedURLException,IOException

URL u1=new URL("http://localhost:8080/index.htm");

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);

Any other example can be considered.

ii) Methods of URL class:


1. getProtocol():
- Returns the protocol name of the current URL.
2. getPort():

- Returns the port of the current URL it returns integer value.


3. getHost ():
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
__________________________________________________________________________________________________
SUMMER – 12 EXAMINATION
Subject Code : 12259 Model Answer Page No : 14-24

- Returns the hostname of the current URL.


4. getFile():

- Returns the Filename of the current URL.


(Example 2 marks)
Example: program to print protocol, port, hostname, & file of http: \\www.msbte.com .
import java.net.*;

import java.io.*;

class urltest1

public static void main(String args[]) throws MalformedURLException

URL ul = new URL("http://www.msbte.com ");

String s1 = ul.getProtocol();

String s2 = ul.getFile();

String s3 = ul.getHost();

int n=ul.getPort();

System.out.println("Protocol name :" +s1);

System.out.println("File name :" +s2);

System.out.println("Host name :" +s3);

System.out.println("Port no :" +n);

System.out.println("Ext : " +ul.toExternalForm());

}
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
__________________________________________________________________________________________________
SUMMER – 12 EXAMINATION
Subject Code : 12259 Model Answer Page No : 15-24

iii) Techniques of session management / tracking .

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:

url? Name1= value1 & name2 = value2 &……

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.

This method is easy to use, an HTML form is always required.

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.

Information of each cookie includes name,value, expiration date,path,domain etc.


If the domain & Path of cookie is supplied to the webserver.

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

Every user of a site is associated with javax.servlet.http package.

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.

The service() method called for each Http request.

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

Q5 b) Attempt any one of the following:


i) Use of cookie:

A cookie is stored on a client & contains stale information.

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.

Expiration date determines when cookie is deleted from client machine.

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)

Any three points from above.


Example:
import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class exp17 extends HttpServlet

public void doGet(HttpServletRequest req,HttpServletResponse res) throws


IOException,ServletException

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

if ((c != null) && (c.length > 0))

{
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

pr.print("<big>No cookies available");

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

The statement object can be created as,


Statement st = con.createStatement();

After creating statement object , the SQL statement can be used for insert, delete &
updare the records.

SQL Stmt can be created as:


String s1 = “insert into statement values(„rima‟,2);
String s2 = “update statement set rollno = 3 where rollno = 2”;
String s3 = “delete from student”;

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

public void itemStateChanged(ItemEvent e)


{
if(jc.getSelectedItem().toString().equals("India"))
{
jl.setSelectedIndex(0);
msg=jl.getSelectedValue().toString();
jb.setText(msg);
}
if(jc.getSelectedItem().toString().equals("Australia"))
{
jl.setSelectedIndex(1);
msg=jl.getSelectedValue().toString();
jb.setText(msg);
}
if(jc.getSelectedItem().toString().equals("USA"))
{
jl.setSelectedIndex(2);
msg=jl.getSelectedValue().toString();
jb.setText(msg);
}
if(jc.getSelectedItem().toString().equals("SriLanka"))
{
jl.setSelectedIndex(3);
msg=jl.getSelectedValue().toString();
jb.setText(msg);
}
if(jc.getSelectedItem().toString().equals("Pakistan"))
{
jl.setSelectedIndex(4);
msg=jl.getSelectedValue().toString();
jb.setText(msg);
}
}
}

/*<applet code=testapp height=200 width=200>


</applet>*/
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
(Autonomous)
(ISO/IEC - 27001 - 2005 Certified)
__________________________________________________________________________________________________
SUMMER – 12 EXAMINATIONS
Subject Code : 12259 Model Answer Page No : 23-24

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>

(any other valid program can be considered)

You might also like