0% found this document useful (0 votes)
4 views

Advance Java Final

adv

Uploaded by

Ram Chrestha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Advance Java Final

adv

Uploaded by

Ram Chrestha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Explain any two components of swing with examples. What is the MVC design pattern in swing?

VC design pattern in swing? Explain Event handling in Cookies in Servlet


The basic AWT library deals with user interface elements by delegating swing with suitable examples. A cookie is a small piece of information that is persisted between the
their creation and behavior to the native GUI toolkit on each target Swing actually makes use of a simplified variant of the MVC design called multiple client requests.
platform (Windows, Solaris, Macintosh, and so on). the model-delegate . This design combines the view and the controller A cookie has a name, a single value, and optional attributes such as a
This peer-based approach worked well for simple applications. User object into a single element that draws the component to the screen comment, path and domain qualifiers, a maximum age, and a version
interface elements such as menus, scrollbars, and text fields can have and handles GUI events known as the UI delegate . Bundling graphics number.
subtle differences in behavior on different platforms. Moreover, some capabilities and event handling is somewhat easy in Java, since much of
graphical environments do not have as rich a collection of user interface the event handling is taken care of in AWT. As you might expect, the How Cookie works?
components as does Windows or the Macintosh Unlike AWT, Java Swing communication between the model and the UI delegate then becomes By default, each request is considered as a new request. In cookies
provides platform-independent and lightweight components. a two-way street, as shown in Figure below: technique, we add cookie with response from the servlet. So cookie is
The javax.swing package provides classes for java swing API such as With Swing, the view and the controller are combined into a UI-delegate stored in the cache of the browser. After that if request is sent by the
JButton, JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, object user, cookie is added with request by default. Thus, we recognize the
JColorChooser etc. user as the old user.

Difference between AWT and Swing Simple example of Servlet Cookies


