Sharing With Passion
Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

February 08, 2019

Posted by Sabar Santoso in , | February 08, 2019 No comments















Java sebagai salah satu bahasa pemrograman open source menjanjikan banyak kemudahan bagi programer junior maupun senior. Tutorial ini akan membawa Anda mengenal lebih jauh bahasa ini melalui pembahasan konsep model perancangan dan petunjuk sederhana penggunaannya.

Java adalah bahasa pemrograman berorientasi objek yang dikembangkan oleh Sun Microsystems sejak tahun 1991, yang saat ini sudah di akuisisi oleh Oracle. Bahasa ini dikembangkan dengan model yang mirip dengan bahasa C++ dan Smalltalk, namun dirancang agar lebih mudah dipakai dan ­platform independent, yaitu dapat dijalankan di berbagai jenis sistem operasi dan arsitektur komputer­­. Bahasa ini juga dirancang untuk pemrograman di Internet sehingga dirancang agar aman dan portabel.


Platform Independent

Platform independent berarti program yang ditulis dalam bahasa Java dapat dengan mudah dipindahkan antar berbagai jenis sistem operasi dan berbagai jenis arsitektur komputer. Aspek ini sangat penting untuk dapat mencapai tujuan Java sebagai bahasa pemrograman Internet di mana sebuah program akan dijalankan oleh berbagai jenis komputer dengan berbagai jenis sistem operasi. Sifat ini berlaku untuk level source code dan binary code dari program Java. Berbeda dengan bahasa C dan C++, semua tipe data dalam bahasa Java mempunyai ukuran yang konsisten di semua jenis platform. Source code program Java sendiri tidak perlu dirubah sama sekali jika Anda ingin mengkompile ulang di platform lain. Hasil dari mengkompile source code Java bukanlah kode mesin atau instruksi prosesor yang spesifik terhadap mesin tertentu, melainkan berupa bytecode yang berupa file berekstensi .class. Bytecode tersebut dapat langsung Anda eksekusi di tiap platform yang dengan menggunakan Java Virtual Machine (JVM) sebagai interpreter terhadap bytecode tersebut.

JVM sendiri adalah sebuah aplikasi yang berjalan di atas sebuah sistem operasi dan menerjemahkan bytecode program Java dan mengeksekusinya, sehingga secara konsep bisa dianggap sebagai sebuah interpreter. Proses pengeksekusian program Java dapat dilukiskan seperti di Gambar 1. Dengan cara ini, sebuah program Java yang telah dikompilasi akan dapat berjalan di platform mana saja, asalkan ada JVM di sana.

Kompiler dan interpreter untuk program Java berbentuk Java Development Kit (JDK) yang diproduksi oleh Sun Microsystems. JDK ini dapat didownload gratis dari situs java.sun.com. Interpreter untuk program Java sendiri sering juga disebut Java Runtime atau Java Virtual Machine. Interpreter Java, tanpa kompilernya, disebut Java Runtime Environment (JRE) dapat didownload juga di situs yang sama. Untuk mengembangkan program Java dibutuhkan JDK, sementara jika hanya ingin menjalankan bytecode Java cukup dengan JRE saja. Namun untuk mengeksekusi applet (sebuah bytecode Java juga) Anda biasanya tidak perlu lagi mendownload JRE karena browser yang Java-enabled telah memiliki JVM sendiri.


Library

Selain kompiler dan interpreter, bahasa Java sendiri memiliki library yang cukup besar yang dapat mempermudah Anda dalam membuat sebuah aplikasi dengan cepat. Library ini sudah mencakup untuk grafik, desain user interface, kriptografi, jaringan, suara, database, dan lain-lain.


Object Oriented

Java adalah bahasa pemrograman berorientasi objek. Pemrograman berorientasi objek secara gamblang adalah teknik untuk mengorganisir program dan dapat dilakukan dengan hampir semua bahasa pemrograman. Namun Java sendiri telah mengimplementasikan berbagai fasilitas agar seorang programer dapat mengoptimalkan teknik pemrograman berorientasi objek.

