Important Announcement
PubHTML5 Scheduled Server Maintenance on (GMT) Sunday, June 26th, 2:00 am - 8:00 am.
PubHTML5 site will be inoperative during the times indicated!

Home Explore MCA631_Advanced Internet Programming

MCA631_Advanced Internet Programming

Published by Teamlease Edtech Ltd (Amita Chitroda), 2020-12-05 14:21:54

Description: MCA631_Advanced Internet Programming

Search

Read the Text Version

42 Advanced Internet Programming JRadioButton r3=new JRadioButton(\" }} BBI\"); ButtonGroupbg=new ButtonGroup(); Output: 2.17 Jlist This is a box like component that displays text-items in multiple rows. List items are usually scrollable . Constructors JList() JList(s) where ‘s ’is a string array. Methods getSelectedValue() To retrieve the selected item setSelectedValue(object o, Boolean s) To set an item In order to use the above methods we have to implement the ListSelectionListener. Example import javax.swing.*; JList l=new JList(s); import java.io.*; p.add(l); class listdemo f.add(p); { f.setSize(300,300); public static void main(String arg[]) f.setVisible(true); { f.setDefaultCloseOperation(JFrame.EXIT_ON_CL JFrame f=new JFrame(\"list demo\"); OSE); JPanel p=new JPanel(); }} String s[]={\"Dbms\",\"Java\",\"Linux\",\"OS\"}; Output CU IDOL SELF LEARNING MATERIAL (SLM)

User Interface Components 43 2.18 JcomboBox This class represents the combobox which is a pull down list with the capability of displaying the selected item in a display area. The swing ComboBox is an enhancement of the AWTcomponent call choice. Constructors JComboBox() void addItem(Object obj) JcomboBox(vector v) where ‘v’ is a vector.Items to the ComboBox where ‘obj’ is the object that is added to the ComboBox. Example b.addItem(s3); b.addItem(s4); import javax.swing.*; p.add(l); import java.io.*; p.add(b); class comboboxdemo f.add(p); { f.setSize(200,200); public static void main(String arg[]) f.setVisible(true); { f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOS JFrame f=new JFrame(\" frame window \"); E); JPanel p=new JPanel(); } JLabel l=new JLabel(\"cities\"); String s1=\"Mumbai\"; Output String s2=\"Nagpur\"; String s3=\"Pune\"; String s4=\"Delhi\"; JComboBox b=new JComboBox(); b.addItem(s1); b.addItem(s2); 2.19 JMenu and JPopupMenu Class JMenuBar An implementation of a menu bar. You add JMenu objects to the menu bar to construct a menu. When the user selects a JMenu object, its associated JPopup Menu is displayed, allowing the user to select one of the JMenu Items on it. CU IDOL SELF LEARNING MATERIAL (SLM)

44 Advanced Internet Programming JMenu A menu provides a space-saving way to let the user choose one of several options. Other components with which the user can make a one-of-many choice include combo boxes, lists, radio buttons, spinners, and tool bars. If any of your menu items performs an action that is duplicated by another menu item or by a tool-bar button, then in addition to this section you should read How to Use Actions. Menus are unique in that, by convention, they aren’t placed with the other components in the UI. Instead, a menu usually appears either in a menu bar or as a popup menu. A menu bar contains one or more menus and has a customary, platform-dependent location — usually along the top of a window. A popup menu is a menu that is invisible until the user makes a platform- specific mouse action, such as pressing the right mouse button, over a popup-enabled component. The popup menu then appears under the cursor. Constructor or Method Purpose JMenu() Creates a menu. The string specifies the text to display JMenu(String) for the menu. TheActionspecifies the text and other JMenu(Action) properties of the menu (seeHow to Use Actions). Dsd Description Appends the specified menu to the end of the menu bar. Method OverridesJComponent.addNotifyto register this menu bar JMenuadd(JMenu) with the current keyboard manager. voidaddNotify() Description Gets the Accessible Context associated with this dsd JMenuBar. Implemented to be aMenu Element. Method AccessibleContextgetAccessibleContext() ComponentgetComponent() Popup Menu A popup menu is a free-floating menu which associates with an underlying component. This component is called the invoker. Most of the time, popup menu is linked to a specific component to display context-sensitive choices. In order to create a popup menu, you use the class JPopupMenu. You then can add menu items JMenu Item to popup menu like normal menu. To display the popup menu, you call method show(). Normally popup menu is called in response to a mouse event. CU IDOL SELF LEARNING MATERIAL (SLM)

User Interface Components 45 Example: import javax.swing.JButton; JMenuItem pasteMenuItem = new import javax.swing.JFrame; JMenuItem(\"Paste\"); import javax.swing.JMenuItem; pasteMenuItem.setEnabled(false); import javax.swing.JPopupMenu; popupMenu.add(pasteMenuItem); public class PopupMenuExample // Separator { popupMenu.addSeparator(); public static void main(final String args[]) { // Find JFrame frame = new JFrame(\"Popup Menu JMenuItem findMenuItem = new Example\"); JMenuItem(\"Find\"); frame.setDefaultCloseOperation(JFrame.EXIT_ON popupMenu.add(findMenuItem); _CLOSE); JButton label = new JButton(); // Create popup menu, attach popup menu listener frame.add(label); JPopupMenu popupMenu = new label.setComponentPopupMenu(popupMenu); JPopupMenu(\"Title\"); frame.setSize(350, 250); // Cut frame.setVisible(true); JMenuItem cutMenuItem = new JMenuItem(\"Cut\"); }} popupMenu.add(cutMenuItem); // Copy Output: JMenuItem copyMenuItem = new JMenuItem(\"Copy\"); popupMenu.add(copyMenuItem); // Paste 2.20 JMenuItem and JCheckBoxMenuItem JMenuItem An implementation of an item in a menu. A menu item is essentially a button sitting in a list. When the user selects the “button”, the action associated with the menu item is performed. A JMenuItem contained in a JPopupMenu performs exactly that function. Menu Items are added using JMenuItem. CU IDOL SELF LEARNING MATERIAL (SLM)

46 Advanced Internet Programming Constructors JMenu(String label,boolean off) JMenuItem(String s) JMenu() JMenu(String label) where s represents name of menu item. Example submenu.add(m5); menu1.add(submenu); import java.awt.*; mbar.add(menu1); class AWTMenu extends Frame menu2=new Menu(\"Edit\"); { m6=new MenuItem(\"Undo\"); MenuBar mbar; m7=new MenuItem(\"Redo\"); Menu menu1,submenu,menu2,menu3; menu2.add(m6); MenuItem menu2.add(m7); m1,m2,m3,m4,m5,m6,m7,m8,m9; mbar.add(menu2); public AWTMenu() menu3=new Menu(\"Help\"); { m8=new MenuItem(\"About Us\"); setTitle(\"AWT Menu\"); menu3.add(m8); setSize(400,400); mbar.add(menu3); setLayout(new FlowLayout()); setMenuBar(mbar); setVisible(true); } setLocationRelativeTo(null); public static void main(String args[]) mbar=new MenuBar(); { menu1=new Menu(\"File\"); new AWTMenu(); submenu=new Menu(\"Color\"); }} m1=new MenuItem(\"New\"); m2=new MenuItem(\"Save clt+s\" ); Output m3=new MenuItem(\"Save as\"); m4=new MenuItem(\"Red\"); m5=new MenuItem(\"Blue\"); m9=new MenuItem(\"Exit\"); menu1.add(m1); menu1.add(m2); menu1.add(m3); menu1.add(m9); submenu.add(m4); CU IDOL SELF LEARNING MATERIAL (SLM)

User Interface Components 47 JCheckBox-MenuItem A menu item that can be selected or deselected. If selected, the menu item typically appears with a checkmark next to it. If unselected or deselected, the menu item appears without a checkmark. Like a regular menu item, a check box menu item can have either text or a graphic icon associated with it, or both. Eitheris Selected set Selected or get State/set State can be used to determine/specify the menu item’s selection state. The preferred methods are is Selected and set Selected, which work for all menus and buttons. The get State and setState methods exist for compatibility with other component sets. For further information and examples of using check box menu items, see How to Use Menus, a section in The Java Tutorial. For the keyboard keys used by this component in the standard Look and Feel (L&F) renditions, see the JCheckBox MenuItem key assignments Constructor Description JCheckBoxMenuItem() Creates an initially unselected check box menu item with no set text or icon. JCheckBoxMenuItem(Action) Creates a menu item whose properties are taken from the Action supplied. JCheckBoxMenuItem(Icon) Creates an initially unselected check box menu item with an icon. JCheckBoxMenuItem(String) Creates an initially unselected check box menu item with text. Description Ds Method AccessibleContextgetAccessibleCon Get the Accessible Context associated with this JComponent text() Returns an array (length 1) containing the check box menu Object[]getSelectedObjects() item label or null if the check box is not selected. booleangetState() Returns the selected-state of the item. String paramString() Returns a string representation of this JCheckBoxMenuItem. 2.21 JRadioButtonMenuItem An implementation of a radiobutton menu item. AJRadioButton Menu Item is a menu item that is part of a group of menu items in which only one item in the group can be selected. The selected item displays its selected state. Selecting it causes any other selected item to switch to the CU IDOL SELF LEARNING MATERIAL (SLM)

48 Advanced Internet Programming unselected state. To control the selected state of a group of radio button menu items, use a Button Group object. For further documentation and examples see How to Use Menus, a section in The Java Tutorial. For the keyboard keys used by this component in the standard Look and Feel (L&F) renditions, see the JRadioButton MenuItemkey assignments. Constructor Description JRadioButtonMenuItem() JRadioButtonMenuItem(Action) Creates aJRadioButton Menu Itemwith no set text or icon. JRadioButtonMenuItem(Icon) Creates a radio button menu item whose properties are taken JRadioButtonMenuItem(Icon,boolean) from theAction supplied. Ds Creates aJRadioButton Menu Itemwith an icon. Method Creates a radio button menu item with the specified image AccessibleContextgetAccessibleConte and selection state, but no text. xt() StringgetUIClassID() Description Returns theAccessible Context associated with this StringparamString() JRadioButton Menu Item. Returns the name of the L&F class that renders this voidrequestFocus() component. Returns a string representation of this JRadioButton Menu Item. OverridesComponent. requestFocusto not grab focus. 2.22 JScrollBar Scroll bars are used to select continuous values between a specified minimum and maximum. Scroll bars may be oriented horizontally or vertically. A scroll bar is actually a composite of several individual parts. Each end has an arrow that you can click to move the current value of the scroll bar one unit in the direction of the arrow. The current value of the scroll bar relative to its minimum and maximum values is indicated by the slider box (or thumb) for the scroll bar. The slider box can be dragged by the user to a new position. The scroll bar will then reflect this value. In the background space on either side of the thumb, the user can click to cause the thumb to jump in that direction by some increment larger than 1. This action translates into some form of page up and page down. Scroll bars are encapsulated by the Scrollbar class. Scrollbar defines the following constructors: CU IDOL SELF LEARNING MATERIAL (SLM)

User Interface Components 49 1. Scrollbar( ) 2. Scrollbar(int style) 3. Scrollbar(int style, int initial Value, int thumb Size, int min, int max) The first form creates a vertical scroll bar. The second and third forms allow you to specify the orientation of the scroll bar. If style is Scrollbar. VERTICAL, a vertical scroll bar is created. If style is Scrollbar. HORIZONTAL, the scroll bar is horizontal. In the third form of the constructor, the initial value of the scroll bar is passed in initial Value. The number of units represented by the height of the thumb is passed in thumb Size. The minimum and maximum values for the scroll bar are specified by min and max. If you construct a scroll bar by using one of the first two constructors, then you need to set its parameters by using set Values( ), shown here, before it can be used: void setValues(int initialValue, int thumbSize, int min, int max) The parameters have the same meaning as they have in the third constructor just described. To obtain the current value of the scroll bar, call getValue( ). It returns the current setting. To set the current value, call setValue( ). These methods are as follows: 1. int getValue( ) 2. void setValue(intnewValue) Here, new Value specifies the new value for the scroll bar. When you set a value, the slider box inside the scroll bar will be positioned to reflect the new value. You can also retrieve the minimum and maximum values via getMinimum( ) and getMaximum( ), shown here: 1. int getMinimum( ) 2. int getMaximum( ) They return the requested quantity. By default, 1 is the increment added to or subtracted from the scroll bar each time it is scrolled up or down one line. You can change this increment by calling set UnitIncrement( ). By CU IDOL SELF LEARNING MATERIAL (SLM)

50 Advanced Internet Programming default, page-up and page-down increments are 10. You can change this value by calling set BlockIncrement( ). These methods are shown here: 1. void setUnitIncrement(intnewIncr) 2. void setBlockIncrement(intnewIncr) Handling Scroll Bars To process scroll bar events, you need to implement the Adjustment Listener interface. Each time a user interacts with a scroll bar, an Adjustment Event object is generated. Its getAdjustmentType( ) method can be used to determine the type of the adjustment. 2.23 Dialogs (Message, Confirmation, Input) The JOptionPane class is used to provide standard dialog boxes such as message dialog box, confirm dialog box and input dialog box. These dialog boxes are used to display information or get input from the user. The JOptionPane class inherits JComponent class. Common Constructors of JOptionPane class JOptionPane() :- It is used to create a JOptionPane with a test message. JOptionPane(Object message) :- It is used to create an instance of JOptionPane to display a message. JOptionPane(Object message, int messageType) :- It is used to create an instance of JOptionPane to display a message with specified message type and default options. Common Methods of JOptionPane class JDialog createDialog(String title): It is used to create and return a new parentless JDialog with the specified title. static void show MessageDialog(Component parentComponent, Object message): It is used to create an information-message dialog titled “Message”. static void showMessageDialog(Component parentComponent, Object message, String title, int messageType) :- It is used to create a message dialog with given title and message Type. static int showConfirmDialog(Component parentComponent, Object message): It is used to create a dialog with the options Yes, No and Cancel; with the title, Select an Option. static String showInputDialog(Component parentComponent, Object message): It is used to show a question-message dialog requesting input from the user parented to parentComponent. CU IDOL SELF LEARNING MATERIAL (SLM)

User Interface Components 51 void setInputValue(Object newValue): It is used to set the input value that was selected or input by the user. 1. Where Component: The first parameter is a component which determines the Frame in which the dialog is displayed; if null, or if the parentComponent has no Frame, a default Frame is used. 2. Object: The second parameter can be any objects.(In some older versions of Java you might get a compiler error when using primitive types directly). 3. String: The third parameter is a String placed as the title of the message dialog window. 4. Int: The int that follows the String is the Message Type. The different Message Types for JOptionPane, are:  ERROR_MESSAGE  INFORMATION_MESSAGE  WARNING_MESSAGE  QUESTION_MESSAGE  PLAIN_MESSAGE 5. Icon: The last parameter is an Icon that is displayed inside the dialog and overrides the default MessageType icon. Java JOptionPane Example: showMessageDialog() import javax.swing.JOptionPane; Output: public class SimpleDialog1 { public static void main(String[] args){ JOptionPane.showMessageDialog(null, \"Simple Information Message\"); } } Java JOptionPane Example: pdated.\",\"Alert\",JOptionPane.WARNING_M showMessageDialog() ESSAGE); } import javax.swing.*; publicstaticvoidmain(String[]args) { public class OptionPaneExample { newOptionPaneExample(); JFrame f; }} OptionPaneExample() { f=newJFrame(); JOptionPane.showMessageDialog(f,\"SuccessfullyU CU IDOL SELF LEARNING MATERIAL (SLM)

52 Advanced Internet Programming Output: Java JOptionPane Example: publicstaticvoidmain(String[]args){ newOptionPaneExample(); showInputDialog() }} import javax.swing.*; Output: public class OptionPaneExample{ JFrame f; OptionPaneExample() { f=newJFrame(); Stringname=JOptionPane.showInputDialog(f,\"EnterNa me\"); } Java JOptionPane Example: f.setVisible(true); showConfirmDialog() } public void windowClosing(WindowEvent e) import javax.swing.*; { import java.awt.event.*; int public class OptionPaneExample extends a=JOptionPane.showConfirmDialog(f,\"Arey WindowAdapter { ousure?\"); JFrame f; OptionPaneExample() { if(a==JOptionPane.YES_OPTION){ f=newJFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ f.addWindowListener(this); ON_CLOSE); f.setSize(300,300); }} f.setLayout(null); f.setDefaultCloseOperation(JFrame.DO_NOTHING public static void main(String[]args) { _ON_CLOSE); new OptionPaneExample(); }} CU IDOL SELF LEARNING MATERIAL (SLM)

User Interface Components 53 Output: 2.24 JFileChooser A JFileChooser is a dialog to select a file or files. The return value of the three methods is one of the following: JFileChooser.CANCEL_OPTION, if the user clicks Cancel. JFileChooser.APPROVE_OPTION, if the user click an OK/Open/Save button. JFileChooser.ERROR_OPTION, if the user closes the dialog JFileChooser has supporting classes: FileFilter class, FileSystemView class, FileView. FileFilter class is for restricting files and directories to be listed in the FileView of the JFileChooser. The FileView controls how the directories and files are listed within the JFileChooser. The FileSystemView is an abstract class that tries to hide file system-related operating system specifics from the file chooser. Example: import javax.swing.JFileChooser; this.getContentPane().add(fileChooser); fileChooser.setVisible(true); import javax.swing.JFrame; } public static void main(String[] args) public class filechooser extends JFrame { { JFrame frame = new filechooser(); public filechooser() Jframe.setDefaultCloseOperation(JFrame.EXIT_ON_ CLOSE); { frame.pack(); frame.setVisible(true); JFileChooser fileChooser = new }} JFileChooser(); fileChooser.setDialogTitle(\"Choose a file\"); CU IDOL SELF LEARNING MATERIAL (SLM)

54 Advanced Internet Programming Output: 2.25 JColorChooser The JColorChooser class is used to create a color chooser dialog box so that user can select any color. Constructors JColorChooser(): is used to create a color chooser pane with white color initially. JColorChooser(Color initialColor): is used to create a color chooser pane with the specified color initially. Methods public static Color showDialog(Component c, String title, Color initialColor): is used to show the color-chooser dialog box. Example: import java.awt.event.*; public static void main(String[] args) { import java.awt.*; JColorChooserdemo ch=new import javax.swing.*; JColorChooserdemo(); public class JColorChooserdemo extends ch.setSize(400,400); JFrame implements ActionListener{ ch.setVisible(true); JButton b; ch.setDefaultCloseOperation(EXIT_ON_CLOSE); Container c; }} CU IDOL SELF LEARNING MATERIAL (SLM)

User Interface Components 55 JColorChooserdemo(){ Output: c=getContentPane(); c.setLayout(new FlowLayout()); b=new JButton(\"Colordemo\"); b.addActionListener(this); c.add(b); } public void actionPerformed(ActionEvent e) { Color initialcolor=Color.RED; Color color=JColorChooser.showDialog(this,\"Select a color\",initialcolor); c.setBackground(color); } 2.26 Practical Assignment 1. Develop a swing application to accept empno, name and salary details. 2. Develop a swing application to display BIO-DATA. 2.27 Summary A component is an independent visual control. Swing Framework contains a large set of components which provide rich functionalities and allow high level of customization. They all are derived from JComponent class. All these components are lightweight components. This class provides some common functionality like pluggable look and feel, support for accessibility, drag and drop, layout, etc. A container holds a group of components. It provides a space where a component can be managed and displayed. Containers are of two types: 1. Top level Containers  It inherits Component and Container of AWT.  It cannot be contained within other containers.  Heavyweight.  Example: JFrame, JDialog, JApplet CU IDOL SELF LEARNING MATERIAL (SLM)

56 Advanced Internet Programming 2. Lightweight Containers  It inherits JComponent class.  It is a general purpose container.  It can be used to organize related components together.  Example: JPanel 2.28 Key Words/Abbreviations  Event: An event in Java is an object that is created when something changes within a graphical user interface.  Listener: Listeners. A user interface listener is a method which is called when the user does something (eg, click a button) that the programmer has indicated they want to be notified of 2.29 Learning Activity 1. what is JFC? ----------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------- 2. Differentiate between AWT and SWING. ----------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------- 2.30 Unit End Questions (MCQs and Descriptive) A. Descriptive Types Questions 1 Explain MVC Architecture 2. List and explain different Layout Manager 3. Write note on SWING 4. Write Difference between AWT and Swing 5. Explain SWING FEATURES 6 Explain JButton with suitable example 7. Explain JLabel with suitable example CU IDOL SELF LEARNING MATERIAL (SLM)

User Interface Components 57 8. Explain JText with suitable example 9. Explain JTextArea with suitable example 10. Explain JcheckBox with suitable example 11. Explain JradioButton with suitable example 12. Explain Jlist with suitable example 13. Explain JcomboBox with suitable example 14. Explain JMenuItem with suitable example 15. Explain JMenu with suitable example 16. Explain JPopupMenu with suitable example 17. Explain JCheckBoxMenuItem with suitable example 18. Explain JRadioButtonMenuItem with suitable example 19. Explain JscrollBar with suitable example 20. Explain different Dialogs boxes with suitable example 21. Explain JFileChooser with suitable example 22. Explain JcolorChooser with suitable example B. Multiple Choice/Objective Type Questions 1. Public void pack() is use to __________ frame. (a) resize (b) display (c) pack (d) position 2. The GridLayout Breaks the GUI up into __________ and __________. (a) Rows and Columns (b) Rows and Data (c) Columns and Data (d) Horizontal and vertical gaps 3. swing Componnets are also known as __________. (a) Light Weight (b) Heavy Weight (c) Medium Weight (d) Good Weight 4. JFrame Class has __________ Methods. (a) 3 (b) 2 (c) 5 (d) 7 CU IDOL SELF LEARNING MATERIAL (SLM)

58 Advanced Internet Programming 5. Swing Classes supports __________. (a) JComponet (b) AWT Componet Frame (c) AWT tool (d) Answers 1. (d), 2. (a), 3. (a), 4. (b), 5. (a) 2.31 References 1. https://www.startertutorials.com/corejava/introduction-to-swing.html 2. https://www.javatpoint.com/java-swing 3. Dave Wood, Marc Loy, and Robert Eckstein, “Java Swing”. CU IDOL SELF LEARNING MATERIAL (SLM)

UNIT 3 EVENT HANDLING Structure: 3.0 Learning Objectives 3.1 Introduction 3.2 Event Delegation Model 3.3 Events 3.4 AWT Event 3.5 Event Listener Interfaces 3.6 Event Handling in Java with mouse and keyboard 3.7 Different Types of Event in Java AWT 3.8 Adapter Classes 3.9 Swing Components 3.10 Container class 3.11 Practical Assignment 3.12 Summary 3.13 Key Words/Abbreviations 3.14 Learning Activity 3.15 Unit End Questions (MCQs and Descriptive) 3.16 References CU IDOL SELF LEARNING MATERIAL (SLM)

60 Advanced Internet Programming 3.0 Learning Objectives After studying this unit, you will be able to:  Define sources, listeners  Discuss mouse and keyboard event handling  Describe adapters, swing and container class 3.1 Introduction Event: Change in the state of an object is known as event i.e. event describes the change in state of source. Events are generated as result of user interaction with the graphical user interface components. For example, clicking on a button, moving the mouse, entering a character through keyboard, selecting an item from list, scrolling the page are the activities that causes an event to happen. Event Handling is the mechanism that controls the event and decides what should happen if an event occurs. This mechanism have the code which is known as event handler that is executed when an event occurs. Java Uses the Delegation Event Model to handle the events. 3.2 Event Delegation Model The Delegation Event Model The modern approach to handling events is based on the delegation event model, which defines standard and consistent mechanisms to generate and process events. Its concept is quite simple: 1. Source generates an event and sends it to one or more listeners. 2. The listener simply waits until it receives an event. Once received, the listener processes the event and then returns. 3. The advantage of this design is that the application logic that processes events is cleanly separated from the user interface logic that generates those events. 4. A user interface element is able to delegate the processing of an event to a separate piece of code. 5. In the delegation event model, listeners must register with a source in order to receive an event notification. CU IDOL SELF LEARNING MATERIAL (SLM)

Event Handling 61 6. This provides an important benefit: notifications are sent only to listeners that want to receive them. Event Manger Event Objects AddListener(); removeListener(); //called when event generated fireEvent(); Event Listeners The methods addlistener() and remove Listener() has to be used to register and be register to the event All the listeners will Event Source be registering to a Event through the Event Manager ActionPerformed(){ This method will be called by Event Source is ................ the event manager, when the responsible for ................. event will get generated. The .................. API user has to implement this generating the } method in the listener class events Fig. 3.1: Event Delegation Model Events In the delegation model, an event is an object that describes a state change in a source. It can be generated as a consequence of a person interacting with the elements in a graphical user interface. Some of the activities that cause events to be generated are pressing a button, entering a character via the keyboard, selecting an item in a list, and clicking the mouse. Many other user operations could also be cited as examples. Events may also occur that are not directly caused by interactions with a user interface. 3.1.1 Event Sources A source is an object that generates an event. This occurs when the internal state of that object changes in some way. Sources may generate more than one type of event. A source must register listeners in order for the listeners to receive notifications about a specific type of event. Each type of event has its own registration method. Here is the general form: CU IDOL SELF LEARNING MATERIAL (SLM)

62 Advanced Internet Programming public void addTypeListener(Type Listener el) Type is the name of the event and el is a reference to the event listener. The method that registers a keyboard event listener is called addKeyListener(). The method that registers a mouse motion listener is called addMouseMotionListener( ). When an event occurs, all registered listeners are notified and receive a copy of the event object know as multicasting the event In all cases, notifications are sent only to listeners that register to receive them. Some sources may allow only one listener to register. General Form: public void addTypeListener(TypeListener el) throws java.util. TooManyListenersException Type is the name of the event and el is a reference to the event listener. When such an event occurs, the registered listener is notified. This is known as uni casting the event. A source must also provide a method that allows a listener to unregister an interest in a specific type of event. The general form of such a method is this: public void removeTypeListener(TypeListener el) 3.1.2 Event Listeners A listener is an object that is notified when an event occurs. It has two major requirements. First, it must have been registered with one or more sources to receive notifications about specific types of events. Second, it must implement methods to receive and process these notifications. The methods that receive and process events are defined in a set of interfaces found in java.awt.event. For example, the MouseMotionListener interface defines two methods to receive notifications when the mouse is dragged or moved. Any object may receive and process one or both of these events if it provides an implementation of this interface. Event Classes The Event classes represent the event. Java provides us various Event classes but we will discuss those which are more frequently used. It is the root class from which all event state objects shall be derived. All Events are constructed with a reference to the object, the source, that is logically deemed to be the object upon which the Event in question initially occurred upon.This class is defined in java.util package. CU IDOL SELF LEARNING MATERIAL (SLM)

Event Handling 63 Event Object(Object src) Here, src is the object that generates this event. Event Object contains two methods: getSource( ) and toString( ). The getSource( ) method returns the source of the event. Its general form is shown here: Object getSource( ) 3.3 Events Events are the integral part of the java platform. You can see the concepts related to the event handling through the example and use methods through which you can implement the event driven application. For any event to occur, the objects registers themselves as listeners. No event takes place if there is no listener i.e., nothing happens when an event takes place if there is no listener. No matter how many listeners there are, each and every listener is capable of processing an event. ActionListener can be implemented by any Class including Applet. One point to remember here is that all the listeners are always notified. Moreover, you can also call AWTEvent.consume() method whenever you don’t want an event to be processed further. There is another method which is used by a listener to check for the consumption. The method is isConsumed( ) method. The processing of the events gets stopped with the consumption of the events by the system once a listener is notified. Consumption only works for InputEvent and its subclasses. Moreover, if you don’t want any input from the user through keyboard then you can useconsume( ) method for the KeyEvent. The step by step procedure of Event handling is as follow: 1. When anything interesting happens then the subclasses of AWTEvent are generated by the component. 2. Any class can act like a Listener class permitted by the Event sources. For example, addActionListener() method is used for any action to be performed, where Action is the event type. There is another method by which you can remove the listener class which is removeXXXListener() method, where XXX is the event type. 3. A listener type has to be implemented for an event handling such as ActionListener. 4. There are some special type of listener types as well for which you need to implement multiple methods like key Events. There are three methods which are required to be implemented for Key events and to register them i.e., one for key release, key typed and one for key press. There are some special classes as well which are known as adapters that are used to implement the listener interfaces and stub out all the methods. CU IDOL SELF LEARNING MATERIAL (SLM)

64 Advanced Internet Programming 3.4 AWT Event Most of the times every event-type has Listener interface as Events subclass the AWTEvent class. However, PaintEvent and InputEvent don’t have the Listener interface because only the paint() method can be overriden with PaintEvent etc. Low-level Events A low-level input or window operation is represented by the Low-level events. Types of Low-level events are mouse movement, window opening, a key press etc. For example, three events are generated by typing the letter ‘A’ on the Keyboard one for releasing, one for pressing, and one for typing. The different type of low-level events and operations that generate each event are show below in the form of a table. FocusEvent Table 3.1: Different Type of Low-level Events Used for Getting/losing focus. MouseEvent Used for entering, exiting, clicking, dragging, moving, pressing, or releasing. ContainerEvent Used for Adding/removing component. KeyEvent Used for releasing, pressing, or typing (both) a key. WindowEvent Used for opening, deactivating, closing, Iconifying, deiconifying, really closed. ComponentEvent Used for moving, resizing, hiding, showing. Semantic Events The interaction with GUI component is represented by the Semantic events like changing the text of a text field, selecting a button etc. The different events generated by different components is shown below. Table 3.2: The Different Events Generated by Different Components ItemEvent Used for state changed. ActionEvent Used for do the command. TextEvent Used for text changed. AdjustmentEvent Used for value adjusted. Event Sources If a component is an event source for something then the same happens with its subclasses. The different event sources are represented by the following table. CU IDOL SELF LEARNING MATERIAL (SLM)

Event Handling 65 Window Table 3.3: Low-level Events Container WindowListener Component ContainerListener Scrollbar ComponentListener, FocusListener, KeyListener MouseListener, MouseMotionListener Table 3.4: Semantic Events AdjustmentListener TextArea, TextField TextListener Button, List, MenuItem, TextField ActionListener Choice, Checkbox, Checkbox, CheckboxMenuItem List ItemListener 3.5 Event Listeners Every listener interface has at least one event type. Moreover, it also contains a method for each type of event the event class incorporates. For example as discussed earlier, the KeyListener has three methods, one for each type of event that the KeyEvent has: keyTyped(), keyPressed(), and keyReleased(). The Listener interfaces and their methods are as follow: Interface Table 3.5: The Listener Interfaces and their Methods Methods windowActivated(WindowEvent e) windowDeiconified(WindowEvent e) windowOpened(WindowEvent e) WindowListener windowClosed(WindowEvent e) windowClosing(WindowEvent e) windowIconified(WindowEvent e) ActionListener windowDeactivated(WindowEvent e) AdjustmentListener actionPerformed(ActionEvent e) adjustmentValueChanged(AdjustmentEvent e) MouseListener mouseClicked(MouseEvent e) CU IDOL SELF LEARNING MATERIAL (SLM)

66 Advanced Internet Programming FocusListener mouseEntered(MouseEvent e) ItemListener mouseExited(MouseEvent e) KeyListener mousePressed(MouseEvent e) mouseReleased(MouseEvent e) ComponentListener focusGained(FocusEvent e) focusLost(FocusEvent e) itemStateChanged(ItemEvent e) keyReleased(KeyEvent e) keyTyped(KeyEvent e) keyPressed(KeyEvent e) componentHidden(ComponentEvent e) componentMoved(ComponentEvent e) componentShown(ComponentEvent e) componentResized(ComponentEvent e) MouseMotionListener mouseMoved(MouseEvent e) mouseDragged(MouseEvent e) TextListener textValueChanged(TextEvent e) ContainerListener componentAdded(ContainerEvent e) componentRemoved(ContainerEvent e) 3.6 Event Handling In Java with Mouse and Keyboard In this section you will learn about how to handle events in Java. Events in any programming language specifies the external effects that happens and your application behaves according to that event. For example, an application produce an output when a user inputs some data, or the data received from the network or it may be something else. In Java when you works with the AWT components like button, textbox, etc. (except panel, label) generates an event. This event is handled by the listener. Event listener listens the event generated on components and performs the corresponding action. In Java event handling may comprised the following four classes: CU IDOL SELF LEARNING MATERIAL (SLM)

Event Handling 67 1. Event Sources: Sources for generating an event may be the components. In Java java.awt.Component specifies the components that may or may not generate events. These components classes are the subclass of the above class. These event sources may be the button, combobox, textbox etc. 2. Event Classes: Event Classes in Java are the classes defined for almost all the components that may generate events. These events classes are named by giving the specific name such as for the component source button the event class is ActionEvent. Following are the list of Event Classes:  ActionEvent: Button, TextField, List, Menu  WindowEvent: Frame  ItemEvent: Checkbox, List  AdjustmentEvent: Scrollbar  MouseEvent: Mouse  KeyEvent: Keyboard 3. Event Listeners: Event Listeners are the Java interfaces that provides various methods to use in the implemented class. Listeners listens the event generated by a component. In Java almost all components has its own listener that handles the event generated by the component. For example, there is a Listener named ActionListener handles the events generated from button, textfield, list, menus. 4. Event Adapters: Event Adapters classes are abstract class that provides some methods used for avoiding the heavy coding. Adapter class is defined for the listener that has more than one abstract methods. 5. Here I am giving a simple example which will demonstrate you about how to handle an event. In this example we will give a simple example into which you will see how an event generated after clicking on the button is handled. To handle the event you would have to implement a corresponding listener and add the listener on the component i.e. button. Then you have to override the method declared in the listener. You can add the listener by following ways: b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { CU IDOL SELF LEARNING MATERIAL (SLM)

68 Advanced Internet Programming b = (JButton)ae.getSource(); sayHi(); } }); In the second way you can add listener as follows: b.addActionListener(this) publi void actionPerformed(ActionEvent ae){ b = (JButton)ae.getSource(); sayHi(); } 3.7 Different Types of Event in Java AWT Introduction There are many types of events that are generated by your AWT Application. These events are used to make the application more effective and efficient. Generally, there are twelve types of event are used in Java AWT: 1. ActionEvent: This is the ActionEvent class extends from the AWTEvent class. It indicates the component-defined events occurred i.e., the event generated by the component like Button, Checkboxes etc. The generated event is passed to every EventListener objects that receives such types of events using the addActionListener() method of the object. 2. AdjustmentEvent: This is the AdjustmentEvent class extends from the AWTEvent class. When the Adjustable Value is changed then the event is generated. 3. ComponentEvent: ComponentEvent class also extends from the AWTEvent class. This class creates the low-level event which indicates if the object moved, changed and it’s states (visibility of the object). This class only performs the notification about the state of the object. The ComponentEvent class performs like root class for other component-level events. 4. ContainerEvent: The ContainerEvent class extends from the ComponentEvent class. This is a low-level event which is generated when container’s contents changes because of addition or removal of a components. CU IDOL SELF LEARNING MATERIAL (SLM)

Event Handling 69 5. FocusEvent: The FocusEvent class also extends from the ComponentEvent class. This class indicates about the focus where the focus has gained or lost by the object. The generated event is passed to every objects that is registered to receive such type of events using the addFocusListener() method of the object. 6. InputEvent: The InputEvent class also extends from the ComponentEvent class. This event class handles all the component-level input events. This class acts as a root class for all component-level input events. 7. ItemEvent: The ItemEvent class extends from the AWTEvent class. The ItemEvent class handles all the indication about the selection of the object i.e. whether selected or not. The generated event is passed to every ItemListener objects that is registered to receive such types of event using the addItemListener() method of the object. 8. KeyEvent: KeyEvent class extends from the InputEvent class. The KeyEvent class handles all the indication related to the key operation in the application if you press any key for any purposes of the object then the generated event gives the information about the pressed key. This type of events check whether the pressed key left key or right key, ‘A’ or ‘a’ etc. 9. MouseEvent: MouseEvent class also extends from the InputEvent class. The MouseEvent class handle all events generated during the mouse operation for the object. That contains the information whether mouse is clicked or not if clicked then checks the pressed key is left or right. 10. PaintEvent: PaintEvent class also extends from the ComponentEvent class. The PaintEvent class only ensures that the paint() or update() are serialized along with the other events delivered from the event queue. 11. TextEvent: TextEvent class extends from the AWTEvent class. TextEvent is generated when the text of the object is changed. The generated events are passed to every TextListener object which is registered to receive such type of events using the addTextListener() method of the object. 12. WindowEvent: WindowEvent class extends from the ComponentEvent class. If the window or the frame of your application is changed (Opened, closed, activated, deactivated or any other events are generated), WindowEvent is generated. CU IDOL SELF LEARNING MATERIAL (SLM)

70 Advanced Internet Programming 3.8 Adapter Classes An adapter class provides the default implementation of all methods in an event listener interface. Adapter classes are very useful when you want to process only few of the events that are handled by a particular event listener interface. You can define a new class by extending one of the adapter classes and implement only those events which is relevant. There are some event listeners that have multiple methods to implement. That is some of the listener interfaces contain more than one method. For instance, the MouseListener interface contains five methods such as mouse Clicked, mouse Pressed, mouse Released etc. If you want to use only one method out of these then also you will have to implement all of them. Thus, the methods which you do not want to care about can have empty bodies. To avoid such thing, we have adapter class. Adapter classes help us in avoiding the implementation of the empty method bodies. Generally an adapter class is there for each listener interface having more than one method. For instance, the Mouse Adapter class implements the MouseListener interface. An adapter class can be used by creating a subclass of it and then overriding the methods which are of use only. Hence avoiding the implementation of all the methods of the listener interface. The following example shows the implementation of a listener interface directly. Example of MouseAdapter import java.awt.*; f.setVisible(true); import java.awt.event.*; } public class MouseAdapterExample extends public void mouseClicked(MouseEvent e) { MouseAdapter { Graphics g=f.getGraphics(); Frame f; g.setColor(Color.BLUE); MouseAdapterExample(){ g.fillOval(e.getX(),e.getY(),30,30); f=new Frame(\"Mouse Adapter\"); } f.addMouseListener(this); public static void main(String[] args) { f.setSize(300,300); new MouseAdapterExample(); f.setLayout(null); }} CU IDOL SELF LEARNING MATERIAL (SLM)

Event Handling 71 3.9 Swing Components Swing Framework contains a large set of components which provide rich functionalities and allow high level of customization. All these components are lightweight components. They all are derived from JComponent class. It supports the pluggable look and feel. Swing Components Example with Event Handling: Buttton with ActionListener: import java.awt.*; tf.setText(\"Welcome to cbs college\"); import java.awt.event.*; } import java.swing.*; }); public class Buttondemo { f.add(b);f.add(tf); public static void main(String[] args) { f.setSize(400,400); JFrame f=new JFrame(\"Button Example\"); f.setLayout(null); final JTextField tf=new JTextField(); f.setVisible(true); tf.setBounds(50,50, 150,20); }} JButton b=new JButton(\"Click Here\"); b.setBounds(50,100,60,30); Output: b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { 3.10 Container Class When you create an application, initially you should have a base container and you have to add the required components like buttons and text fields in the container. And when you click or perform any operation on any fields, the event will occur and your code should listen to the events and also handle the event. Swing Container A container is a root element for an Application. All the other components are added to that root and it forms a hierarchy. There are three container classes:  JDialog  JApplet  JFrame CU IDOL SELF LEARNING MATERIAL (SLM)

72 Advanced Internet Programming Example of JFrame: import java.awt.FlowLayout; panel.add(button); import javax.swing.JButton; frame.add(panel); import javax.swing.JFrame; frame.setSize(200, 300); import javax.swing.JLabel; frame.setLocationRelativeTo(null); import javax.swing.Jpanel; frame.setDefaultCloseOperation(JFrame.EXIT_ON public class JFrameExample { _CLOSE); frame.setVisible(true); public static void main(String s[ ]) { } JFrame frame = new JFrame(\"JFrame Exam } ple\"); JPanel panel = new JPanel(); Output: panel.setLayout(new FlowLayout()); JLabel label = new JLabel(\"JFrame By Exam ple\"); JButton button = new JButton(); button.setText(\"Button\"); panel.add(label); Example of JDialog: f.add(p); // java Program to create a simple JDialog f.setSize(400, 400); import java.awt.event.*; import java.awt.*; f.show(); } import javax.swing.*; class solve extends JFrame implements public void actionPerformed(ActionEvent ActionListener { e) { static JFrame f; String s = e.getActionCommand(); public static void main(String[] args) { if (s.equals(\"click\")) { // create a new frame f = new JFrame(\"frame\"); JDialog d = new JDialog(f, \"dialog solve s = new solve(); Box\"); JPanel p = new JPanel(); JButton b = new JButton(\"click\"); JLabel l = new JLabel(\"this is a dialog b.addActionListener(s); box\"); p.add(b); d.add(l); Output: d.setSize(100, 100); d.setVisible(true); } }} CU IDOL SELF LEARNING MATERIAL (SLM)

Event Handling 73 Example of JApplet: prsMe.addActionListener(this); } answr.addActionListener(this); import javax.swing.*; import java.awt.*; public void actionPerformed(ActionEvent e) import java.awt.event.*; public class JHello2JavaExample extends JApplet { implements ActionListener { String name = answr.getText(); JLabel Grtng = new JLabel(\"Hello. Who are you?\"); cntnr.remove(Grtng); Font FntOne = new Font(\"Arial\", Font.BOLD, 36) Font FntTwo = new Font(\"Arial\", Font.ITALIC, 48); cntnr.remove(PrsMe); JTextField answr = new JTextField(10); JButton PrsMe = new JButton(\"Press me\"); cntnr.remove(answr); JLabel PrsnlGrtng = new JLabel(\" \"); Container cntnr = getContentPane( ); PrsnlGrtng.setText(\"Hello, \" + name + \"! \"); public void init( ) { cntnr.add(PrsnlGrtng); Grtng.setFont(FntOne); PrsnlGrtng.setFont(FntTwo); cntnr.setBackground(Color.CYAN); cntnr.add(Grtng); cntnr.add(answr); validate(); cntnr.add(PrsMe); cntnr.setLayout(new FlowLayout()); } cntnr.setBackground(Color.YELLOW); } Output 3.11 Practical Assignment 1. Develop AWT Application which accepts name of User through textbox and one Button, set flowlayout for desigining and on click of Button Welcome to name typed in text box. 2. Develop a Java application to demonstrate all mouse movements Like click, mouse move etc. 3.12 Summary Any program that uses GUI (graphical user interface) such as Java application written for windows, is event driven. Event describes the change in state of any object. For Example: Pressing a button, Entering a character in Textbox, Clicking or Dragging a mouse, etc. CU IDOL SELF LEARNING MATERIAL (SLM)

74 Advanced Internet Programming 3.13 Key Words/Abbreviations  pluggable look and feel: Pluggable look and feel is a mechanism used in the Java Swing widget toolkit allowing to change the look and feel of the graphical user interface at runtime.The look and feel can be changed at runtime.  JComponent : JComponent is an abstract class that almost all Swing components extend; it provides much of the underlying functionality common throughout the Swing component library 3.14 Learning Activity 1. Explain container class ----------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------- 2. What is event handling ----------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------- 3.15 Unit End Questions (MCQs and Descriptive) A. Descriptive Types Questions 1. Write short notes on Event Delegation Model 2. Different types of event in Java AWT 3. What are Events and Event Classes ? 4. Explain how Event Handling is done in Java 5. What are Adapter classes ? 6. What are AWT Events Explain? 7. Explain Need of swing Components. 8. Explain different Swing components. 9. Explain AWT and Swing Components. 10. Explain Container class. CU IDOL SELF LEARNING MATERIAL (SLM)

Event Handling 75 B. Multiple Choice/Objective Type Questions 1. Which of these packages contains all the classes and methods required for even handling in Java? (a) java.applet (b) java.awt (c) java.event (d) java.awt.event 2. Which of these methods are used to register a keyboard event listener? (a) KeyListener() (b) addKistener() (c) addKeyListener() (d) eventKeyboardListener() 3. Which is the container that doesn’t contain title bar and MenuBars but it can have other components like button, textfield etc? (a) Window (b) Frame (c) Panel (d) Container 4. Which method is used to set the graphics current color to the specified color in the graphics class? (a) public abstract void setFont(Font font) (b) public abstract void setColor(Color c) (c) public abstract void drawString(String str, int x, int y) (d) None of the above 5. Which object can be constructed to show any number of choices in the visible window? (a) Labels (b) Choice (c) List (d) Checkbox Answers 1. (d), 2. (c), 3. (c), 4. (b), 5. (c) 3.16 References 1. https://www.studytonight.com/java/event-handling-in-java.php 2. https://www.javatpoint.com/java-swing 3. Java AWT Reference by John Zukowski CU IDOL SELF LEARNING MATERIAL (SLM)

UNIT 4 JAVA SERVLETS - I Structure: 4.0 Learning Objectives 4.1 Introduction 4.2 Introduction to Servelts 4.3 Server-Side Programming 4.4 Web Server 4.5 Servlet Architecture 4.6 Web Container 4.7 Servlet Life Cycle 4.8 Tomcat Interface 4.9 Servlet Interface 4.10 Practical Assignment 4.11 Summary 4.12 Key Words/Abbreviations 4.13 Learning Activity 4.14 Unit End Questions (MCQs and Descriptive) 4.15 References CU IDOL SELF LEARNING MATERIAL (SLM)

Java Servlets - I 77 4.0 Learning Objectives After studying this unit, you will be able to:  Describe server side programming  Elaborate web server, and Java serverside components  Explain Servlet Architecture, WebContainer, Servlet Life Cycle  Discuss Tomcat Interface, and Servlet interface 4.1 Introduction Servlets provide a component-based, platform-independent method for building Webbased applications, without the performance limitations of CGI programs. Servlets have access to the entire family of Java APIs, including the JDBC API to access enterprise databases. This tutorial will teach you how to use Java Servlets to develop your web based applications in simple and easy steps. 4.2 Introduction to Servlets Servlets are Java programs that run on Web or application servers, acting as a middle layer between requests coming from Web browsers or other HTTP clients and databases or applications on the HTTP server. Their job is to perform the following tasks, as illustrated in Figure Database Legacy Application Java Application Web Service Client (End User) Web Server (Servlets/JSP) Fig. 4.1: Servlets  Read the explicit data sent by the client: The end user normally enters the data in an HTML form on a Web page. However, the data could also come from an applet or a custom HTTP client program.  Read the implicit HTTP request data sent by the browser: Figure 1 shows a single arrow going from the client to the Web server (the layer where servlets and JSP execute), CU IDOL SELF LEARNING MATERIAL (SLM)

78 Advanced Internet Programming but there are really two varieties of data: the explicit data that the end user enters in a form and the behind-the-scenes HTTP information. Both varieties are critical.  Generate the results: This process may require talking to a database, executing an RMI or EJB call, invoking a Web service, or computing the response directly. Your real data may be in a relational database. Fine. But your database probably doesn’t speak HTTP or return results in HTML, so the Web browser can’t talk directly to the database. Even if it could, for security reasons, you probably would not want it to. The same argument applies to most other applications. You need the Web middle layer to extract the incoming data from the HTTP stream, talk to the application, and embed the results inside a document.  Send the explicit data (i.e., the document) to the client: This document can be sent in a variety of formats, including text (HTML or XML), binary (GIF images), or even a compressed format like gzip that is layered on top of some other underlying format. But, HTML is by far the most common format, so an important servlet/JSP task is to wrap the results inside of HTML.  Send the implicit HTTP response data: Figure 1 shows a single arrow going from the Web middle layer (the servlet or JSP page) to the client. But, there are really two varieties of data sent.both varieties are critical to effective development. Sending HTTP response data involves telling the browser or other client what type of document is being returned (e.g., HTML), setting cookies and caching parameters, and other such tasks. Web Server HTTP Request Client Servlet Container HTTP Response Fig. 4.2: Deployment Diagram of a Web Server 4.3 Server-Side Programming All of us would have started programming in java with the famous “hello world” program. If you can recollect, we saved the file with a ‘.java’ extension and later compiled the program using ‘javac’ and then executed the program using ‘java’. Apart from introducing you to the language basics, the important point is that it is a client-side program. That means you write, compile and CU IDOL SELF LEARNING MATERIAL (SLM)

Java Servlets - I 79 execute the program in the client machine (i.e., your PC). No doubt, it is the easiest and fastest way to write, compile and execute the program. However, it has little practical significance when it comes to real-world programming. Why Server Side Programming Though it is technically feasible to implement almost any business logic using client-side programs, logically or functionally it server no purpose when it comes to enterprises application (e.g., banking, air ticketing, e-shopping, etc). To further explain, going by the client-side programming logic; a bank having 10,000 `1.. customers would mean that each customer would have a copy of the program(s) in his or her PC (and now even mobiles) which translates to 10,000 programs! In addition, there are issues like security, resource pooling, concurrent access and manipulations to the database which simply cannot be handled by client-side programs. The answer to most of the issues cited above is- “Server Side Programming”. Figure illustrates the Server Side Architecture in the simplest way. Client 1 Java Server/ Client 2 java Server Page/XML Application Server Client 3 Database/ Web Services Web Server Server Side Programming Architecture Fig. 4.3: Server Side Programming Architecture Advantages of Server Side Programs Some of the advantages of Server Side programs are as follows: 1. All programs reside in one machine called server. Any number of remote machines (called clients) can access the server programs. 2. New functionalities to existing programs can be added at the server side which the clients can take advantage of without having to change anything. CU IDOL SELF LEARNING MATERIAL (SLM)

80 Advanced Internet Programming 3. Migrating to newer versions, architectures, design patterns, adding patches, switching to new databases can be done at the server side without having to bother about client’s hardware or software capabilities. 4. Issues relating to enterprise applications like resource management, concurrency, session management, security and performance are managed by the server side applications. 5. They are portable and possess the capability to generate dynamic and user-based content (e.g., displaying transaction information of credit card or debit card depending on user’s choice). It is the program that runs on server dealing with the generation of content of web page. 1. Querying the database 2. Operations over databases 3. Access/Write a file on server. 4. Interact with other servers. 5. Structure web applications. 6. Process user input. For example if user input is a text in search box, run a search algorithm on data stored on server and send the results. Examples The Programming languages for server-side programming are: 1. PHP 2. C++ 3. Java and JSP 4. Python 5. Ruby on Rails 4.4 Web Server Servlet Container It provides the runtime environment for JavaEE (j2ee) applications. The client/user can request only a static WebPages from the server. If the user wants to read the web pages as per input then the servlet container is used in java. The servlet container is used in java for dynamically generate the web pages on the server side. Therefore the servlet container is the part of a web server that interacts with the servlet for handling the dynamic web pages from the client. CU IDOL SELF LEARNING MATERIAL (SLM)

Java Servlets - I 81 There are two Types of Servers 1. Web Server 2. Application Server Web Server Web server contains only web or servlet container. It can be used for servlet, jsp, struts, jsf etc. It can’t be used for EJB. It is a computer where the web content can be stored. In general web server can be used to host the web sites but there also used some other web servers also such as FTP, email, storage, gaming etc. Examples of Web Servers are: Apache Tomcat and Resin. Important Points  If the requested web page at the client side is not found, then web server will sends the HTTP response: Error 404 Not found.  When the web server searching the requested page if requested page is found then it will send to the client with an HTTP response.  If the client requests some other resources then web server will contact to application server and data is store for constructing the HTTP response. Application Server Application server contains Web and EJB containers. It can be used for servlet, jsp, struts, jsf, ejb etc. It is a component based product that lies in the middle-tier of a server centric architecture. It provides the middleware services for state maintenance and security, along with persistence and data access. It is a type of server designed to install, operate and host associated services and applications for the IT services, end users and organizations. The block diagram representation of Application Server is shown below: CU IDOL SELF LEARNING MATERIAL (SLM)

82 Advanced Internet Programming Applications Client Tier APIs Browsers J2EE Platform Middle Tier EJB Server Web Server APIs APIs Database EIS Tier Servers Applications Files Databases Fig. 4.4: Application Server The Example of Application Servers are: 1. JBoss: Open-source server from JBoss community. 2. Glassfish: Provided by Sun Microsystem. Now acquired by Oracle. 3. Weblogic: Provided by Oracle. It more secured. 4. Websphere: Provided by IBM. 4.5 Servlet Architecture Following diagram shows the position of Servelts in a Web Application. HTTP Server HTTP Protocol Web Browser Servelets Program Database Fig. 4.5: Position of Servelts in a Web Application Servlets Tasks Servlets perform the following major tasks: CU IDOL SELF LEARNING MATERIAL (SLM)

Java Servlets - I 83 1. Read the explicit data sent by the clients (browsers). This includes an HTML form on a Web page or it could also come from an applet or a custom HTTP client program. 2. Read the implicit HTTP request data sent by the clients (browsers). This includes cookies, media types and compression schemes the browser understands, and so forth. 3. Process the data and generate the results. This process may require talking to a database, executing an RMI or CORBA call, invoking a Web service, or computing the response directly. 4. Send the explicit data (i.e., the document) to the clients (browsers). This document can be sent in a variety of formats, including text (HTML or XML), binary (GIF images), Excel, etc. 5. Send the implicit HTTP response to the clients (browsers). This includes telling the browsers or other clients what type of document is being returned (e.g., HTML), setting cookies and caching parameters, and other such tasks. Servlets Packages Java Servlets are Java classes run by a web server that has an interpreter that supports the Java Servlet specification. Servlets can be created using the javax.servlet and javax.servlet.http packages, which are a standard part of the Java’s enterprise edition, an expanded version of the Java class library that supports large-scale development projects. These classes implement the Java Servlet and JSP specifications. At the time of writing this tutorial, the versions are Java Servlet 2.5 and JSP 2.1. Java servlets have been created and compiled just like any other Java class. After you install the servlet packages and add them to your computer’s Classpath, you can compile servlets with the JDK’s Java compiler or any other current compiler. 4.6 Web Container Web container (also known as a Servlet container) is the component of a web server that interacts with Java servlets. A web container is responsible for managing the lifecycle of servlets, mapping a URL to a particular servlet and ensuring that the URL requester has the correct access rights. A web container implements the web component contract of the Java EE architecture, specifying a runtime environment for web components that includes security, concurrency, CU IDOL SELF LEARNING MATERIAL (SLM)

84 Advanced Internet Programming lifecycle management, transaction, deployment, and other services. A web container provides the same services as a JSP container as well as a federated view of the Java EE platform APIs A Web application runs within a Web container of a Web server. The Web container provides the runtime environment through components that provide naming context and life cycle management. Some Web servers may also provide additional services such as security and concurrency control. A Web server may work with an EJB server to provide some of those services. A Web server, however, does not need to be located on the same machine as an EJB server. Web applications are composed of web components and other data such as HTML pages. Web components can be servlets, JSP pages created with the JavaServer Pages™ technology, web filters, and web event listeners. These components typically execute in a web server and may respond to HTTP requests from web clients. Servlets, JSP pages, and filters may be used to generate HTML pages that are an application’s user interface. They may also be used to generate XML or other format data that is consumed by other application components. 4.7 Servlet Life Cycle The lifecycle of a servlet is controlled by the container in which the servlet has been deployed. When a request is mapped to a servlet, the container performs the following steps. 1. If an instance of the servlet does not exist, the web container (a) Loads the servlet class. (b) Creates an instance of the servlet class. (c) Initializes the servlet instance by calling the init method. Initialization is covered in Creating and Initializing a Servlet. 2. Invokes the service method, passing request and response objects. Service methods are discussed in Writing Service Methods. 1. Load servlet class. 5. Call the destroy method. 2. Create servlet instance. 3. Call the in it method. <<interface>> Servlet 4. Call the service method. Init (servletConfig) Service (req, resp) Destroy () Fig. 4.6: Servlet Life Cycle CU IDOL SELF LEARNING MATERIAL (SLM)

Java Servlets - I 85 1. Load the Servlet Class: The classloader is responsible to load the servlet class. The servlet class is loaded when the first request for the servlet is received by the web container. 2. Create Servlet instance: The web container creates the instance of a servlet after loading the servlet class. The servlet instance is created only once in the servlet life cycle. 3. Call the init method: The web container calls the init method only once after creating the servlet instance. The init method is used to initialize the servlet. It is the life cycle method of the javax.servlet.Servlet interface. 4. call the service method: The web container calls the service method each time when request for the servlet is received. If servlet is not initialized, it follows the first three steps as described above then calls the service method. If servlet is initialized, it calls the service method. Notice that servlet is initialized only once. 5. destroy method is invoked: The web container calls the destroy method before removing the servlet instance from the service. It gives the servlet an opportunity to clean up any resource for example memory, thread etc Create Initialize Available for Servicing service requests unavailable for (Unavailable service exception Destroy thrown) (Initialization Failed) Unload Fig. 4.7: Servlet Life Cycle Diagram A servlet life cycle can be defined as the entire process from its creation till the destruction. The following are the paths followed by a servlet  The servlet is initialized by calling the init () method.  The servlet calls service() method to process a client’s request.  The servlet is terminated by calling the destroy() method.  Finally, servlet is garbage collected by the garbage collector of the JVM. Now let us discuss the life cycle methods in details. CU IDOL SELF LEARNING MATERIAL (SLM)

86 Advanced Internet Programming The init() Method The init method is designed to be called only once. It is called when the servlet is first created, and not called again for each user request. So, it is used for one-time initializations, just as with the init method of applets. The servlet is normally created when a user first invokes a URL corresponding to the servlet, but you can also specify that the servlet be loaded when the server is first started. When a user invokes a servlet, a single instance of each servlet gets created, with each user request resulting in a new thread that is handed off to doGet or doPost as appropriate. The init() method simply creates or loads some data that will be used throughout the life of the servlet. The init method definition looks like this: public void init() throws ServletException { // Initialization code... } The service() Method The service() method is the main method to perform the actual task. The servlet container (i.e. web server) calls the service() method to handle requests coming from the client( browsers) and to write the formatted response back to the client. Each time the server receives a request for a servlet, the server spawns a new thread and calls service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate. Here is the signature of this method: public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { } The service () method is called by the container and service method invokes doGe, doPost, doPut, doDelete, etc. methods as appropriate. So you have nothing to do with service() method but you override either doGet() or doPost() depending on what type of request you receive from the client. CU IDOL SELF LEARNING MATERIAL (SLM)

Java Servlets - I 87 4.8 Tomcat Interface Interfaces in javax.servlet.http Package There are many interfaces in javax.servlet.http package. They are as follows:  HttpServletRequest  HttpServletResponse  HttpSession  HttpSessionListener  HttpSessionAttributeListener  HttpSessionBindingListener  HttpSessionActivationListener  HttpSessionContext (deprecated now) <<Interface>> <<Interface>> <<Interface>> ServletRequest Servlet ServletResponse get Parameter (name) Service(req,resp) get Writer (): PrintWriter get ParameterValues(name) get OutputStream get ParameterName SetContentType (MIME) SetContentLength (int) <<Interface>> Httpservlet <<Interface>> HttpServletRequest {abstract} HttpServletRequest getHeader (name) Service setHeader getHeaders(name) doGet setDateHeader get HeaderNames ( ) :Enum. dopost setIntHeader getIntHeader (name) getDateHeader (name) Fig. 4.8: Tomcat Interfaces Classes in javax.servlet.http Package There are many classes in javax.servlet.http package. They are as follows:  HttpServlet  Cookie  HttpServletRequestWrapper CU IDOL SELF LEARNING MATERIAL (SLM)

88 Advanced Internet Programming  HttpServletResponseWrapper  HttpSessionEvent  HttpSessionBindingEvent 4.9 Servlet Interface Servlet interface is a collection of empty method signatures. A Servlet must directly or indirectly [by subclassing the GenericServlet or HttpServlet class] implement the Servlet interface. This interface holds method signatures that bring the following Servlet functionalities:  Initializing a Servlet  Handling a client request  Destroying a Servlet The following are the methods available in this interface: Methods Table 4.1: Methods Available in this Interface init() Description destroy() service() Is used for initializing the Servlet parameters provided by the ServletConfig getServletConfig() object. Is called only once when the Servlet is first loaded. It is commonly used to initialize resources to be used by a Servlet when requests are received. For example, database or network connections, file initialization and other environmental settings. None of the Servlets methods can be called unless the Servlet is initialized using init(). destroy() is also called only once immediately before the Servlet is unloaded. Is used to clear all retained resources such as database connection, threads, file handles and so on. This method is overridden in order to free up any resources being used by the Servlet. Is the actual heart of the HTTP Request-Response model. Is called to handle a single client request. A Servlet receives request information through the ServletRequest object and sends data back to the client through the ServletResponse object. Provides the ServletConfig object for initializing the Servlet’s parameters. CU IDOL SELF LEARNING MATERIAL (SLM)

Java Servlets - I 89 getServletInfo() Provides the Servlet metadata such as author, Servlet version and other copyright information. This method needs to be overridden inside the Servlet for it to return the required information. 4.10 Practical Assignment 1. Develop Java Application to demonstrate Servlet Life cycle. 2. Develop Java Application for Servlet Login. 4.11 Summary Java Servlets often serve the same purpose as programs implemented using the Common Gateway Interface (CGI). But Servlets offer several advantages in comparison with the CGI.  Performance is significantly better.  Servlets execute within the address space of a Web server. It is not necessary to create a separate process to handle each client request.  Servlets are platform-independent because they are written in Java.  Java security manager on the server enforces a set of restrictions to protect the resources on a server machine. So servlets are trusted.  The full functionality of the Java class libraries is available to a servlet. It can communicate with applets, databases, or other software via the sockets and RMI mechanisms that you have seen already. 4.12 Key Words/Abbreviations  Cookie: Cookies are text files stored on the client computer and they are kept for various information tracking purpose. 4.13 Learning Activity 1. Explain Tomcat interface. ----------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------- CU IDOL SELF LEARNING MATERIAL (SLM)

90 Advanced Internet Programming 2. Explain Web container. ----------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------- 4.14 Unit End Questions (MCQs and Descriptive) A. Descriptive Types Questions 1. What is Servlet? Explain in detail. 2. Explain Web Server and Application server with its working. 3. Explain Web Container in detail 4. Explain Servlet Interface and its methods. 5. Explain Servlet Lifecycle. 6. Write a short note on Server-Side Programming. 7. Explain Java Server side components in detail. 8. Explain Servlet Architecture with neat diagram. 9. Explain Tomcat Interface with httpservlet. B. Multiple Choice/Objective Type Questions 1. Which object of HttpSession can be used to view and manipulate information about a session? (a) session identifier (b) creation time (c) last accessed time (d) All mentioned above 2. Which class provides stream to read binary data such as image etc. from the request object? (a) ServltInputStream (b) ServletOutputStream (c) Both A & B (d) None of the above 3. Which of these ways used to communicate from an applet to servlet? (a) RMI Communication (b) HTTP Communication (c) Socket Communication (d) All mentioned above CU IDOL SELF LEARNING MATERIAL (SLM)

Java Servlets - I 91 4. Which type of ServletEngine is a server that includes built-in support for servlets? (a) Add-on ServletEngine (b) Embedded ServletEngine (c) Standalone ServletEngine (d) None of the above 5. Which cookie it is valid for single session only and it is removed each time when the user closes the browser? (a) Persistent cookie (b) Non-persistent cookie (c) All the above (d) None of the above Answers 1. (d), 2. (a), 3. (d), 4. (c), 5. (b) 4.15 References 1. https://www.tutorialspoint.com/servlets/index.htm 2. https://www.baeldung.com/intro-to-servlets 3. JDBC 4.2, Servlet 3.1, and JSP 2.3 Includes JSF 2.2 and Design Patterns, Black Book, 2ed CU IDOL SELF LEARNING MATERIAL (SLM)


Like this book? You can publish your book online for free in a few minutes!
Create your own flipbook