There are many differences between java awt and swing that are given below. In this example, we are storing the name of the user in the cookie
object and accessing it in another servlet.
No. Java AWT Java Swing As we know well that session corresponds to the particular user. So if
you access it from too many browsers with different values, you will get
the different value.
1) AWT components Java swing Figure 1-7. With Swing, the view and the controller are combined into a
are platform- components
UI-delegate object
dependent. are platform-
Each Swing component contains a model and a UI delegate. The model
independent.
is responsible for maintaining information about the component’s state.
The UI delegate is responsible for maintaining information about how to
2) AWT components Swing components draw the component on the screen. In addition, the UI delegate (in
are heavyweight. are lightweight. conjunction with AWT) reacts to various events that propagate through
the component.
3) AWT doesn't support Swing supports
Event Handling is the mechanism that controls the event and decides
pluggable look and feel. pluggable look and
what should happen if an event occurs. This mechanism has a code
feel.
which is known as an event handler, that is executed when an event index.html
occurs. 1) <form action="servlet1" method="post">
4) AWT provides less Swing provides more Create the following Java program using any editor of your choice in say 2) Name:<input type="text" name="userName"/><br/>
components than powerful D:/ > SWING > com > example> gui > 3) <input type="submit" value="go"/>
Swing. components such as SwingControlDemo.java 4) </form>
tables, lists, 1) package com.tutorialspoint.gui;
scrollpanes, 2) import java.awt.*; FirstServlet.java
colorchooser, 3) import java.awt.event.*; 1) import java.io.*;
tabbedpane etc.
4) import javax.swing.*; 2) import javax.servlet.*;
5) public class SwingControlDemo { 3) import javax.servlet.http.*;
5) AWT doesn't follows Swing follows MVC. 6) private JFrame mainFrame; 4) public class FirstServlet extends HttpServlet {
MVC(Model View 7) private JLabel headerLabel; 5) public void doPost(HttpServletRequest request,
Controller) where model 8) private JLabel statusLabel; HttpServletResponse response){
represents data, view 9) private JPanel controlPanel; 6) try{
represents presentation 10) public SwingControlDemo(){ 7) response.setContentType("text/html");
and controller acts as an 11) prepareGUI(); 8) PrintWriter out = response.getWriter();
interface between 12) } 9) String n=request.getParameter("userName");
model and view.
13) public static void main(String[] args){ 10) out.print("Welcome "+n);
14) SwingControlDemo swingControlDemo = new 11) Cookie ck=new Cookie("uname",n);//creating cookie
SwingControlDemo(); object
Java Swing Example 1 :
15) swingControlDemo.showEventDemo(); 12) response.addCookie(ck);//adding cookie in the response
Using java button:
16) } 13) //creating submit button
17) private void prepareGUI(){ 14) out.print("<form action='servlet2'>");
1. import javax.swing.*;
18) mainFrame = new JFrame("Java SWING Examples"); 15) out.print("<input type='submit' value='go'>");
2. public class FirstSwingExample {
19) mainFrame.setSize(400,400); 16) out.print("</form>");
3. public static void main(String[] args) {
20) mainFrame.setLayout(new GridLayout(3, 1)); 17) out.close();
4. JFrame f=new JFrame();//creating instance of JFrame
21) headerLabel = new JLabel("",JLabel.CENTER ); 18) }catch(Exception e){System.out.println(e);}
5. JButton b=new JButton("click");//creating instance of
22) statusLabel = new JLabel("",JLabel.CENTER); 19) }
JButton
23) statusLabel.setSize(350,100); 20) }
6. b.setBounds(130,100,100, 40);//x axis, y axis, width,
24) mainFrame.addWindowListener(new WindowAdapter() {
height
25) public void windowClosing(WindowEvent windowEvent){ SecondServlet.java
7. f.add(b);//adding button in JFrame
26) System.exit(0); 1) import java.io.*;
8. f.setSize(400,500);//400 width and 500 height
27) } 2) import javax.servlet.*;
9. f.setLayout(null);//using no layout managers
28) }); 3) import javax.servlet.http.*;
10. f.setVisible(true);//making the frame visible
29) controlPanel = new JPanel(); 4) public class SecondServlet extends HttpServlet {
11. }
30) controlPanel.setLayout(new FlowLayout()); 5) public void doPost(HttpServletRequest request,
12. }
31) mainFrame.add(headerLabel); HttpServletResponse response){
32) mainFrame.add(controlPanel); 6) try{
Example 2:
33) mainFrame.add(statusLabel); 7) response.setContentType("text/html");
Java JLabel Example
34) mainFrame.setVisible(true); 8) PrintWriter out = response.getWriter();
1. import javax.swing.*;
35) } 9) Cookie ck[]=request.getCookies();
2. class LabelExample
36) private void showEventDemo(){ 10) out.print("Hello "+ck[0].getValue());
3. {
37) headerLabel.setText("Control in action: Button"); 11) out.close();
4. public static void main(String args[])
38) JButton okButton = new JButton("OK"); 12) }catch(Exception e){System.out.println(e);}
5. {
39) JButton submitButton = new JButton("Submit"); 13) }
6. JFrame f= new JFrame("Label Example");
40) JButton cancelButton = new JButton("Cancel"); 14) }
7. JLabel l1,l2;
41) okButton.setActionCommand("OK");
8. l1=new JLabel("First Label.");
42) submitButton.setActionCommand("Submit"); web.xml
9. l1.setBounds(50,50, 100,30);
43) cancelButton.setActionCommand("Cancel"); 1) <web-app>
10. l2=new JLabel("Second Label.");
44) okButton.addActionListener(new ButtonClickListener()); 2) <servlet>
11. l2.setBounds(50,100, 100,30);
45) submitButton.addActionListener(new ButtonClickListener()); 3) <servlet-name>s1</servlet-name>
12. f.add(l1); f.add(l2);
46) cancelButton.addActionListener(new ButtonClickListener()); 4) <servlet-class>FirstServlet</servlet-class>
13. f.setSize(300,300);
47) controlPanel.add(okButton); 5) </servlet>
14. f.setLayout(null);
48) controlPanel.add(submitButton); 6) <servlet-mapping>
15. f.setVisible(true);
49) controlPanel.add(cancelButton); 7) <servlet-name>s1</servlet-name>
16. }
50) mainFrame.setVisible(true); 8) <url-pattern>/servlet1</url-pattern>
17. }
51) } 9) </servlet-mapping>
=========================================================
52) private class ButtonClickListener implements ActionListener{ 10) <servlet>
53) public void actionPerformed(ActionEvent e) { 11) <servlet-name>s2</servlet-name>
54) String command = e.getActionCommand(); 12) <servlet-class>SecondServlet</servlet-class>
55) if( command.equals( "OK" )) { 13) </servlet>
56) statusLabel.setText("Ok Button clicked."); 14) <servlet-mapping>
57) } else if( command.equals( "Submit" ) ) { 15) <servlet-name>s2</servlet-name>
58) statusLabel.setText("Submit Button clicked."); 16) <url-pattern>/servlet2</url-pattern>
59) } else { 17) </servlet-mapping>
60) statusLabel.setText("Cancel Button clicked.");}}}} 18) </web-app>
Explain different types of tags in JSP with examples. Why are adapter classes important? Compare it with the listener Explain RMI Architecture in detail.
JSP Scripting elements interface with suitable examples. Remote Method Invocation (RMI) is an API that allows an object to
The scripting elements provides the ability to insert java code inside the invoke a method on an object that exists in another address space,
jsp. There are three types of scripting elements: Java adapter classes provide the default implementation of listener which could be on the same machine or on a remote machine. Through
1) scriptlet tag interfaces. If you inherit the adapter class, you will not be forced to RMI, an object running in a JVM present on a computer (Client-side) can
2) expression tag provide the implementation of all the methods of listener interfaces. So invoke methods on an object present in another JVM (Server-side). RMI
3) declaration tag it saves code. creates a public remote server object that enables client and server-side
communications through simple method calls on the server object.
1. JSP scriptlet tag Pros of using Adapter classes:
A scriptlet tag is used to execute java source code in JSP. Syntax is as • It assists the unrelated classes to work combinedly.
follows: • It provides ways to use classes in different ways.
<% java source code %> • It increases the transparency of classes.
• It provides a way to include related patterns in the class.
Example of JSP scriptlet tag that prints the user name • It provides a pluggable kit for developing an application.
In this example, we have created two files index.html and welcome.jsp. • It increases the reusability of the class.
The index.html file gets the username from the user and the
welcome.jsp file prints the username with the welcome message. Listeners are used when the programmer intends to utilize most of the
methods listed under the interface. If a listener interface is implemented
File: index.html directly by a class, all the methods within that interface need to be
<html> implemented, making the code unreasonably large. This complexity can
<body> be resolved by calling upon an adapter class. An adapter class proves
<form action="welcome.jsp"> essential in instances where an event calls for only specific methods.
<input type="text" name="uname">
<input type="submit" value="go"><br/> Transport Layer : This layer connects the client and the server. It
The programmer has only to create a subclass of it and override the manages the existing connection and also sets up new connections.
</form> interest methods to use an adapter class. Adapter classes are, therefore,
</body> beneficial for listener interfaces in JAVA having more than one method.
</html> Stub : A stub is a representation (proxy) of the remote object at client. It
To better understand this, let us consider the example of the resides in the client system; it acts as a gateway for the client program.
MouseListener interface. This interface is notified whenever there is a
File: welcome.jsp change in the state of the mouse. It has five methods, mouse clicked,
<html> Skeleton: This is the object which resides on the server side. stub
mouseExited, mouseEntered, mousePressed, and mouseReleased. communicates with this skeleton to pass request to the remote object.
<body>
<% Java WindowAdapter Example
String name=request.getParameter("uname"); RRL(Remote Reference Layer): It is the layer which manages the
In the following example, we are implementing the WindowAdapter references made by the client to the remote object.
out.print("welcome "+name); class of AWT and one its methods windowClosing() to close the frame
%> window.
</form> Working of an RMI Application
</body> The following points summarize how an RMI application works −
AdapterExample.java • When the client makes a call to the remote object, it is
</html> 1) import java.awt.*; received by the stub which eventually passes this
2) import java.awt.event.*; request to the RRL.
2. JSP expression tag
The code placed within JSP expression tag is written to the output • When the client-side RRL receives the request, it invokes
3) public class AdapterExample {
stream of the response. So you need not write out.print() to write data. a method called invoke() of the object remoteRef. It
4) // object of Frame
It is mainly used to print the values of variable or method. passes the request to the RRL on the server side.
5) Frame f;
• The RRL on the server side passes the request to the
6) // class constructor
Example of JSP expression tag that prints the user name Skeleton (proxy on the server) which finally invokes the
7) AdapterExample() {
In this example, we are printing the username using the expression tag. required object on the server.
8) // creating a frame with the title
The index.html file gets the username and sends the request to the • The result is passed all the way back to the client.
9) f = new Frame ("Window Adapter");
welcome.jsp file, which displays the username. Goals of RMI
10) // adding the WindowListener to the frame
Following are the goals of RMI −
11) // overriding the windowClosing() method
File: index.jsp • To minimize the complexity of the application.
12) f.addWindowListener (new WindowAdapter() {
<html> 13) public void windowClosing (WindowEvent e) { • To preserve type safety.
<body> 14) f.dispose(); • Distributed garbage collection.
<form action="welcome.jsp"> 15) } • Minimize the difference between working with local and
<input type="text" name="uname"><br/> 16) }); remote objects.
<input type="submit" value="go"> 17) // setting the size, layout and
</form> 18) f.setSize (400, 400); ==========================================================
</body> 19) f.setLayout (null); Explain about different types of ResultSet used in JDBC.
</html> 20) f.setVisible (true); There are two types of result sets namely, forward only and,
21) } bidirectional.
File: welcome.jsp 1. Forward only ResultSet:
<html> 22) // main method The ResultSet object whose cursor moves only in one direction is known
<body> 23) public static void main(String[] args) { as forward only ResultSet. By default, JDBC result sets are forward-only
<%= "Welcome "+request.getParameter("uname") %> 24) new AdapterExample(); result sets.
</body> 25) } You can move the cursor of the forward only ResultSets using the next()
</html> 26) } method of the ResultSet interface. It moves the pointer to the next row
========================================================== from the current position. This method returns a boolean value. If there
3. JSP declaration tag What is Java bean? Explain Properties, Events and Methods design are no rows next to its current position it returns false, else it returns
The JSP declaration tag is used to declare fields and methods. patterns. true.
The code written inside the jsp declaration tag is placed outside the A JavaBean is a Java class that should follow the following conventions: Therefore, using this method in the while loop you can iterate the
service() method of auto generated servlet. • It should have a no-arg constructor. contents of the ResultSet object.
So it doesn't get memory at each request. • It should be Serializable. while(rs.next()){
Example of JSP declaration tag that declares method }
• It should provide methods to set and get the values of the
In this example of JSP declaration tag, we are defining the method which properties, known as getter and setter methods.
returns the cube of given number and calling this method from the jsp 2. Bidirectional ResultSet:
A JavaBean property may be read, write, read-only, or write-only.
expression tag. But we can also use jsp scriptlet tag to call the declared A bi-directional ResultSet object is the one whose cursor moves in both
JavaBean features are accessed through two methods in the JavaBean's
method. forward and backward directions.
implementation class:
index.jsp
<html> The createStatement() method of the Connection interface has a variant
1. getPropertyName ()
<body> which accepts two integer values representing the result set type and
For example, if the property name is firstName, the method name would
<%! the concurrency type.
be getFirstName() to read that property. This method is called the
int cube(int n){ accessor.
return n*n*n*; Statement createStatement(int resultSetType, int
} resultSetConcurrency)
2. setPropertyName ()
%> To create a bi-directional result set you need to pass the type as
For example, if the property name is firstName, the method name would
<%= "Cube of 3 is:"+cube(3) %> ResultSet.TYPE_SCROLL_SENSITIVE or
be setFirstName() to write that property. This method is called the
</body> ResultSet.TYPE_SCROLL_INSENSITIVE, along with the concurrency, to
mutator.
</html> this method as:
Property design patterns are used to identify the properties of a Bean.
//Creating a Statement object
Not surprisingly, property design patterns are closely related to accessor
========================================================== Statement stmt =
methods. In fact, accessor methods are the means by which the
con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
JavaBean's automatic introspection facility determines the properties of
ResultSet.CONCUR_UPDATABLE);
a Bean. Basically, any time the JavaBeans introspector encounters a
public getter or setter method, it assumes the member variable being
==========================================================
get or set is a property, and then exposes the property to the outside
=
world.
==========================================================
Difference between RMI and CORBA What is an Event Handling and describe the components in Event JavaBean and its properties with example.
RMI CORBA Handling in Java? Explain with example ? A JavaBean is a Java class that should follow the following conventions:
RMI is a Java-specific CORBA has implementation The GUI in Java processes the interactions with users via mouse,
keyboard and various user controls such as button, checkbox, text field,
o It should have a no-arg constructor.
technology. for many languages.
etc. as the events. These events are to be handled properly to o It should be Serializable.
It uses Java interface for It uses Interface Definition implement Java as an Event-Driven Programming. o It should provide methods to set and get the values of the
implementation. Language (IDL) to separate properties, known as getter and setter methods.
interface from Components in Event Handling
implementation. • Events Why use JavaBean?
• Event Sources According to Java white paper, it is a reusable software component. A
RMI objects are garbage CORBA objects are not • Event Listeners/Handlers bean encapsulates many objects into one object so that we can access
collected automatically. garbage collected because it this object from multiple places. Moreover, it provides easy
is language independent and 1. Events maintenance.
some languages like C++ does • The events are defined as an object that describes a Simple example of JavaBean class
not support garbage change in the state of a source object. 1. //Employee.java
collection. • The Java defines a number of such Event Classes inside 2.
java.awt.event package 3. package mypack;
RMI programs can download CORBA does not support this • Some of the events are ActionEvent, MouseEvent, 4. public class Employee implements java.io.Serializable{
new classes from remote code sharing mechanism. KeyEvent, FocusEvent, ItemEvent and etc. 5. private int id;
JVM’s. 6. private String name;
2. Event Sources 7. public Employee(){}
RMI passes objects by CORBA passes objects by • A source is an object that generates an event. 8. public void setId(int id){this.id=id;}
remote reference or by reference. • An event generation occurs when an internal state of that 9. public int getId(){return id;}
value. object changes in some way. 10. public void setName(String name){this.name=name;}
• A source must register listeners in order for the listeners 11. public String getName(){return name;}
The responsibility of locating The responsibility of locating to receive the notifications about a specific type of event. 12. }
an object implementation an object implementation • Some of the event sources are Button, CheckBox, List,
falls on JVM. falls on Object Adapter either Choice, Window and etc. How to access the JavaBean class?
To access the JavaBean class, we should use getter and setter methods.
Basic Object Adapter or
Portable Object Adapter. 3. Event Listeners 1. package mypack;
2. public class Test{
• A listener is an object that is notified when an event
occurs. 3. public static void main(String args[]){
RMI uses the Java Remote CORBA use Internet Inter-
4. Employee e=new Employee();//object is created
Method Protocol as its ORB Protocol as its • A Listener has two major requirements, it should be
5. e.setName("Arjun");//setting value to the object
underlying remoting underlying remoting registered to one more source object to receiving event
6. System.out.println(e.getName());
protocol. protocol. notification and it must implement methods to receive
7. }}
and process those notifications.
Note: There are two ways to provide values to the object. One way is by
• Java has defined a set of interfaces for receiving and
constructor and second is by setter method.
========================================================= processing the events under the java.awt.event package.
• Some of the listeners are ActionListener, MouseListener,
JavaBean Properties
========================================================= ItemListener, KeyListener, WindowListener and etc.
A JavaBean property is a named feature that can be accessed by the user
why do we use panels while creating GUI program in java?
of the object. The feature can be of any Java data type, containing the
By using Panels it's easier to group components and arrange them in Example
classes that you define.
a Frame. Every Panel can have it's own layout. So you could give your 1. import java.awt.*;
A JavaBean property may be read, write, read-only, or write-only.
outer Frame a BorderLayout and put a Panel into the center. 2. import java.awt.event.*;
JavaBean features are accessed through two methods in the JavaBean's
The Panel then can have let's say a GridBagLayout for it's components. 3. import javax.swing.*;
implementation class:
A panel is a container. 4. public class EventListenerTest extends JFrame
• It allows you to group components together 5.
implements ActionListener {
JButton button;
1. getPropertyName ()
For example, if the property name is firstName, the method name would
• It allows you to devise complex interfaces, as each panel 6. public static void main(String args[]) {
be getFirstName() to read that property. This method is called the
can have a different layout, allowing you to leverage the 7. EventListenerTest object = new EventListenerTest();
accessor.
power of different layout managers. 8. object.createGUI();
9. }
• It allows you to build reusable components and isolate 10. void createGUI() {
2. setPropertyName ()
For example, if the property name is firstName, the method name would
responsibility 11. button = new JButton(" Click Me !");
be setFirstName() to write that property. This method is called the
• But most of all, it gives you the bases for deciding how 12.
13.
setSize(300,200);
setLocationRelativeTo(null);
mutator.
the panel should be deployed. With a panel you can add Advantages of JavaBean
it to a frame or applet or another component as 14. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
The following are the advantages of JavaBean:/p>
needed... 15. setVisible(true);
16. add(button); o The JavaBean properties and methods can be exposed to
• A panel also makes a good surface onto which to 17. button.addActionListener(this); another application.
perform custom painting. For all the benefits mentioned 18. } o It provides an easiness to reuse the software
above - its isolated and reusable... 19. public void actionPerformed(ActionEvent ae) { components.
========================================================== 20. if(ae.getSource() == button) { Disadvantages of JavaBean
Cookies and using handling cookies in Java 21. JOptionPane.showMessageDialog(null, "Generates an The following are the disadvantages of JavaBean:
Cookies are the textual information that is stored in key-value pair Action Event");
format to the client’s browser during multiple requests. It is one of the 22. }
o JavaBeans are mutable. So, it can't take advantages of
immutable objects.
state management techniques in session tracking. Basically, the server 23. }
treats every client request as a new one so to avoid this situation 24. } o Creating the setter and getter method for each property
cookies are used. When the client generates a request, the server gives separately may lead to the boilerplate code.
the response with cookies having an id which are then stored in the ========================================================== ==========================================================
client’s browser. Thus if the client generates a second request, a cookie Marshalling and Unmarshalling Working with 2D Shapes
with the matched id is also sent to the server. The server will fetch the Whenever a client invokes a method that accepts parameters on a Starting with Java 1.0, the Graphics class from java.awt package has
methods to draw strings, lines, rectangles, ellipses, and so on. For
cookie id, if found it will treat it as an old request otherwise the remote object, the parameters are bundled into a message before being example to draw line, we use drawLine(x1, y1, x2, y2) method as show
request is considered new. sent over the network. These parameters may be of primitive type or below,
objects. In case of primitive type, the parameters are put together and class SimplePanel extends JPanel
Methods in Cookies a header is attached to it. In case the parameters are objects, then they {
1) clone(): Overrides the standard java.lang.Object.clone are serialized. This process is known as marshalling. public void paintComponent(Graphics g)
method to return a copy of this Cookie. {
g.drawLine(10,10,100,100);
2) getComment(): Returns the comment describing the purpose At the server side, the packed parameters are unbundled and then the
}
of this cookie, or null if the cookie has no comment. required method is invoked. This process is known as unmarshalling. }
3) getDomain(): Gets the domain name of this Cookie. To draw rectangles, we use drawRect(x1, y1, w, h) method and to draw
4) getMaxAge(): Gets the maximum age in seconds of this ======================================================== string we use
Cookie. SimplePropertyBeanMain.java(java bean Example) drawString(▫String▫, x1, y1) and so on. The drawings using Graphics
5) getName(): Returns the name of the cookie. public class SimplePropertyBeanMain class methods are very limited. For example, you cannot vary the line
6) getPath(): Returns the path on the server to which the thickness and cannot rotate the shapes.
{
browser returns this cookie. public static void main(String args[]) program :
7) getSecure(): Returns true if the browser is sending cookies { class SimplePanel extends JPanel
only over a secure protocol, or false if the browser can send SimplePropertyBean ob=new SimplePropertyBean(); {
cookies using any protocol. ob.setLength(5); public void paintComponent(Graphics g)
8) getValue(): Gets the current value of this Cookie. ob.setBreadth(3); {
9) getVersion(): Returns the version of the protocol this cookie ob.setHeight(2); Graphics2D g2d = (Graphics2D)g;
Rectangle2D floatRect = new Rectangle2D.Float (10, 15.5F, 52.5F,
complies with. System.out.println("Volume 60.0F);
10) setValue(String newValue): Assigns a new value to this :"+ob.getLength()*ob.getBreadth()*ob.getHeight()); g2d.draw(floatRect);
Cookie. }} }
11) setVersion(int v): Sets the version of the cookie protocol that }
this Cookie complies with. ========================================================= =========================================================
Life Cycle of a Servlet (Servlet Life Cycle) What is a LayoutManager and types of LayoutManager in Java? 33) gridLayoutPanel2.setLayout(new GridLayout(1, 3, 5, 5));
The web container maintains the life cycle of a servlet instance. Let's see // Set GridLayout Manager
the life cycle of the servlet: The Layout managers enable us to control the way in which visual 34) gridLayoutPanel2.add(lbl1);
• Servlet class is loaded. components are arranged in the GUI forms by determining the size and 35) gridLayoutPanel2.add(lbl2)
• Servlet instance is created. position of components within the containers. 36) gridLayoutPanel2.add(lbl3);
• init method is invoked. Types of LayoutManager 37) gridLayoutPanel3.setLayout(new GridLayout(3, 1, 5,
• service method is invoked. There are 6 layout managers in Java 5)); // Set GridLayout Manager
• destroy method is invoked. • FlowLayout: It arranges the components in a container
38)
39)
gridLayoutPanel3.add(four);
gridLayoutPanel3.add(five);
like the words on a page. It fills the top line from left to 40) gridLayoutPanel3.add(six);
right and top to bottom. The components are arranged
41) gridLayoutPanel1.setLayout(new GridLayout(2, 1)); //
in the order as they are added i.e. first components Set GridLayout Manager
appears at top left, if the container is not wide enough
42) gridLayoutPanel1.add(gridLayoutPanel2);
to display all the components, it is wrapped around the 43) gridLayoutPanel1.add(gridLayoutPanel3);
line. Vertical and horizontal gap between components
44) add(flowLayoutPanel1, BorderLayout.NORTH);
can be controlled. The components can be left, center 45) add(flowLayoutPanel2, BorderLayout.SOUTH);
or right aligned.
46) add(gridLayoutPanel1, BorderLayout.CENTER);
• BorderLayout: It arranges all the components along the 47) setSize(400, 325);
edges or the middle of the container i.e. top, bottom, 48) setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
right and left edges of the area. The components added 49) setLocationRelativeTo(null);
to the top or bottom gets its preferred height, but its 50) setVisible(true);
width will be the width of the container and also the 51) }
components added to the left or right gets its preferred 52) public static void main(String args[]) {
width, but its height will be the remaining height of the 53) new LayoutManagerTest();
container. The components added to the center gets 54) }
neither its preferred height or width. It covers the 55) }
remaining area of the container. Output:

• GridLayout: It arranges all the components in a grid


of equally sized cells, adding them from the left to right
As displayed in the above diagram, there are three states of a servlet:
and top to bottom. Only one component can be placed
new, ready and end. The servlet is in new state if servlet instance is
in a cell and each region of the grid will have the same
created. After invoking the init() method, Servlet comes in the ready
size. When the container is resized, all cells are
state. In the ready state, servlet performs all the tasks. When the web
automatically resized. The order of placing the
container invokes the destroy() method, it shifts to the end state.
components in a cell is determined as they were added.
1) Servlet class is loaded • GridBagLayout: It is a powerful layout which arranges all
The classloader is responsible to load the servlet class. The servlet class the components in a grid of cells and maintains the
is loaded when the first request for the servlet is received by the web aspect ration of the object whenever the container is
container. resized. In this layout, cells may be different in size. It
assigns a consistent horizontal and vertical gap among ==========================================================
2) Servlet instance is created components. It allows us to specify a default alignment Session Tracking in Servlets
The web container creates the instance of a servlet after loading the for components within the columns or rows. Session simply means a particular interval of time.
servlet class. The servlet instance is created only once in the servlet life
cycle. • BoxLayout: It arranges multiple components in
Session Tracking is a way to maintain state (data) of an user. It is also
known as session management in servlet.
either vertically or horizontally, but not both. The
3) init method is invoked components are arranged from left to right or top to
Http protocol is a stateless so we need to maintain state using session
The web container calls the init method only once after creating the bottom. If the components are aligned horizontally, the
tracking techniques. Each time user requests to the server, server
servlet instance. The init method is used to initialize the servlet. It is the height of all components will be the same and equal to
treats the request as the new request. So we need to maintain the
life cycle method of the javax.servlet.Servlet interface. Syntax of the init the largest sized components. If the components are
state of an user to recognize to particular user.
method is given below: aligned vertically, the width of all components will be
HTTP is stateless that means each request is considered as the new
public void init(ServletConfig config) throws ServletException the same and equal to the largest width components.
request. It is shown in the figure given below:
• CardLayout: It arranges two or more components
4) service method is invoked having the same size. The components are arranged in a
The web container calls the service method each time when request for deck, where all the cards of the same size and the only
the servlet is received. If servlet is not initialized, it follows the first three top card are visible at any time. The first component
steps as described above then calls the service method. If servlet is added in the container will be kept at the top of the
initialized, it calls the service method. Notice that servlet is initialized deck. The default gap at the left, right, top and bottom
only once. The syntax of the service method of the Servlet interface is edges are zero and the card components are displayed
given below: either horizontally or vertically.
Example
public void service(ServletRequest request, ServletResponse response) 1) import java.awt.*;
throws ServletException, IOException 2) import javax.swing.*;
3) public class LayoutManagerTest extends JFrame {
5) destroy method is invoked 4) JPanel flowLayoutPanel1, flowLayoutPanel2,
The web container calls the destroy method before removing the servlet gridLayoutPanel1, gridLayoutPanel2, gridLayoutPanel3;
instance from the service. It gives the servlet an opportunity to clean up 5) JButton one, two, three, four, five, six; We use session tracking To recognize the user It is used to recognize
any resource for example memory, thread etc. The syntax of the destroy 6) JLabel bottom, lbl1, lbl2, lbl3; the particular user.
method of the Servlet interface is given below: 7) public LayoutManagerTest() { Session Tracking Techniques
8) setTitle("LayoutManager Test"); There are four techniques used in Session tracking:
public void destroy() 9) setLayout(new BorderLayout()); • Cookies
========================================================== 10) // Set BorderLayout for JFrame • Hidden Form Field
Servlet vs JSP 11) flowLayoutPanel1 = new JPanel(); • URL Rewriting
Servlet JSP 12) one = new JButton("One"); • HttpSession
Servlets are faster as JSP is slower than Servlets, as 13) two = new JButton("Two");
==================================================
compared to JSP, as they have the first step in the JSP 14) three = new JButton("Three"); Difference between scrollable and updateable resultSet with example.
a short response time. lifecycle is the conversion of 15) flowLayoutPanel1.setLayout(new
JSP to Java code and then the FlowLayout(FlowLayout.CENTER)); Scrollable result set Updateable result set
compilation of the code. 16) // Set FlowLayout Manager
Servlets are Java-based codes. JSP are HTML-based codes. 17) flowLayoutPanel1.add(one);
you can move you can programmatically update entries
Servlets are harder to code, as JSPs are easier to code, as 18) flowLayoutPanel1.add(two);
forward and so that the database is automatically
here, the HTML codes are here Java is coded in HTML. 19) flowLayoutPanel1.add(three);
backward through a updated.
written in Java. 20) flowLayoutPanel2 = new JPanel();
result set and even
In an MVC architecture, In MVC architectures, the JSPs 21) bottom = new JLabel("This is South");
jump to any
Servlets act as the controllers. act as a view to present the 22) flowLayoutPanel2.setLayout (new
position.
output to the users. FlowLayout(FlowLayout.CENTER))
The service() function can be The service() function cannot ; // Set FlowLayout Manager
overridden in Servlets. be overridden in JSPs. 23) flowLayoutPanel2.add(bottom); Statement stmt = Statement stmt
The Servlets are capable of The JSPs are confined to 24) gridLayoutPanel1 = new JPanel(); conn.createStatem =conn.createStatement(ResultSet.TYPE_S
accepting all types of protocol accept only the HTTP 25) gridLayoutPanel2 = new JPanel(); ent(type, CROLL_SENSITIVE,
requests. requests. 26) gridLayoutPanel3 = new JPanel(); concurrency);
27) lbl1 = new JLabel("One"); ResultSet.CONCUR_UPDATABLE);
Modification in Servlets is a Modification is easy and faster
time-consuming and in JSPs as we just need to 28) lbl2 = new JLabel("Two"); =========================================================
challenging task, as here, one refresh the pages. 29) lbl3 = new JLabel("Three");
will have to reload, recompile, 30) four = new JButton("Four");
and then restart the servers. 31) five = new JButton("Five");
32) six = new JButton("Six");
Java JDBC and it’s drivers types What is WEB Framework in Java
JDBC stands for Java Database Connectivity. JDBC is a Java API to Java Framework is the body or platform of pre-written codes used by
connect and execute the query with the database. It is a part of JavaSE Java developers to develop Java applications or web applications. In
(Java Standard Edition). JDBC API uses JDBC drivers to connect with the other words, Java Framework is a collection of predefined classes and
database. There are four types of JDBC drivers: functions that is used to process input, manage hardware devices
interacts with system software. It acts like a skeleton that helps the
• JDBC-ODBC Bridge Driver, developer to develop an application by writing their own code.
• Native Driver,
• Network Protocol Driver, and Spring
• Thin Driver It is a light-weighted, powerful Java application development
framework. It is used for JEE. Its other modules are Spring Security,
Spring MVC, Spring Batch, Spring ORM, Spring Boot and Spring Cloud etc.