Sedikit perbandingan tambahan dengan bahasa C dan C++, Java banyak mewarisi konsep orientasi objek dari C++ namun dengan menghilangkan aspek-aspek kerumitan dalam bahasa C++ tanpa mengurangi kekuatannya. Hal ini mempermudah programer pemula untuk mempelajari Java namun mengurangi keleluasaan programer berpengalaman dalam mengutak-atik sebuah program. Di balik kemudahan yang ditawarkan Java, luasnya fasilitas library Java sendiri membuat seorang programer membutuhkan waktu yang tidak singkat untuk dapat menguasai penggunaan library-library tersebut.


Memulai Pemrograman Java

Untuk membuat program Java, seperti telah disebutkan sebelumnya, Anda membutuhkan JDK. Proses instalasi JDK tersebut sangat mudah dan tidak membutuhkan pengetahuan tertentu. Namun untuk menggunakannya Anda perlu melakukan beberapa penyesuaian dengan sistem operasi Anda. Umumnya yang perlu Anda lakukan adalah memasukkan path ke direktori JDK Anda ke setting path pada sistem operasi Anda. Misalkan direktori JDK Anda adalah C:\jdk1.4SET PATH=C:\jdk1.4\bin pada file autoexec.bat Anda. Untuk Windows NT/2000/XP Anda cukup menambahkan direktori C:\jdk1.4\bin pada variabel path di System Environment. Caranya: klik kanan ikon My Computer, pilih Properties. Kemudian pilih tab Advanced. Lalu klik tombol Environment Variables, cari variabel path, kemudian tambahkan path direktori JDK Anda ke dalam variabel tersebut. Untuk Linux, tambahkan baris perintah SET CLASSPATH=(direktori jdk Anda) ke file profile Anda. Untuk mencoba JDK, ketikkan perintah java dan javac pada shell prompt (atau DOS Command Prompt). Jika perintah tersebut sudah dikenali, maka program java atau javac Visual Café dari Symantec atau JBuilder dari Borland pada Windows 98 anda cukup menambahkan baris perintah akan menampilkan sintaks penggunaan. Untuk kemudahan dan berbagai fasilitas tambahan Anda dapat menggunakan Integrated Development Environment (IDE) untuk bahasa Java seperti

Urutan langkah-langkah yang harus Anda lakukan untuk membuat sebuah program Java sederhana adalah:
  1. Membuat source code program dengan editor teks apapun. Ingat, file tersebut harus berekstensi .java dan case sensitive.
  2. Mengkompile source code dengan perintah javac. Misalnya: javac HelloWorld.java. Jika berhasil, hasilnya adalah file bytecode berakhiran .class.
  3. Mengeksekusi bytecode dengan perintah java. Parameter dari perintah ini adalah nama file hasil kompilasi tanpa ekstensi .class. Contoh: java HelloWorld.

Source Code

Berikut kode untuk HelloWorld.java:

public class HelloWorld
{
    public static void main(String[] args)
    {
        System.out.println("Hello World....");
    }
}

Dan ini sebuah contoh lain, yaitu applet sederhana untuk menampilkan teks di applet. Sebutlah file ini bernama HelloWorldApplet.java:

import java.awt.Graphics;

public class HelloWorldApplet extends java.applet.Applet
   {
      public void paint(Graphics g)
      {
         g.drawString("Apa Kabar Dunia?", 5, 25);
      }
   }

Secara gamblang dapat diperhatikan bahwa struktur kedua program sangat mirip, dan hanya berbeda dalam konteks eksekusi. Kedua program ini akan dibahas lebih lanjut setelah kita membahas cara mengkompile dan mengeksekusi program tersebut. Perlu diingat bahwa bahasa Java bersifat case sensitive, sehingga Anda harus memperhatikan penggunaan huruf besar dan kecil. Selain itu penulisan source code program tidak harus memperhatikan bentuk tertentu, sehingga Anda bisa saja menuliskan semua baris source code tersebut dalam satu baris asal Anda tidak lupa membubuhkan tanda titik koma (;), atau menuliskan tiap kata dalam satu baris tersendiri. Namun dianjurkan Anda mengikuti layout seperti pada contoh agar program Anda mudah dibaca dan dimengerti.