Hibernate
Hibernate is ORM (Object-Relation Mapping) framework that allows us
establish communication between Java programming language and the
RDBMS.

Grails
It is a dynamic framework created by using the Groovy programming
language. It is an OOPs language. Its purpose is to enhance the
productivity. The syntax of Grails is matched with Java and the code is
We can use JDBC API to handle database using Java program and can
compiled to JVM. It also works with Java, JEE, Spring and Hibernate.
perform the following activities:
========================================================
• Connect to the database
Difference between Library and framework
• Execute queries and update statements to the database
Library Framework
• Retrieve the result received from the database.
Library is the collection of Framework is the collection of
1) JDBC-ODBC bridge driver frequently used, pre- libraries.
The JDBC-ODBC bridge driver uses ODBC driver to connect to the compiled classes.
database. The JDBC-ODBC bridge driver converts JDBC method calls It is a set of reusable It is a piece of code that dictates
into the ODBC function calls. This is now discouraged because of thin functions used by computer the architecture of your project
driver. programs. and aids in programs.
You are in full control when The code never calls into a
you call a method from a framework, instead the
library and the control is then framework calls you.
returned.
It is in corporate seamlessly It cannot be seamlessly
into existing projects to add incorporated into an existing
functionality that you can project. Instead it can be used
access using an API. when a new project is started.
They are important in They provide a standard way to
program for linking and build and deploy applications. =========================================================
binding process. Differentiate between rowset and resultset
Libraries do no employ an Framework employs an inverted ResultSet RowSet
2) Native-API driver
The Native API driver uses the client-side libraries of the database. The inverted flow of control flow of control between itself
A ResultSet always A RowSet can be connected, disconnected
driver converts JDBC method calls into native calls of the database API. between itself and its clients. and its clients.
maintains connection with from the database.
It is not written entirely in java. Example: jQuery is a Example: Angular JS is a
the database.
JavaScript library that JavaScript-based framework for
It cannot be serialized. A RowSet object can be serialized.
simplifies DOM dynamic web applications.
manipulation. ResultSet object cannot be You can pass a RowSet object over the
========================================================== passed other over network. network.
Write a program object to read personal details from HTML file or ResultSet object is not a ResultSet Object is a JavaBean object.You
another JSP file. JavaBean objectYou can can get a RowSet using
create/get a result set using the RowSetProvider.newFactory().createJdb
the executeQuery() method. cRowSet() method.
By default, ResultSet object By default, RowSet object is scrollable and
is not scrollable or, updatable.
updatable.

==========================================================
3) Network Protocol driver 1. Statement :
The Network Protocol driver uses middleware (application server) that It is used for accessing your database. Statement interface cannot
converts JDBC calls directly or indirectly into the vendor-specific accept parameters and useful when you are using static SQL
database protocol. It is fully written in java. statements at runtime. If you want to run SQL query only once then
this interface is preferred over PreparedStatement.

Example –
//Creating The Statement Object
Statement GFG = con.createStatement();
//Executing The Statement
GFG.executeUpdate("CREATE TABLE STUDENT(ID NUMBER NOT NULL,
NAME VARCHAR)");