Kompilasi

Setelah kedua file disave dengan nama HelloWorld.java dan HelloWorldApplet.java, kita akan mengkompile kedua program tersebut dengan perintah:
prompt> javac HelloWorld.java
prompt> javac HelloWorldApplet.java
Perlu diperhatikan bahwa direktori aktif Anda saat ini adalah direktori tempat Anda meletakkan file-file program tersebut. Anda tetap dapat mengkompile program Anda dari direktori berbeda dengan perintah:
prompt> javac (direktori program)/namafile.java
Setelah perintah ini selesai, Anda akan melihat bahwa telah tercipta dua buah file .class, yaitu bytecode hasil kompilasi source code kita.


Sintaks Program

Sekarang kita akan mencoba membahas elemen-elemen dalam kedua source code tersebut.

Pada awal Listing 2 kita menemukan perintah import. Pada tahap awal ini Anda perlu mengetahui bahwa pernyataan tersebut hanya berfungsi mempermudah penulisan metode atau dalam bahasa pemrograman lain disebut prosedur atau fungsi. Jadi Anda hanya perlu menulis Graphics sebagai pengganti java.awt.Graphics, karena kita telah mengimpor java.awt.Graphics.

Kemudian di masing-masing listing terdapat pernyataan public class. Pernyataan ini adalah pernyataan pembuka sebuah kelas. Kelas sendiri digunakan untuk menciptakan objek. Ingat bahwa Java berorientasi objek. Kata public di depannya berfungsi agar kelas tersebut dapat diakses oleh semua program lain. Untuk saat ini anggaplah objek sebagai suatu item yang dapat dimanipulasi oleh sebuah program. Dalam Listing 2 terdapat tambahan kata extends. Hal ini berarti kelas yang kita buat akan mewarisi sifat-sifat dari kelas yang kita extends. Dengan kata lain kita menjadikan kelas yang kita extends sebagai himpunan bagian dari kelas kita buat.

Kemudian kita menemukan baris pernyataan public static void main(String[] args) dan public void paint(Graphics g). Keduanya adalah pernyataan pembuka sebuah metode. Metode sendiri adalah kumpulan pernyataan untuk melakukan suatu tugas tertentu dalam kelas. Keduanya sebenarnya mempunyai fungsi yang sama namun dalam konteks yang berbeda. Dalam setiap aplikasi harus ada sebuah metode yang bernama main yang akan dieksekusi pertama kali saat program tersebut dieksekusi. Sementara dalam applet, metode yang pertama kali akan dieksekusi ketika applet diload adalah paint. Kata public di depannya mempunyai fungsi yang sama dengan kata public yang ada di depan baris permulaan kelas. Namun nantinya Anda akan menemukan juga bentuk lain seperti private dan protect yang akan kita bahas nanti.

Pada Listing 1 terdapat kata static pada pernyataan pembuka metode main. Hal ini berarti metode main tidak mengubah atau menggunakan objek yang diciptakan oleh kelas tersebut, sehingga dapat dikatakan berdiri sendiri dan tidak terikat dengan objek. Dalam metode mainString[] args, di mana args hanyalah sebuah nama dari objek array dari String. Array ini nantinya akan berisi parameter-parameter yang diberikan user sebagai argumen command line. Sementara Anda tidak perlu mengerti mengenai parameter tersebut, cukup diingat bahwa bentuk metode main harus selalu demikian. dalam aplikasi, parameternya adalah selalu