2. PreparedStatement :
It is used when you want to use SQL statements many times. The
PreparedStatement interface accepts input parameters at runtime.
4) Thin driver
The thin driver converts JDBC calls directly into the vendor-specific Example –
database protocol. That is why it is known as thin driver. It is fully //Creating the PreparedStatement object
written in Java language. PreparedStatement GFG = con.prepareStatement("update STUDENT
set NAME = ? where ID = ?");
//Setting values to place holders
//Assigns "RAM" to first place holder
GFG.setString(1, "RAM");
//Assigns "512" to second place holder
GFG.setInt(2, 512);
//Executing PreparedStatement
GFG.executeUpdate();

==========================================================
==

-------------------------------------------------à
JDBC Configuration to execute sql Write a program to calculate simple interest using swing? The following JSP program calculates factorial values for an integer
In this example we are using MySql as the database. So we need to know number, while the input is taken from an HTML form.
following information’s for the mysql database: 1) import javax.swing.*;
2) import java.awt.*;
1. Load a JDBC Driver class 3) import java.awt.event.*; input.html
To load a class at runtime into JVM, we need to call a static method 4) public class SimpleIntrest extends JFrame implements
called forName() of java.lang.Class. By calling the forName() method we ActionListener 1) <html>
can load the JDBC Driver class into the JVM. 5) { 2) <body>
3) <form action="Factorial.jsp">
2. Establish a Connection 6) JLabel lblPrinciple = new JLabel("Principle"); 4) Enter a value for n: <input type="text" name="val">
By using the DriverManager class, we can establish the connection to 7) JLabel lblRate = new JLabel("Rate"); 5) <input type="submit" value="Submit">
the database. By calling the getConnection(String url, String user,String 8) JLabel lblTime = new JLabel("Time"); 6) </form>
password) static factory method in DriverManager class, we can obtain 9) JLabel lblResult = new JLabel("Result"); 7) </body>
a Connection object. To get the connection object we need to proved 8) </html>
the connection url as a first parameter and database username and 10) JTextField txtPrinciple = new JTextField();
password as second and third parameters. 11) JTextField txtTime = new JTextField();
12) JTextField txtRate = new JTextField(); Factorial.jsp
3. Create a Statement 13) JTextField txtResult = new JTextField();
Create a Statement : In order to send the SQL commands to database 1) <html>
from our java program, we need Statement object. We can get the 14) SimpleIntrest() 2) <body>
Statement object by calling the createStatement() method on 15) { 3) <%!
connection. 16) setSize(400,500); 4) long n, result;
17) setTitle("Simple Intrest"); 5) String str;
4. Execute Sql queries 18) setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Inorder to execute the SQL commands on database, Statement interface 6) long fact(long n) {
provides provides three different methods: executeUpdate(), 19) setLayout(null); 7) if(n==0)
executeQuery() ,execute(). 8) return 1;
20) JButton btn = new JButton("Compute"); 9) else
5. Process the ResultSet 21) btn.addActionListener(this); 10) return n*fact(n-1);
For the select operations, we use executeQuery() method. The executed 11) }
query returns the data in the form of ResultSet object. To process the 22) lblPrinciple.setBounds(50,20,60,20); 12) %>
data we need to go through the ResultSet. 23) lblTime.setBounds(50,50,60,20); 13) <%
24) lblRate.setBounds(50,80,60,20); 14) str = request.getParameter("val");
6. Close Connection 25) lblResult.setBounds(50,110,60,20); 15) n = Long.parseLong(str);
Last but not least, finally we need to close the connection object. It is 16) result = fact(n);
very important step to close the connection. Else we may get 26) txtPrinciple.setBounds(150,20,100,20); 17) %>
JDBCConnectionException exception. 27) txtTime.setBounds(150,50,100,20); 18) <b>Factorial value: </b> <%= result %>
Conn.close(); 28) txtRate.setBounds(150,80,100,20); 19) </body>
29) txtResult.setBounds(150,110,100,20); 20) </html>
To connect java application with the mysql database, ==========================================================
mysqlconnector.jar file is 30) btn.setBounds(150,140,100,20); Creating Frames using Swings in Java with examples:
required to be loaded. Swing is a part of JFC (Java Foundation Classes). Building Graphical User
download the jar file mysql-connector.jar 31) add(lblPrinciple); Interface in Java requires the use of Swings. Swing Framework contains
32) add(lblTime); a large set of components that allow a high level of customization and
Example 33) add(lblRate); provide rich functionalities and is used to create window-based
import java.sql.*; 34) add(lblResult); applications.
import javax.swing.*; Java swing components are lightweight, platform-independent, provide
public class JDBCProgram { 35) add(txtPrinciple); powerful components like tables, scroll panels, buttons, lists, color
public static void main(String args[]) { 36) add(txtTime); chooser, etc. In this article, we’ll see how to make frames using Swings
try 37) add(txtRate); in Java. Ways to create a frame:
{ 38) add(txtResult); Methods:
//step-1 Load a JDBC Driver class • By creating the object of Frame class (association)
Class.forName("com.mysql.cj.jdbc.Driver"); 39) add(btn); • By extending Frame class (inheritance)
//step-2 Establish a Connection • Create a frame using Swing inside main()
Connection 40) setVisible(true);
conn=DriverManager.getConnection("jdbc:mysql://localhost:3307/tes 41) } JFrame Example
t"); 1) import java.awt.FlowLayout;
//step-3 Create a Statement 42) public void actionPerformed(ActionEvent ae) 2) import javax.swing.JButton;
Statement stmt=conn.createStatement(); 43) { 3) import javax.swing.JFrame;
String sql="select * from student"; 44) int p,t,r; 4) import javax.swing.JLabel;
//step-4 Execute Sql queries 45) float res; 5) import javax.swing.JPanel;
ResultSet rs=stmt.executeQuery(sql); 46) p = Integer.parseInt(txtPrinciple.getText()); 6) public class JFrameExample {
//step-5 Process the ResultSet 47) t = Integer.parseInt(txtTime.getText()); 7) public static void main(String s[]) {
while(rs.next()) 48) r = Integer.parseInt(txtRate.getText()); 8) JFrame frame = new JFrame("JFrame Example");
{ 49) res=(p*t*r)/100; 9) JPanel panel = new JPanel();
System.out.println(rs.getInt(2)+" "+rs.getString(3)+" 50) txtResult.setText(String.valueOf(res)); 10) panel.setLayout(new FlowLayout());
"+rs.getString(4)); 51) } 11) JLabel label = new JLabel("JFrame By Example");
} 12) JButton button = new JButton();
//step-6 Close Connection 52) public static void main(String args[]) 13) button.setText("Button");
conn.close(); 53) { 14) panel.add(label);
} 54) new SimpleIntrest(); 15) panel.add(button);
catch(Exception e) 55) } 16) frame.add(panel);
{ 56) } 17) frame.setSize(200, 300);
JOptionPane.showMessageDialog(null,e); ========================================================== 18) frame.setLocationRelativeTo(null);
} Differentiate between statement and prepared Statement, 19) frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOS
} Statement PreparedStatement E);
} It is used when SQL query is to It is used when SQL query is to be 20) frame.setVisible(true);
be executed only once. executed multiple times. 21) }
You can not pass parameters at 22) }
runtime. You can pass parameters at runtime.
Used for CREATE, ALTER, DROP Used for the queries which are to be Output:
statements. executed multiple times.
Performance is better than
Performance is very low. Statement.
=============================================== It is base interface. It extends statement interface.
Used to execute normal SQL Used to execute dynamic SQL
queries. queries.
We can not use statement for We can use Preparedstatement for
reading binary data. reading binary data.
It is used for DDL statements. It is used for any SQL Query.
We can not use statement for We can use Preparedstatement for
writing binary data. writing binary data.
No binary protocol is used for Binary protocol is used for
communication. communication.
Explain JCheckBOX and JRadio Button component of Java swing Write a JSP script for enabling and disabling session? 43) Vector v = new Vector();
library? <%@ page language="java" session="false"%> 44) while (rs.next()) {
Java JCheckBox <html> 45) ids = rs.getString(1);
The JCheckBox class is used to create a checkbox. It is used to turn an <head> 46) v.add(ids);
option on (true) or off (false). Clicking on a CheckBox changes its state <title>Session Disabled</title> 47) }
from "on" to "off" or from "off" to "on ".It inherits JToggleButton class. </head> 48) c1 = new JComboBox(v);
<body> 49) c1.setBounds(150, 110, 150, 20);
Java JCheckBox Example <p>Session is Disabled in this page 50) add(c1);
1) import javax.swing.*; </body> 51) st.close();
2) public class CheckBoxExample </html> 52) rs.close();
3) { 53) } catch (Exception e) {
4) CheckBoxExample(){ <%@ page language="java" session="true"%> 54) }
5) JFrame f= new JFrame("CheckBox Example"); <html> 55) }
6) JCheckBox checkBox1 = new JCheckBox("C++"); <head> 56) public void actionPerformed(ActionEvent ae) {
7) checkBox1.setBounds(100,100, 50,50); <title>Session Enabled</title> 57) if (ae.getSource() == b1) {
8) JCheckBox checkBox2 = new JCheckBox("Java", true); </head> 58) showTableData();
9) checkBox2.setBounds(100,150, 50,50); <body> 59) }
10) f.add(checkBox1); <p>Session is Enabled in this page 60) }
11) f.add(checkBox2); </body> 61) public void showTableData() {
12) f.setSize(400,400); </html> 62) frame1 = new JFrame("Database Search Result");
13) f.setLayout(null); ======================================================== 63) frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLO
14) f.setVisible(true); jsp form program to add two numbers . SE);
15) } index.html 64) frame1.setLayout(new BorderLayout());
16) public static void main(String args[]) <html> 65) //TableModel tm = new TableModel();
17) { <head> 66) DefaultTableModel model = new DefaultTableModel();
18) new CheckBoxExample(); <title>calculator </title> 67) model.setColumnIdentifiers(columnNames);
<meta charset=”UTF-8”>
19) }} 68) //DefaultTableModel model = new
<meta name=”viewportal” content = “width=device-width,initial-scale=1.0”>
DefaultTableModel(tm.getData1(),
</head>
Java JRadioButton <body> tm.getColumnNames());
The JRadioButton class is used to create a radio button. It is used to <form action =”add.jsp”> 69) //table = new JTable(model);
choose one option from multiple options. It is widely used in exam Enter first number : <input type=”text” name=”num1”><br><br> 70) table = new JTable();
systems or quiz. Enter second number:<input type=”text” name=”num2”><br><br> 71) table.setModel(model);
It should be added in ButtonGroup to select one radio button only. <input type=”submit” value=”sum”> 72) table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_CO
</body> LUMNS);
Java JRadioButton Example </html> 73) table.setFillsViewportHeight(true);
1) import javax.swing.*; 74) JScrollPane scroll = new JScrollPane(table);
2) public class RadioButtonExample { JSP for adding two number : add.jsp 75) scroll.setHorizontalScrollBarPolicy(
3) JFrame f; 76) JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
<html>
4) RadioButtonExample(){ 77) scroll.setVerticalScrollBarPolicy(
<head>
5) f=new JFrame(); <meta http-equiv="Content-type" content="text/html; charset=UTF-8"> 78) JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
6) JRadioButton r1=new JRadioButton("A) Male"); <title>JSP page for result sum </title> 79) from = (String) c1.getSelectedItem();
7) JRadioButton r2=new JRadioButton("B) Female"); </head> 80) //String textvalue = textbox.getText();
8) r1.setBounds(75,50,100,30); <body> 81) String uname = "";
9) r2.setBounds(75,100,100,30); <h1>sum</h1> 82) String email = "";
10) ButtonGroup bg=new ButtonGroup(); <%=”<h4>sum is “ + (Integer.parseInt(request.getParameter(“num1”))+ 83) String pass = "";
11) bg.add(r1);bg.add(r2); Integer.parseInt(request.getParameter(“num2”)))+”</h4>”%> 84) String cou = "";
12) f.add(r1);f.add(r2); </body> 85) try {
13) f.setSize(300,300); </html> 86) pst = con.prepareStatement("select * from emp where
14) f.setLayout(null); ========================================================== UNAME='" + from + "'");
15) f.setVisible(true); write a swing program to connect database and display 87) ResultSet rs = pst.executeQuery();
16) } student/employee details in Jtable. 88) int i = 0;
17) public static void main(String[] args) { 1) import java.awt.*; 89) if (rs.next()) {
18) new RadioButtonExample(); 2) import java.awt.event.*; 90) uname = rs.getString("uname");
19) } 3) import java.sql.*; 91) email = rs.getString("umail");
20) } 4) import java.util.Vector; 92) pass = rs.getString("upass");
========================================================== 5) import javax.swing.*; 93) cou = rs.getString("ucountry");
What is javabean ?how it is different from java class? 6) import javax.swing.table.DefaultTableModel; 94) model.addRow(new Object[]{uname, email, pass, cou});
A JavaBean is a Java class that follows a certain standard: 7) public class DisplayEmpData extends JFrame 95) i++;
• JavaBean class properties should be set to private – implements ActionListener { 96) }
accessing /mutating these properties is done using 8) JFrame frame1; 97) if (i < 1) {
getters/setters methods. 9) JLabel l0, l1, l2; 98) JOptionPane.showMessageDialog(null, "No Record
10) JComboBox c1; Found", "Error", JOptionPane.ERROR_MESSAGE);
• A JavaBean class should have a public no-argument
11) JButton b1; 99) }
constructor.
12) Connection con; 100) if (i == 1) {
• A JavaBean class should implement the
13) ResultSet rs, rs1; 101) System.out.println(i + " Record Found");
java.io.Serializable interface. The Serializable interface
14) Statement st, st1; 102) } else {
allows the saving, storing, and restoring of a JavaBean’s
15) PreparedStatement pst; 103) System.out.println(i + " Records Found");
state while in use.
16) String ids; 104) }
The only difference between both the classes is Java make java beans
17) static JTable table; 105) } catch (Exception ex) {
objects serialized so that the state of a bean class could be preserved in
18) String[] columnNames = {"User name", "Email", 106) JOptionPane.showMessageDialog(null, ex.getMessage(),
case required.So due to this a Java Bean class must either implements
"Password", "Country"}; "Error", JOptionPane.ERROR_MESSAGE);
Serializable or Externalizable interface.
19) String from; 107) }
20) DisplayEmpData() { 108) frame1.add(scroll);
Example of javabeans
21) l0 = new JLabel("Fatching Employee Information"); 109) frame1.setVisible(true);
public class Employee implements java.io.Serializable {
22) l0.setForeground(Color.red); 110) frame1.setSize(400, 300);
private int id;
23) l0.setFont(new Font("Serif", Font.BOLD, 20)); 111) }
private String name;
24) l1 = new JLabel("Select name"); 112) public static void main(String args[]) {
public Employee(){}
25) b1 = new JButton("submit"); 113) new Displaystudent Data();
public void setId(int id){this.id=id;}
26) l0.setBounds(100, 50, 350, 40); 114) }
public int getId(){return id;}
27) l1.setBounds(75, 110, 75, 20); 115) }
public void setName(String name){this.name=name;}
28) b1.setBounds(150, 150, 150, 20);
}
public String getName(){return name;}
29) b1.addActionListener(this); =========================
30) setTitle("Fetching Student Info From DataBase");
31) setLayout(null);
32) setVisible(true);
33) setSize(500, 500);
34) setDefaultCloseOperation(WindowConstants.EXIT_ON_
CLOSE);
35) add(l0);
36) add(l1);;
37) add(b1);
38) try {
39) Class.forName("oracle.jdbc.driver.OracleDriver");
40) con =
DriverManager.getConnection("jdbc:oracle:thin:@mcnd
esktop07:1521:xe", "sandeep", "welcome");
41) st = con.createStatement();
42) rs = st.executeQuery("select uname from emp");-------à
Write a swing program to get two number input using two text field 24) out.println("<td>"+rs.getString(2)+"</td>"); conn=DriverManager.getConnection("jdbc:mysql://localhost:3307/tes
and multiply it by clicking button and display it in third text field. 25) out.println("<td>"+rs.getString(3)+"</td>"); t","root","");
1) import java.awt.FlowLayout; 26) out.println("<td>"); String sql="delete from tblstd where RollNo=?";
2) import java.awt.event.*; 27) out.println("</td>"); PreparedStatement ptst=conn.prepareStatement(sql);
3) import javax.swing.*; 28) out.println("</tr>"); ptst.setInt(1,
4) public class MultiplyUsingSwing extends JFrame 29) } Integer.parseInt(txtRollno.getText()));
implements ActionListener { 30) out.println("</table> ptst.executeUpdate();
5) JLabel l1 = new JLabel("First No:"); 31) </body> if(ptst.getUpdateCount()>0)
6) JTextField t1 = new JTextField(10); 32) </html>") JOptionPane.showMessageDialog(null,"Data deleted
7) JLabel l2 = new JLabel("Second No:"); Successfully");
8) JTextField t2 = new JTextField(10); ========================================================== Found");
9) JTextField t3 = new JTextField(10); }}
10) JButton b = new JButton("Multiply"); );
11) String fno = ""; else
12) String sno = ""; JOptionPane.showMessageDialog(null,"Data not
13) public MultiplyUsingSwing() { conn.close();
14) setLayout(new FlowLayout()); }
15) setSize(250, 250); catch(Exception e)
16) setVisible(true); {
17) setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JOptionPane.showMessageDialog(null, ae);
18) add(l1); }
19) add(t1); btnUpdate.addActionListener(new ActionListener()
20) add(l2); {
import java.awt.event.*;
21) add(t2); public void actionPerformed(ActionEvent ae)
import javax.swing.*;
22) t3.setEditable(false); {
import javax.swing.event.*;
23) add(t3); try
import java.sql.*;
24) add(b); {
public class AllOp
25) b.addActionListener(this); Class.forName("com.mysql.cj.jdbc.Driver");
{
26) } Connection
AllOp() {
27) @Override conn=DriverManager.getConnection("jdbc:mysql://localhost:3307/tes
JFrame f=new JFrame();
28) public void actionPerformed(ActionEvent e) { t","root","");
JLabel lblRollno=new JLabel("Roll Number");
29) int f = Integer.parseInt(t1.getText()); String sql="update tblstd set
lblRollno.setBounds(10, 10, 150, 20);
30) int s = Integer.parseInt(t2.getText()); RollNo=?,Name=?,Address=? where RollNo=?";
f.add(lblRollno);
31) int r = f * s; PreparedStatement ptst=conn.prepareStatement(sql);
JTextField txtRollno=new JTextField();
32) t3.setText("" + r); ptst.setInt(1,
txtRollno.setBounds(100, 10, 150, 20);
33) } Integer.parseInt(txtRollno.getText()));
f.add(txtRollno);
34) public static void main(String[] args) { ptst.setString(2, txtName.getText());
JLabel lblName=new JLabel("Name");
35) new MultiplyUsingSwing(); ptst.setString(3, txtAddress.getText());
lblName.setBounds(10, 40, 150, 20);
36) } ptst.setInt(4,
f.add(lblName);
37) } Integer.parseInt(txtRollno.getText()));
JTextField txtName=new JTextField();
========================================================== ptst.executeUpdate();
txtName.setBounds(100, 40, 150, 20);
Write a swing program to read two input user using input dialog and if(ptst.getUpdateCount()>0)
f.add(txtName);
sum those values and display it using message dialog. JOptionPane.showMessageDialog(null,"Data Updated
JLabel lblAddress=new JLabel("Address");
1) /* Successfully");
lblAddress.setBounds(10, 70, 150, 20);
2) To change this license header, choose License Headers found");
f.add(lblAddress);
in Project Properties. else
JTextField txtAddress=new JTextField();
3) To change this template file, choose Tools | Templates JOptionPane.showMessageDialog(null,"Data not
txtAddress.setBounds(100, 70, 150, 20);
4) and open the template in the editor. conn.close();
f.add(txtAddress);
5) */ }
JButton btnInsert=new JButton("Insert");
6) package inputdialogexample; catch(Exception e)
btnInsert.setBounds(20, 110, 80, 20);
7) import javax.swing.*; {
f.add(btnInsert);
8) /** JOptionPane.showMessageDialog(null, ae);
JButton btnDelete=new JButton("Delete");
9) * }
btnDelete.setBounds(110, 110, 80, 20);
10) @author DELL }}
f.add(btnDelete);
11) */ );
JButton btnUpdate=new JButton("Update");
12) public class InputDialogExample { btnSearch.addActionListener(new ActionListener()
btnUpdate.setBounds(200, 110, 80, 20);
{
f.add(btnUpdate);
13) /** public void actionPerformed(ActionEvent ae)
JButton btnSearch=new JButton("Search");
14) @param args the command line arguments {
btnSearch.setBounds(290, 110, 80, 20);
15) */ try
f.add(btnSearch);
16) public static void main(String[] args) { {
btnInsert.addActionListener(new ActionListener()
17) int num,num1; Class.forName("com.mysql.cj.jdbc.Driver");
{
18) num=Integer.parseInt(JOptionPane.showInputDialog(" Connection
public void actionPerformed(ActionEvent ae)
Enter first values")); conn=DriverManager.getConnection("jdbc:mysql://localhost:3307/tes
{
19) num1=Integer.parseInt(JOptionPane.showInputDialog(" t","root","");
try
Enter second values")); String sql="select * from tblstd where RollNo=?";
{
20) JOptionPane.showMessageDialog(null,(num+num1)); PreparedStatement ptst=conn.prepareStatement(sql);
Class.forName("com.mysql.cj.jdbc.Driver");
21) } ptst.setInt(1,
Connection
Integer.parseInt(txtRollno.getText()));
conn=DriverManager.getConnection("jdbc:mysql://localhost:3307/tes
22) } ResultSet rs=ptst.executeQuery();
t","root","");
========================================================== if(rs.next())
String sql="insert into tblStd
Write a servlet program to select students id name age from student {
(ID,RollNo,Name,Address) values(NULL,?,?,?)";
table and display in html table. txtName.setText(rs.getString("Name"));
PreparedStatement ptst=conn.prepareStatement(sql);
txtAddress.setText(rs.getString("Address"));
ptst.setInt(1,
1) public void doGet(HttpServletRequest req, }
Integer.parseInt(txtRollno.getText()));
HttpServletResponse res) else
ptst.setString(2, txtName.getText());
2) throws ServletException,IOException{ {
ptst.setString(3, txtAddress.getText());
3) res.setContentType("text/html"); Found");
ptst.executeUpdate();
4) PrintWriter out=res.getWriter(); }
if(ptst.getUpdateCount()>0)
5) //selecting data }}
JOptionPane.showMessageDialog(null,"Data inserted
6) try { );
Successfully");
7) Connection conn=DbConnection.getConn(); JOptionPane.showMessageDialog(null,"Data not
conn.close();
8) String sql="SELECT * FROM employees"; conn.close();
}}
9) PreparedStatement pst=conn.prepareStatement(sql); }
);
10) ResultSet rs=pst.executeQuery(); catch(Exception e)
}
11) out.println("<html><body>"); {
catch(Exception e)
12) out.println("<a href='index.html'> JOptionPane.showMessageDialog(null, ae);
{
13) Goto Index </a> <br><br>"); }
JOptionPane.showMessageDialog(null, ae);
14) //displaying data f.setSize(400,500);
}
15) out.println("<table>"); f.setLayout(null);
btnDelete.addActionListener(new ActionListener()
16) out.println("<tr>"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
{
17) out.println("<th> Eid </th>"); f.setVisible(true);
public void actionPerformed(ActionEvent ae)
18) out.println("<th> Name </th>"); }
{
19) out.println("<th> Address </th>"); public static void main(String args[])
try
20) out.println("</tr>"); {
{
21) while(rs.next()) { new AllOp();
Class.forName("com.mysql.cj.jdbc.Driver");
22) out.println("<tr>"); }}
Connection
23) out.println("<td>"+rs.getInt(1)+"</td>"); ==========================================================
How JSP is differing from servlet? Write JSP program to display " 13) JInternalFrame frame1 = new JInternalFrame("Frame 1", Difference between session and cookie. WAP ti implement session.
Tribhuvan University" 10 times. true, true, true,
Session Cookie
Servlets are faster as compared to JSP, as they have a short response 14) true);
time. JSP is slower than Servlets, as the first step in the JSP lifecycle is 15) JInternalFrame frame2 = new JInternalFrame("Frame 2",
the conversion of JSP to Java code and then the compilation of the code. true, true, true, Server side files that contain Client side files on a local
Servlets are Java-based codes. JSP are HTML-based codes. In Servlet we 16) true); user data computer that hold user
have to implement everything like business logic and presentation logic 17) frame1.getContentPane().add(new JLabel("Frame 1 information
in just one servlet file.In JSP business logic is separated from contents..."));
presentation logic by using JavaBeansclient-side. 18) frame1.pack(); It can hold an indefinite It can only store a certain
19) frame1.setVisible(true); quantity of data amount of info.
Program: 20) frame2.getContentPane().add(new JLabel("Frame 2
<!DOCTYPE html> contents..."));
They are more secured. They are not secured.
<html> 21) frame2.pack();
<head> 22) frame2.setVisible(true);
<meta http-equiv=“Content-Type” content=“text/htm; charset=UTF- 23) int x2 = frame1.getX() + frame1.getWidth() + 10; Store data in text file. Save data in encrypted form.
8”> 24) int y2 = frame1.getY();
<title> JSP program to display “Tribhuvan University” 10 25) frame2.setLocation(x2, y2); They have maximum They have maximun memory of
times</title> 26) desktopPane.add(frame1); capacity of 4KB 128KB
</head> 27) desktopPane.add(frame2);
<body> 28) this.add(desktopPane, BorderLayout.CENTER); 1) import java.io.*;
<h1> Displaying “Tribhuvan University” 10 times!!</h1> 29) this.setMinimumSize(new Dimension(300, 300)); 2) import java.util.*;
<table> 30) } 3) import javax.servlet.*;
<% 31) public static void main(String[] args) { 4) import javax.servlet.http.*;
for(int i=1; i<=10; i++){ 32) try { 5) @WebServlet("/test_session")
%> 33) UIManager.setLookAndFeel(UIManager.getSystemLook 6) public class TestSessionServlet extends HttpServlet {
<tr><td> Tribhuvan University</td></tr> AndFeelClassName()); 7) private static final long serialVersionUID = 1L;
<% } %> 34) } catch (Exception e) { 8) public TestSessionServlet() {
</table> 35) e.printStackTrace(); 9) super();
</body> 36) } 10) }
</html> 37) SwingUtilities.invokeLater(() -> { 11) protected void doGet(HttpServletRequest request,
========================================================== 38) Main frame = new Main(); HttpServletResponse response)
How to develop MDI application on java explain? 39) frame.pack(); 12) throws ServletException, IOException {
MDI stands for Multiple Document Interface. In an MDI application, one 40) frame.setVisible(true); 13) HttpSession session = request.getSession();
main window is opened, and multiple child windows are open within the 41) frame.setExtendedState(frame.MAXIMIZED_BOTH); 14) PrintWriter writer = response.getWriter();
main window. 42) }); 15) writer.println("Session ID: " + session.getId());
In an MDI application, we can open multiple frames that will be 43) } 16) writer.println("Creation Time: " + new
instances of the JInternalFrame class. 44) } Date(session.getCreationTime()));
We can organize multiple internal frames in many ways. For example, ========================================================== 17) writer. println("Last Accessed Time: " + new
we can maximize and minimize them; we can view them side by side in What are JTextField and JTextArea in Java? Date(session.getLastAccessedTime()));
a tiled fashion, or we can view them in a cascaded form. JTextField 18) }
The following are four classes we will be working with in an MDI A JTextFeld is one of the most important components that allow the user 19) }
application: to an input text value in a single line format. A JTextField will generate ==========================================================
• JInternalFrame an ActionListener interface when we trying to enter some input inside WAP to calculate sum of any two number using rmi.
• JDesktopPane it. The important methods in the JTextField class are setText(), getText(), 1) Adder.interface
setEnabled(), etc. 2) import java.rmi.Remote;
• DesktopManager
3) import java.rmi.RemoteException;
• JFrame 4) public interface Adder extends Remote{
An instance of the JInternalFrame class acts as a child window that is Example 5) void Add(Integer a,Integer b) throws RemoteException;
displayed inside the area of its parent window. 1) import javax.swing.*; 6) }
We can add Swing components to JInternalFrame content pane, pack 2) import java.awt.*; 7) ImplExample.java
3) public class JTextFieldTest {
them using the pack() method, and make it visible using the 8) public class ImplExample implements Adder{
4) public static void main(String[] args) { 9) ImplExample()
setVisible(true) method.
5) final JFrame frame = new JFrame("JTextField Demo"); 10) {
To listen to window events such as activated, deactivated, etc., we need 6) JLabel lblFirstName = new JLabel("First Name:");
to add an InternalFrameListener to the JInternalFrame instead of a 11) super();
7) JTextField tfFirstName = new JTextField(20); 12) }
WindowListener, which is used for a JFrame. 8) lblFirstName.setLabelFor(tfFirstName); 13) public void Add(Integer x,Integer y) {
The following code shows how to use an instance of the JInternalFrame 9) JLabel lblLastName = new JLabel("Last Name:"); 14) System.out.println("sum = "+(x+y));
class: 10) JTextField tfLastName = new JTextField(20); 15) }
String title = "A Child Window"; 11) lblLastName.setLabelFor(tfLastName); 16) }
Boolean resizable = true; 12) JPanel panel = new JPanel(); 17) ServerRMI.java
Boolean closable = true; 13) panel.setLayout(new FlowLayout()); 18) import java.rmi.registry.Registry;
Boolean maximizable = true; 14) panel.add(lblFirstName); 19) import java.rmi.registry.LocateRegistry;
15) panel.add(tfFirstName); 20) import java.rmi.RemoteException;
Boolean iconifiable = true;
16) panel.add(lblLastName); 21) import java.rmi.server.UnicastRemoteObject;
JInternalFrame iFrame = new JInternalFrame(title, resizable, closable,
17) panel.add(tfLastName); 22) public class ServerRMI extends ImplExample{
maximizable, iconifiable); 18) frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Add components to the iFrame using public ServerRMI() {}
19) frame.setSize(300, 100); public static void main(String args[]) {
iFrame.add(...) 20) frame.getContentPane().add(panel, BorderLayout.CENTER); try {
Pack eth frame and make it visible 21) frame.setVisible(true); 23) ImplExample obj = new ImplExample();
iFrame.pack(); 22) } 24) Hello skeleton =(Hello)
iFrame.setVisible(true); 23) } UnicastRemoteObject.exportObject(obj, 0);
JDesktopPane is used as a container for all JInternalFrame. It uses a null 25) Registry registry = LocateRegistry.getRegistry();
layout manager. JTextArea 26) registry.bind("RMITest",skeleton);
JDesktopPane desktopPane = new JDesktopPane(); A JTextArea is a multi-line text component to display text or allow the user to 27) System.err.println("server Ready");
enter text. A JTextArea will generate a CaretListener interface. 28) }
// Add all JInternalFrames to the desktopPane
The important methods in the JTextArea class are setText(), append(), 29) catch(Exception e) {
desktopPane.add(iFrame);
setLineWrap(), setWrapStyleWord(), setCaretPosition(), etc. 30) System.err.println("Server Exception:"+ e.toString());
We can get all JInternalFrames that are added to a JDesktopPane using Example
its getAllFrames() method. 31) e.printStackTrace();
1) import java.awt.*; 32) }
JInternalFrame[] frames = desktopPane.getAllFrames(); 2) import javax.swing.*; 33) }
A JDesktopPane uses an instance of the DesktopManager interface to 3) import javax.swing.event.*; 34) }
manage all internal frames. 4) public class JTextAreaTest { 35) ClientRMI.java
The DefaultDesktopManager implements DesktopManager interface. 5) public static void main(String args[]) { 36) import java.rmi.registry.LocateRegistry;
The desktop manager has many useful methods. For example, to close 6) JFrame frame = new JFrame("JTextArea Example"); 37) import java.rmi.registry.Registry;
an internal frame programmatically, use its closeFrame() method. 7) frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 38) public class ClientRMI{
desktopPane.getDesktopManager().closeFrame(frame1); 8) JTextArea textArea = new JTextArea(); 39) private ClientRMI() {}
9) JScrollPane scrollPane = new JScrollPane(textArea); 40) public static void main(String[] args) {
10) frame.add(scrollPane, BorderLayout.CENTER); 41) try {
The following code demonstrates how to develop an MDI application.
11) CaretListener listener = new CaretListener() { 42) Registry registry = LocateRegistry.getRegistry();
1) import java.awt.BorderLayout; 12) public void caretUpdate(CaretEvent caretEvent) {
2) import java.awt.Dimension; 43) Hello stub = (Hello) registry.lookup("RMITest");
13) System.out.println("Dot: "+ caretEvent.getDot()); 44) stub.Add(5,10);
3) /*from w w w. j av a2 s. co m*/ 14) System.out.println("Mark: "+caretEvent.getMark()); 45) }
4) import javax.swing.JDesktopPane; 15) } 46) catch(Exception e) {
5) import javax.swing.JFrame; 16) }; 47) System.err.println("Client Exception:"+e.toString());
6) import javax.swing.JInternalFrame; 17) textArea.addCaretListener(listener); 48) }
7) import javax.swing.JLabel; 18) frame.setSize(250, 150); 49) }
8) import javax.swing.SwingUtilities; 19) frame.setVisible(true); 50) }
9) import javax.swing.UIManager; 20) } ===============================================================
21) }
10) public class Main extends JFrame {
11) private final JDesktopPane desktopPane = new
==============================================================
JDesktopPane();
12) public Main() {
Write a swing program to show color panel using dialog box Write a GUI program to create table , insert and show 38) san..getDefaultCloseOperation (Frame. EXIT_ON_CLOSE);
to get color. product information which include id, name and price. 39) }
1. import java.awt.Color; o import java.sql.*; 40) public void actionPerformed(ActionEvent e){
2. import java.awt.event. o public class CreateProductTable{ 41) if(e.getsource).equals(btnregister)){
3. import javax.swing.*; o public static void main (String [] args){ 42) JOptionPane.showMessageDialog(frame,”you have
4. public class ShowColor implements ActionListener o try{ registered your information”);
5. Button btn; o Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriv 43) String tname=txtname.getText();
6. Color color; er"); 44) taddress=txtaddress.getText()
7. Panel panel; o String DB URL="jdbc: sqlserver://<usernames> \\ 45) String taddress=txtaddress.getText():
8. Frame frame; SQLEXPRESS2:1433;databaseName=BCA 46) String tlevel=txtlevel.getText():
9. public void showColor() { ;integratedSecurity=true;”; 47) createNewForm (tame, taddress,tlevel):
10. panel=new JPanel () ; o Connection con = DriverManager. getConnection( DB URL) ; 48) }
11. panel.setBackground (color) ; o System. out.println ("Database connected..."); 49) void createNewForm(String tname,String address, String
12. btn=new JButton ("Change color') ; o Statement statement = con.createStatement () ; tlevel){
13. btn.addActionlistener (this) ; o String sql="CREATE TABLE PRODUCT (ID VARCHAR (10) , 50) lblname = new JLabel (“Name:”);
14. panel.add (btn); NAME VARCHAR (30) , PRICE FLOAT, PRIMARY KEY (ID)) ;"; 51) lbladdress = new JLabel(“Address:”);
15. Frame = New JFrame(“sample frame”); o statement.executeUpdate ( sql); 52) lbllevel = new JLabel(“Level:);
16. frame.getContentPane () .add (panel) ; o } 53) lname= new JLabel();
17. frame.setSize (500, 500) ; o catch ( Exception e) 54) laddress=newJLabel();
18. frame.setLocationRelativeTo(null); o { 55) llevel =newJLabel();
19. frame.setVisible (true) ; o e.printstackTrace(); 56) Iname.setText (tname) :
20. frame.setDefaultCloseOperation (JFrame.EXIT ON CLOSE); o }}} 57) laddress.setText(taddress):
21. } o public class InsertProduct{ 58) llevel.setText(tlevel);
23. Public void actionPerformed(ActionEvent e) o public static void main (String[ ] args)( 59) lblname.setBounds (10, 20, 80, 25) ;
25. Color = JColorChooser.showDialog(frame,”choose a color o try{ 60) lbladdress.setBounds (10, 60,80,25);
“, color ); o String DB URL="jdbc:sqlserver: / /<username>\ 61) lbllevel.setBounds (10, 100,80,25);
26. If (color =null). color=color.LIGTH_GRAY; \(SQLEXPRESS 2: 1433; databaseName-BCA; 62) lblname.setBounds(100,20,160,25);
28. panel.setBackground(color); integratedSecurity=true;"; 63) lbladdress.setBounds (10, 60,80,25);
29. } o Connection con = DriverManager. getConnection( DB_URL) ; 64) level.setBounds(100,100,160,25);
30. public static void main (String args[]){ o System. out.println ("Database connected") ; 65) JPanel panel =new JPanel();
31. ShowColor show=new ShowColor(); o Statement statement = con.createStatement(); 66) panel.setLayout(null);
32. show. showColor(); o String sql="INSERT INTO PRODUCT VALUES ('A102', 'pant', 67) panel.setLayout(null);
33. } 950) ; "; 68) panel.add(lblname);
34. } o statement. executeUpdate ( sql): 69) panel.add(lbladdress);
================================================== o Catch (Exception e) 70) panel.add(lbllevel);
Write a program to show font. o { 71) panel.add(lname);
o e.printStackTrace(); 72) panel.add(laddress);
1) import java.awt.Color; o } 73) panel.add(llevel);
2) import java.awt.Font; o } 74) JFrame frame = new JFrame (“Data entry Form…”);
3) import java.awt.Graphics; o } 75) frame.add (panel);
4) import javax.swing.JPanel; o public class ViewProduct{ 76) frame.setSize(300,240);
5) public Class Fonts { o public static void main (String[]args){ 77) frame.setlocationRelativeTo (null) ;
6) public static void main (String args[]) o try{ 78) frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
7) { o Class. 79) frame.setVisible (true) ;
8) JFrame frame=new Frame ("Font styles..”); forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); 80) }
9) frame.add (new FontExample()); o String DB URL="idbc: sqlserver://<username>\\ 81) Public static void main (Sting args[]){
10) frame.setSize(480,150); SQLEXPRESS2:1433; 82) InformationformForm info=new InformationForm() ;
11) frame.setlocationRelativeTo(null) ; databaseName=BCA;integratedSecurity-true;"; 83) info.createForm();
12) frame.setDefaultCloseOperation(JFrame.EXIT ON o Connection con = DriverManager. getConnection( DB_URL) ; 84) }
CLOSE) ; o System. out.println ("Database connected...") ; 85) }
13) frame. getVisible(true); o Statement statement= con. createStatement () ; ===============================================================
14) } o String sql="SELECT * FROM PRODUCI;"; Write servlet program to add two number.
15) } o ResultSet rs=statement.executeQuery (sql) ; Index.html
16) public class FontExample extends JPanel{ o String id,name,price; <!DOCTYPE html>
17) public void paint (Graphics g) { o while(rs.next()) <html>
18) g.setFont (new Font ("Arial", Font.BOLD, 12)) ; o { <head>
19) g.drawString ("This is a sample text", 20, 30) ; o id= rs.getString(“ID”); <title>Practical Work</title>
20) g. setFont (new Font ("Serif",Font.ITALIC, 18)) ; o name=rs.getString(“Name”); </head>
21) g. drawString ("This is another sample text", 20, 60); o Price = rs.getString(“PRICE”); <body>
22) g. setColor (Color.RED) o System.out.println(id+”\t”+name+”\”+price); <form action="add_me">
23) g.setFont (new Font ("Monospaced", Font.BOLD, 20) ) o } <label>First number </label> <input type="text" name="num1"/> <br/><br/>
; o }catch (Exception e ) <label>Second number </label> <input type="text" name="num2"/>
24) g. drawString ("This is again, another sample text", o { <br/><br/>
20, 90) : o e.printStackTrack(); <button type="submit" name="calculate">Product and Sum </button><br/>
25) } o } </form>
26) } o } </body>
================================================== o } </html>
Write program to create Different shapes. ==================================================
1) import java.awt.Color; Write a program using jdbc to enter and display data to the Add_Numbers.java
2) import java.awt.Graphics; database. package com.programmerbay;
3) import javax.swing.JPanel; 1) Import javax. swing.*; import java.io.IOException;
4) public class DrawShapes 2) Import java.awt.event.*; import java.io.PrintWriter;
5) { 3) public class InformationForm implements ActionListener{
6) public static void main (String args[]) 4) JLabel lblname, lbladdress, lbllevel, Iname, laddress, llevel; import javax.servlet.http.*;
7) { 5) JTextfield txtname, txtaddress,txtlevel; public class Add_Numbers extends HttpServlet{
8) Frame frame=new Frame ("Sample shapes."); 6) JButton btnregister; public void service(HttpServletRequest request,HttpServletResponse
9) frame.add(new Draw()); 7) JPanel panel; response) throws IOException
10) frame.setSize (400, 200) . 8) Jfarme frame; {
11) frame. setLocationRelativeTo (null); 9) void createForm() { int num1 = Integer.parseInt(request.getParameter("num1"));
12) frame.setDefaultCloseOperation (JFrame.EXIT ON 10) lblname= new JLabel(“Name”); int num2 = Integer.parseInt(request.getParameter("num2"));
CLOSE) ; 11) Lbladress= new JLabel(“address:”); int sum = num1 + num2;
13) frame.setvisible(true) 12) Lbllevel = new JLabel(“Level:”); int product = num1 * num2;
14) } 13) txtname = new JTextField(); PrintWriter output = response.getWriter();
15) } 14) txtadress = new JtextField(10); output.println("The Answer :"+sum +"\n The product :"+product);
16) public class Draw extends JPanel{ 15) txtlevel =new JTextField(10); }
17) public void paint (Graphics g) { 16) btnregister = newButton ( “register”); }
18) g. setColor (Color.RED) ; 17) btnregister.addActionlistener(this); Web.xml
19) g. drawLine(5,30,380,30); 18) lblname.setBounds(10,20,80,25); <?xml version="1.0" encoding="UTF-8"?>
20) g. setColor (Color. BLUE) ; 19) lbladdress.setBounds(10,60,80,25); <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
21) g. drawRect (5,40, 90,55) : 20) lbllevel.setBounds(10,100,80,25) ; xmlns="http://xmlns.jcp.org/xml/ns/javaee"
22) g. fillRect (100, 40, 90,55) ; 21) txtname. setBounds(100, 20,160,25); xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
23) g.setColor (Color. GREEN) 22) txtaddress.setBounds(100,100,160,25); http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID"
24) g. drawOval (195, 40, 90, 23) txtlevel.setBounds(100,100,160,25); version="3.1">
25) g. filloval (290, 40, 90, 55) : 24) btnregister.setBounds(100,150,80,25);
26) g. setColor (Color. CYAN) ; 25) JPanel panel=new Jpanel(); <servlet>
27) g. fillOval (5, 100, 90, 90) ; 26) panel.setlayout(null); <servlet-name>Add</servlet-name>
28) } 27) panel.ad(lblname); <servlet-class>com.programmerbay.Add_Numbers</servlet-class>
29) } 28) panel.add (lbladdress); </servlet>
=============================================================== 29) panel.add (lbllevel); <servlet-mapping>
30) panel.add (txtname); <servlet-name>Add</servlet-name>
31) panel.add (txtaddress); <url-pattern>/add_me</url-pattern>
32) panel.add (txtlevel); </servlet-mapping>
33) panel.add (btnregister); </web-app>
34) JFrame= new uFrame ("Data entry Form frame….”); ===============================================================
35) frame.add (panel); ======
36) frame. setSize(300,240);
37) frame.setlocationRelativeTo(null):

You might also like