Kemudian di dalam kedua metode pada kedua listing tersebut, kita menemukan sebuah pernyataan. Anda tentu dapat saja meletakkan lebih dari satu pernyataan dalam sebuah metode. Setiap pernyataan dalam sebuah metode dipisahkan oleh titik koma dan akan dieksekusi satu persatu. Kedua pernyataan pada listing ternyata memanggil sebuah metode lain yaitu metode println dan paint. Tentunya dapat Anda perhatikan bahwa untuk memanggil sebuah metode diperlukan tiga komponen yaitu:
  1. Objek yang ingin kita pakai. Dalam hal ini objek System.out dan Graphics g.
  2. Nama metode yang ingin kita pakai. Dalam hal ini println dan paint.
  3. Sepasang tanda kurung yang berisi informasi tambahan yang diperlukan oleh metode yang dipanggil, yaitu parameter.
Dalam Listing 1, pernyataan System.out.println("Apa Kabar Dunia?"); berarti carilah objek outSystem kemudian panggil metode println dari objek out dengan parameter berupa string "Apa Kabar Dunia?". Sedang dalam Listing 2, pernyataan g.drawString("Apa Kabar Dunia?", 5, 25); berarti carilah objek g kemudian panggil metode drawString pada objek g dengan parameter "Apa Kabar Dunia?”, 5, 25);. dalam kelas


Eksekusi

Setelah selesai membahas sintaks dasar Java dalam kedua listing, selanjutnya kita akan mencoba mengeksekusi kedua program ini. Untuk program pertama yang berupa aplikasi biasa, kita tinggal mengetikkan perintah java HelloWorld pada prompt dan pesan Apa Kabar Dunia? akan tampil di layar (atau mungkin di tempat lain, bergantung sistem operasi Anda). (ref - Ari Hermawan, Ilmu Komputer).

July 09, 2012

Posted by Sabar Santoso in , , , | July 09, 2012 No comments

The Java Swing provides the multiple platform independent APIs interfaces for interacting between the users and GUIs components. All Java Swing classes imports form the import javax.swing.*; package. Java provides an interactive features for design the GUIs toolkit or components like: labels, buttons, text boxes, checkboxes, combo boxes, panels and sliders etc. All AWT flexible components can be handled by the Java Swing. The Java Swing supports the plugging between the look and feel features. The look and feel that means the dramatically changing in the component like JFrame, JWindow, JDialog etc. for viewing it into the several types of window.
Here the following APIs interfaces and classes are available:
The following interfaces and it's descriptions to be used by the Java swing.
Interfaces
Descriptions
ActionThis interface performed the action with the ActionListenerwhere the multiple controls are used for same purposes.
BoundedRangeModelThis interface defines the data model of components like: sliders and progressBars.
ButtonModelIt defines the state model for the buttons like: radio buttons, check boxes etc.
CellEditorThis interface used by the developer for creating the new editor and it has the new components implement interfaces. TheCellEditor implements the wrapper based approach.
ComboBoxEditorIn this interface, the editor component used to JComboBoxcomponents.
ComboBoxModelThis interface represents the data model in a list model with the selected items.
DesktopManagerThis interface has JDesktopPane object. The JInternalFrameimplements in the JDesktopPane with the help of DesktopManager.
IconThis interface used to graphical representation of the components. It has fixed size picture.
JComboBox.KeySelectionManagerThis interface has KeySelectionManager and used for the combo box data model.
ListCellRendererThis interface used for paint the cell in the list with the help of "rubber stamps" .
ListModelThis interface used for JList components method. It gets the value of each cell of list.
ListSelectionModelThis interface indicates the components, which are stable or not.
MenuElementThis interface used where the any components are implements in the menu.
MutableComboBoxModelThis interface extends from the ComboBoxModel. It is a mutable version of ComboBoxModel.
RendererIt defines the requirements of an object for displaying the values.
RootPaneContainerThis interface uses the RootPane properties and it has the components like: JFrame, JInternalFrame and JWindow etc.
ScrollableThis interface provides the scrolling to show the large amount of data with the help of JScrollPane.
ScrollPaneConstantsThis interface used for JScrollPane components.
SingleSelectionModelThis interface used to select the one index in a model.
SwingConstantsYou can set the components on the screen to own requirements.
UIDefaults.ActiveValueIt constructs the DefaultListCellRenderer.
UIDefaults.LazyValueThis enables one to store an entry in the default table. The entered value is not constructed until first time is a real value is created through it using LazyValue.createValue() method.
WindowConstantsThis interface has two methods setDefaultCloseOperation and getDefaultCloseOperation and provides the window close opration.
The following classes and it's descriptions to be used by the Java swing.
Classes
Descriptions
AbstractActionThis class handles the any types of action and provides JFC Action interface.
AbstractButtonThis class defines the nature of buttons and menu items.
AbstractCellEditorIt provides a list and contents of the data model.
AbstractListModelThis class defines the data model which provides the list with its contents.
ActionMapThis class works with InputMap and performs any action when the key is pressed.
BorderFactoryThis class extends from Object and creates the Border instance in the factory.
BoxIt provides the fixed spaces between two components and uses the BoxLayout object of the layout manager.
Box.FillerThis class participates in the Layout and uses the lightweight components.
BoxLayoutThis class uses the arranging the multiple components either horizontally or vertically. The Box container uses this class.
ButtonGroupThis class used to create the multiple buttons in aButtonGroup object.
CellRandererPaneThis class used to insert the components like: JList, JTable and JTree.
ComponentInputMapThis class has ComponentInputMap constructor and creates the components with the help of InpuMap.
DebugGraphicsIt extends from the Graphics and used to debug the graphics
DefaultBoundedRangeModelThis class provides the implementation of default BoundedRangeModel.
DefaultButtonModelThis class implements the generic ButtonModel.
DefaultCellEditorIt implements the TableCellEditor and TreeCellEditor for the table and tree cells.
DefaultComboBoxModelIt provides the default model for combo boxes.
DefaultDesktopManagerIt implements the DesktopManager. The DesktopManager has the JInternalFrame for creating the internal fame in a frame.
DefaultFocusManagerIt provides the implementing the FocusManager.
DefaultListCellRandererIt implements the default ListCellRanderer.
DefaultListCellRanderer.UIResourceThis extends the DefaultListCellRanderer and implementing in the UIResource.
DefaultListModelIt extends the AbstractListModel and implementing thejava.util.Vector.
DefaultListSelectionModelThis class used for select the list in a data model.
DefaultSingleSelectionModelThis class provides the default SingleSelectionModel.
FocusManagerIt handles all focus like: gainedFocus and lostFocus.
GrayFilterIt extends the RGBImageFilter and used for disabling the image through the button.
ImageIconThis class implements the Icon and paints the icons from the images.
InputMapThis class uses the ActionMap to performed the action when you press any key of keyboard. It bounds data between the input event and an object.
InputVerifierThis class helps you when you works with the text fields through the focus.
JAppletThis class extends the Applet and implements the Accessibleand RootPaneContainer.
JButtonThis class extends the AbstractButton and you can create the new button.
JCheckBoxThis class extends the JToggleButton and implements the check box in which buttons are selected or deselected.
JCheckBoxMenuItemIt extends the JMenuItem and determines the items which is selected or deselected.
JColorChooserIt extends the JComponent and implementing the Accessable. Here, you choose and manipulate the colors.
JComboBoxThis class extends the JComboBox. It provides the drop-down list where user select only one item or value at a time. But combo box is a combination of multiple text or buttons etc.
JComponentIn java swing, All components are used the JComponent except the top-level containers like: JFrame, JDialog etc.
JDesktopPaneThis class extends the JLayeredPane and when you create the object of JInternalFrame to be maintained in the JDesktopPane. The JDesktopPane has DesktopManager.
JDialogIt extends the Dialog. This class used to create the dialog window and when you want to create the custom dialog window with the help of JOptionPane method.
JEditorPaneThis class extends the JTextComponent. It edits the component by the EditorKit.
JFileChooserThis class provides the facility to choosing the file.
JFrameIt extends the Frame and supports the swing components architecture.
JInternalFrameThis class extends from the JComponent and provides the facility to dragging, closing, resizing and menu bar of the internal frame. The JInternalFrame added into the JDesktopPane.
JInternalFrame.JDesktopIconIt displays the desktop icon and create the instance of JInternalFrame and iconify.
JLabelThis class used to show the small text and image.
JLayeredPaneIt has JFC/Swing container that can be used to overlap the components to each other.
JListThis class used to create a list where you select the one or more than objects.
JMenuThis class used to create a new menu where you add the JMenuItems. When you select the item then shows the popup menu items in the JMenuBar.
JMenuBarIt used to create a new menu bar where the JMenu objects are added.
JMenuItemThis class used to create new menu items in the mebus.
JOptionPaneIt used to create some different types of dialog box like: message dialog box, error dialog box etc.
JPanelIt extends the JComponent and used to create a new panel.
JPassworkFieldIt provides the single line text editing. Here, don't available the original characters but view type indication characters are available.
JPopupMenuThis class used to create a popup menu. It provides small window where the various types of choices are available.
JPopupMenu.SeparatorHere the popup menu and the separator are available.
JProgressBarIt shows the integer types values in percent within a bounded range to determine the working process.
JRadioButtonIt implements the radio button and shows the state of an item selected or deselected.
JRadioButtonMenuItemIt extends the JMenuItem and implements the radio button menu item
JRootPaneThis class provides the component behind the scenes by JFrame, JWindow, JDialog etc. for providing the task-orientation and functionality.
JScrollBarThis class used to create a scroll bar. It provides the view content area where you show the content to scroll this.
JScrollPaneIt provides the scrollable view components.
JSeparatorThis class use the separator among the components.
JSliderThis class provides a control to represent a numeric value by dragging the slider.
JSplitPaneThis class used to divides the two components graphically like: top and button, left and right.
JTabbedPaneThis class provides the tab component through which you can switch from one component to another component regarding to the specific tab button by clicking on that.
JTableIt provides the user interface component and represents the two dimensional data.
JTextAreaIt provides the multi line plain text area.
JTextFieldIt provides the facility to editing the text in a single line.
JTextPaneThis class provides the component like JTexArea for multiple lines text with more capabalities.
JToggleButtonIt implements two state button that means selected or deselected.
JToggleButton.ToggleButtonModelIt extends the DefaultButtonModel and provides theToggleButton model.
JToolBarIt provides set of command buttons icons that performs the different actions or controls.
JToolBar.SeparatorIt provides the tool bar separator.
JToolTipIt shows the tool tips related to it's components.
JTreeIt shows the data in a hierarchical way.
JTree.DynamicUtilTreeNodeThis extends the DefaultMutableTreeNode and create children nodes.
JTree.EmptySelectionModelIt does not allows the any selection.
JViewPortIt gives you about the underlying information.
JWindowIt extends window and shows the any location or area on the desktop. It couldn't any title bar and window management buttons.
KeyStrokeThis class controls the key events on the keyboard for the equivalent device.
LayoutFocusTraversalPolicyThis class conducts the sorting objects according to their size, type, position or orientation.
LookAndFeelIt provides the dramatically changes in the component like frame related to the graphics for the application. Through this the application can be done very efficient and easier.
MenuSelectionManagerIt has menu selection hierarchy.
OverlayLayoutThe layout manager arrange the components.
ProgressMonitorThis class is used to monitoring the progress of any operation to be done.
ProgressMonitorInputStreamThis class creates a progress monitor to monitor the progress of reading input from the input stream. It cleanups all the rights when the stream is closed.
RepaintManagerThis class manage and override the repaint requests.
ScrollPaneLayoutIt implements the LayoutManager and manage the components like: scroll bar, row header, column header etc.
ScrollPaneLayout.UIResourceIt extends the ScrollPaneLayout and implements theUIResource.
SizeRequirementsIt calculates the size and positions of components.
SizeSequenceIt represents the order list of size and it's positions.
SwingUtilitiesThis class has utilities methods for swing.
TimerActions perform the predefined rate.
ToolTipManagerIt manages the all tool tips.
UIDefaultsIt extends the Hashtable and you set/get the value with the help of UIManager.
UIDefaults.LazyInputMapThis class creates a Input Map through it's createValue() method. The array of key after binding is passed to the constructor of this. Example of binding of key is array of pressing key information (e.g. ctrl + c or alt + f).
UIDefaults.ProxyLazyValueThis class is used to create a lazy value which is used to delay loading of the class to create instance for that.
UIManagerThis class has track of the current look and feel details.
UIManager.LookAndFeelInfoThis is the nested class of UIManager class i.e. used for getting information about all the look and feels installed with the software development kit.
ViewportLayoutIt implements the LayoutManager and defines the policy for the layout.


July 08, 2012

Posted by Sabar Santoso in , | July 08, 2012 No comments
Forms are a very common method of interactions in web sites. JSP makes forms processing specially easy.
The standard way of handling forms in JSP is to define a "bean". This is not a full Java bean. You just need to define a class that has a field corresponding to each field in the form. The class fields must have "setters" that match the names of the form fields. For instance, let us modify our GetName.html to also collect email address and age.
The new version of GetName.html is
  
What's your name?
What's your e-mail address?
What's your age?
To collect this data, we define a Java class with fields "username", "email" and "age" and we provide setter methods "setUsername", "setEmail" and "setAge", as shown. A "setter" method is just a method that starts with "set" followed by the name of the field. The first character of the field name is upper-cased. So if the field is "email", its "setter" method will be "setEmail". Getter methods are defined similarly, with "get" instead of "set". Note that the setters (and getters) must be public.
 package user;  public class UserData {
 String username;     
 String email;     
 int age;      
     public void setUsername( String value )     
     {         username = value;     }      
     public void setEmail( String value )     
     {         email = value;     }      
     public void setAge( int value )     
     {         age = value;     }      
     public String getUsername() 
     { return username; }      
     public String getEmail() 
     { return email; }      
     public int getAge() 
     { return age; }
}
The method names must be exactly as shown. Once you have defined the class, compile it and make sure it is available in the web-server's classpath. The server may also define special folders where you can place bean classes, e.g. with Blazix you can place them in the "classes" folder. If you have to change the classpath, the web-server would need to be stopped and restarted if it is already running.
Note that we are using the package name user, therefore the file UserData.class must be placed in a folder named user under the classpath entry.
Now let us change "SaveName.jsp" to use a bean to collect the data.
All we need to do now is to add the jsp:useBean tag and the jsp:setProperty tag!  The useBean tag will look for an instance of the "user.UserData" in the session.  If the instance is already there, it will update the old instance.  Otherwise, it will create a new instance of user.UserData (the instance of the user.UserData is called a bean), and put it in the session.
The setProperty tag will automatically collect the input data, match names against the bean method names, and place the data in the bean!
Let us modify NextPage.jsp to retrieve the data from bean..
    You entered
Name: <%= user.getUsername() %>
Email: <%= user.getEmail() %>
Age: <%= user.getAge() %>
 
Notice that the same useBean tag is repeated. The bean is available as the variable named "user" of class "user.UserData". The data entered by the user is all collected in the bean.
We do not actually need the "SaveName.jsp", the target of GetName.html could have been NextPage.jsp, and the data would still be available the same way as long as we added a jsp:setProperty tag. But in the next tutorial, we will actually use SaveName.jsp as an error handler that automatically forwards the request to NextPage.jsp, or asks the user to correct the erroneous data.
Exercise:
1) Write a JSP/HTML set that allows a user to enter the name of a system property, and then displays the value returned by System.getProperty for that property name (handle errors appripriately.)
2) Go back to the exercises where you manually modified boolean variables. Instead of a boolean variable, make these come from a HIDDEN form field that can be set to true or false.

Search

Bookmark Us

Delicious Digg Facebook Favorites More Stumbleupon Twitter