Professional Documents
Culture Documents
JBoss Developer Studio 5.0 Getting Started Guide en US
JBoss Developer Studio 5.0 Getting Started Guide en US
JBoss Developer Studio 5.0 Getting Started Guide en US
Edition 5.0.1
Legal Notice
Legal Notice
Copyright 2011 Red Hat. T he text of and illustrations in this document are licensed by Red Hat under a Creative Commons AttributionShare Alike 3.0 Unported license ("CC-BY-SA"). An explanation of CC-BY-SA is available at http://creativecommons.org/licenses/by-sa/3.0/. In accordance with CC-BY-SA, if you distribute this document or an adaptation of it, you must provide the URL for the original version. Red Hat, as the licensor of this document, waives the right to enforce, and agrees not to assert, Section 4d of CC-BY-SA to the fullest extent permitted by applicable law. Red Hat, Red Hat Enterprise Linux, the Shadowman logo, JBoss, MetaMatrix, Fedora, the Infinity Logo, and RHCE are trademarks of Red Hat, Inc., registered in the United States and other countries. Linux is the registered trademark of Linus T orvalds in the United States and other countries. Java is a registered trademark of Oracle and/or its affiliates. XFS is a trademark of Silicon Graphics International Corp. or its subsidiaries in the United States and/or other countries. MySQL is a registered trademark of MySQL AB in the United States, the European Union and other countries. All other trademarks are the property of their respective owners.
Abstract
T he Getting Started Guide explains the JBoss Developer Studio.
Table of Contents
Table of Contents
Preface 1. Introduction to JBoss Developer Studio 1.1. What JBoss Developer Studio is 1.2. Key Features of JBoss Developer Studio and Requirements 2. System Requirements 3. Installing JBoss Developer Studio 3.1. Configuring Your Java Environment 3.1.1. Installing and Configuring 32-bit Sun JDK 6 on Linux 3.1.2. Installing and Configuring 32-bit Sun JDK 6 on Microsoft Windows 3.2. JBoss Developer Studio Installation 3.2.1. Important information before installation 3.2.2. Installation 3.3. Automating subsequent installations 3.4. Upgrading 3.5. Updating JBoss Developer Studio 4. First launch of the JBoss Developer Studio 4.1. Welcome 4.2. Usage Reporting 4.2.1. Collected usage information guide 5. JBoss Central 5.1. Getting Started with JBoss Central 5.2. Software installation and updates from within JBoss Central 5.3. Project Example Installation 6. JBoss Perspective 7. Setting up a JBoss runtime and managing the server 7.1. Adding and configuring a JBoss server runtime 7.2. Starting JBoss Server 7.3. Stopping the JBoss Server 7.4. Server Container Preferences 8. Example of developing a Java EE6, HT ML5, Maven application for mobile devices 8.1. Purpose and T arget Audience 8.2. Creating a new Java EE 6 project with Maven 8.3. Adding a new entity using Forge 8.4. Reviewing persistence.xml and updating import.sql 8.5. Optional: Adding a new entity as a POJO 8.6. Deployment 8.7. Adding a JAX-RS REST ful web service 8.8. Adding a jQuery Mobile client application 9. Developing a simple JSP web application 9.1. Setting Up the Project 9.2. Creating JSP Page 9.2.1. Editing a JSP Page 9.2.2. web.xml file 9.2.3. Deploying the project
9.2.4. JSP Page Preview 9.2.5. Launch JSP Project 10. Rapid Application Development of a JSF application 10.1. Setting up the project 10.2. Creating JSP Pages 10.3. Creating T ransition between two views 10.4. Creating Resource File 10.5. Creating a Java Bean 10.6. Editing faces-config.xml File 10.7. Editing the JSP View Files 10.7.1. Editing inputnumber.jsp page 10.7.2. Editing success.jsp page 10.8. Creating index.jsp page 10.9. Running the Application 11. Uninstalling the JBoss Developer Studio 12. FAQ 12.1. What should I do if the Visual Page Editor does not start under Linux 12.2. Visual Editor starts OK, but the Missing Natures dialog appears 12.3. I have an existing Seam 1.2.1 project. Can I migrate or import the project into a JBoss Developer Studio Seam project? 12.4. I have an existing Struts or JSF project. Can I open the project in JBoss Developer Studio? 12.5. Can I import a WAR file? 12.6. Is it possible to increase the performance of Eclipse after installing your product? 12.7. How can I add my own tag library to the JBoss T ools Palette? 12.8. How to get Code Assist for Seam specific resources in an externally generated project? 12.9. How to import an example Seam project from jboss-eap directory? 12.10. Is a cross-platform project import possible for JBoss Developer Studio? A. Getting Help and Giving Feedback A.1. Do You Need Help? A.2. Give us Feedback B. Revision History
Preface
Preface
T his manual uses several conventions to highlight certain words and phrases and draw attention to specific pieces of information. T o get more information on these conventions please refer to the Docum ent Conventions manual, which can be found on the Red Hat Documentation website under the JBoss Developer Studio section.
T able 1.1. Key Functionality of JBoss Developer Studio Feature JBoss Central Benefit Your first interaction with the tooling suite, JBoss Central is at the heart ofthe JBoss tooling; providing the latest software updates, news, and project creation. Context Dependency Injection (CDI) tooling allows you to create associated projects and add artifacts to existing projects. Validation and code completion is also included. JBoss Developer Studio includes a Visual Page Editor for combined visual and source editing of Web pages. T he Visual Page Editor even renders AJAX-enabled RichFaces components. JBoss Developer Studio includes a T echnology Preview of JBoss RichFaces. RichFaces provides nearly 70 skinnable components, including calendar, tree, dropdown menu, drag-and-drop components, and more. JBoss Developer Studios Visual Page Editor can render RichFaces components. T he JBoss T ools Palette contains a developers project tag libraries and enables inserting tags into a JSP file with one click. T he T ools Palette supports custom and 3rd party tags. JBoss Developer Studio includes jBPM tooling for defining Seam page flows. JBoss Developer Studio includes Spring IDE for developing Spring applications. JBoss Developer Studio includes Struts tools for Struts 1.x applications. JBoss Developer Studios advanced JBoss AS adapter includes features like incremental deployment for fast development. JBoss Developer Studio includes access to Red Hat Enterprise Linux, Linux development tools, and Red Hat Network for development purposes. T ooling for easy installation of Examples. JBoss WS is a web service framework developed as a part of the JBoss Application Server. It implements the JAX-WS specification that defines a programming model and run-time architecture for implementing web services in Java. T he usage plug-in anonymously gathers information on how you use the provided tools. T his information is used to improve and shape the JBoss Developer Studio product to better cater to your needs. For more information refer to Section 4.2, Usage Reporting.
CDI T ooling
AJAX Capabilities
JBoss jBPM T ools Spring T ools Struts T ools Optimized JBoss Application Server adapter Red Hat Enterprise Linux and RHN Access Project Examples JBossWeb Service
Usage reporting
JBoss Developer Studio requires JDK 6 or above. It is important that the architecture of the Java Virtual Machine (JVM) matches the particular JBoss Developer Studio build. For example, if you are using a 64bit system and use the 64-bit JVM, you need the 64-bit JBoss Developer Studio. For the 32-bit version of JBoss Developer Studio use the 32-bit JVM or just use -vm flag to tell JBoss Developer Studio to use 32-bit java if the 64-bit one is found as the default.
Note:
On Linux systems with a 64-bit JVM, the visual editor may fail to start. In this case you will need the libstdc++.so.5 library. See the FAQ for further details.
10
11
Launch the installation package, and follow the prompts to install Java JDK 6. If you don't want to use SysV service scripts you can install the "self-extracting file" for Linux instead of choosing the "RPM in self-extracting" file. In that case you can skip the next step mentioned here. But it is recommended to use the SysV service scripts for production servers. Download and install the appropriate -compat RPM from JPackage here. Please ensure you choose a matching version of the -compat package to the JDK you've installed. Create an environment variable that points to the JDK installation directory and call it JAVA_HOME. Add $JAVA_HOME/bin to the system path to be able to run java from the command line. You can do this by adding the following lines to the .bashrc file in your home directory.
#In this example /usr/java/jdk1.6.0_24 is the JDK installation directory. export JAVA_HOME=/usr/java/jdk1.6.0_24 export PATH=$PATH:$JAVA_HOME/bin
Note:
If you have a JDK already installed and added in your system path, you should add $JAVA_HOME/bin before the old $PATH (not after it) so that the new version of JDK can be found first, i. e. export PAT H=$JAVA_HOME/bin:$PAT H T his way, the machine will pick up the new JVM first. You only need to run "alternative" as a safe guard for the right JVM. Set this variable for your account doing the installation and also for the user account that will run the server. If you have more than one version of JVM installed on your machine, make sure you are using the JDK 1.6 installation as the default java and javac. You can do this using the alternatives system. T he alternatives system allows different versions of Java from different sources to co-exist on your system.
12
Note
If the JDK is not listed by the alternatives command, you can manually add it with the following commands (substitute the location of your JDK for /usr/java/jdk1.6.0_24 where appropriate):
sudo /usr/sbin/alternatives --install "/usr/bin/java" "java" "/usr/java/jdk1.6.0_24/bin/java" sudo /usr/sbin/alternatives --install "/usr/bin/javac" "javac" "/usr/java/jdk1.6.0_24/bin/javac" sudo /usr/sbin/alternatives --install "/usr/lib/jvm/java-1.6.0" "java_sdk_1.6.0" "/usr/java/jdk1.6.0_24" 1
3.1.1.1. Select alternatives for java, javac and java_sdk_1.6.0 As a root user, type the following command at the shell prompt and you should see something like this:
sudo /usr/sbin/alternatives --config java There are 3 programs which provide 'java'. Selection Command ----------------------------------------------1 /usr/lib/jvm/jre-1.5.0-gcj/bin/java * 2 /usr/lib/jvm/jre-1.6.0-openjdk.x86_64/bin/java + 3 /usr/java/jdk1.6.0_24/bin/java Enter to keep the current selection[+], or type selection number:
Make sure the Sun version [/usr/java/jdk1.6.0_24/bin/java in this case] is selected (marked with a '+' in the output), or select it by entering its number as prompted. Repeat the same for javac and java_sdk_1.6.0.
sudo /usr/sbin/alternatives --config javac There are 2 programs which provide 'javac'. Selection Command ----------------------------------------------* 1 /usr/lib/jvm/java-1.6.0-openjdk.x86_64/bin/javac + 2 /usr/java/jdk1.6.0_24/bin/javac Enter to keep the current selection[+], or type selection number: sudo /usr/sbin/alternatives --config java_sdk_1.6.0 There are 2 programs which provide 'java_sdk_1.6.0'. Selection Command ----------------------------------------------* 1 /usr/lib/jvm/java-1.6.0-openjdk.x86_64 + 2 /usr/java/jdk1.6.0_24 Enter to keep the current selection[+], or type selection number:
13
You should verify that java, javac and java_sdk_1.6.0 all point to the same manufacturer and version.
Note:
You can always override this step by setting the JAVA_HOME environment variable as explained in the previous step. Make sure that the java executable is in your path and that you are using an appropriate version. T o verify your Java environment, type java -version at the shell prompt and you should see something like this:
java -version java version "1.6.0_24" Java(TM) SE Runtime Environment (build 1.6.0_24-b07) Java HotSpot(TM) Server VM (build 19.1-b02, mixed mode)
3.1.2. Installing and Configuring 32-bit Sun JDK 6 on Microsoft Windows T o install and configure 32-bit Sun JDK 6 on Microsoft Windows, follow these steps: Download the Sun JDK 6 from Oracle's website. Choose "JDK 6 Update <x>" (where "x" is the latest update number) for download and then select your Windows Platform options to perform the installation. Create an environment variable called JAVA_HOME that points to the JDK installation directory, for example: C:\Program Files\Java\jdk1.6.0_24 \ In order to run java from the command line, add the jre\bin directory to your path, for example: C:\Program Files\Java\jdk1.6.0_24 \jre\bin T o do this, open the Control Panel from the Start menu, switch to Classic View if necessary, open the System Control Panel applet (System ), select the Advanced T ab, and click on the Environm ent Variables button. Now, when 32-bit Sun JDK 6 has been successfully installed, we can pass on to the next step.
T hese settings will ensure you do not encounter an error regarding maximum open files when starting JBoss Developer Studio. A GUI interface is also necessary for JBoss Developer Studio to run correctly. Either Gnome or KDE are acceptable.
14
are acceptable. When installing JBoss Developer Studio on the 64-bit edition of MacOS X Snow Leopard or Lion, only the 64-bit edition of JBoss Developer Studio is supported. T hough the 32-bit edition will install, many features will not work correctly due to Java 1.6 being specific to 64-bit applications on Leopard and JBoss Developer Studio requiring Java 1.6 for all features to function. 3.2.2. Installation JBoss Developer Studio comes with a universal installer, allowing you to use the same file to install on Linux, Windows and Max OS X operating systems. T he following steps show you how to install JBoss Developer Studio: You can download the universal installer from here the Red Hat Customer Portal. Run the following command in a terminal window:
java -jar jbdevstudio-product-universal-5.0.0.GA.jar
Figure 3.1. JBoss Developer Studio Installation Wizard Accept the license agreement.
15
Figure 3.2. Accepting the license agreement Provide the installation path
Figure 3.3. Set installation path Select the appropriate Java Virtual Machine
Tip:
By selecting Default Java VM you set the default Java VM of your system (to verify your Java environment, type "java -version" in console). Selecting the Specific Java VM option will allow you to provide the path to a specific Java VM installation.
16
Figure 3.4 . Select Java VM T his step lets you select a location that will be used to search for locally available JBoss servers upon first running of JBoss Developer Studio:
Figure 3.5. Selecting a location to search for JBoss servers T o add a location click on the Add button. When the Add button is clicked you are prompted to select the folder from which to search for available JBoss Application Servers. Click the OK button to select the chosen location. T his location and subsequent directories will be searched for any JBoss server instances when you launch JBoss Developer Studio. Click the Next button to bring up a summary page where you can check your installation paths and see the components that will be installed. If you'd like to change something, press the Previous button. Click the Next button to start installation.
17
Figure 3.7. Installation Once installation completes you will have the option to create shortcuts to JBoss Developer Studio.
18
Figure 3.8. Shortcut creation T he final screen will declare that Installation has com pleted successfully. Click the Done button.
19
AutomatedInstallation/com.jboss.jbds.installer.PathInputPanel/installpath: Installation folder AutomatedInstallation/com.jboss.jbds.installer.JBossAsSelectPanel/installgroup: jbds com.izforge.izpack.panels.ShortcutPanel: Shortcut menu for installation
Note
If you change the installation folder path, you must update the com.izforge.izpack.panels.ShortcutPanel parameter to reflect the new path. Once you have configured the InstallConfigRecord.xm l file for your needs, the following command can be run on the command line to begin installation:
java -jar /path/to/installer.jar /path/to/InstallConfigRecord.xml
Current limitations T he following limitations currently exist when using the automated method of installation: Desktop shortcuts are not supported. Creation of shoortcuts for all users on a system has not been tested. Automated installation does not check if the specified installation path already exists. If the path does exist, any files will be overwritten without notice. T he Java Virtual Manchine to be used with JBoss Developer Studio is automatically chosen and cannot be specified. No verification exists to ensure the installer you are using is correct for your platform.
Warning
Automated installation does not check if the specified installation path already exists. If the path does exist, any files will be overwritten without notice. An example of an InstallConfigRecord.xm l file is available below:
20
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <AutomatedInstallation langpack="eng"> <com.jboss.jbds.installer.HTMLInfoPanelWithRootWarning id="introduction"/> <com.izforge.izpack.panels.HTMLLicencePanel id="licence"/> <com.jboss.jbds.installer.PathInputPanel id="target"> <installpath>/opt/local/JBDS5/GA</installpath> </com.jboss.jbds.installer.PathInputPanel> <com.jboss.jbds.installer.JREPathPanel id="jre"/> <com.jboss.jbds.installer.JBossAsSelectPanel id="as"> <installgroup>jbds</installgroup> </com.jboss.jbds.installer.JBossAsSelectPanel> <com.jboss.jbds.installer.UpdatePacksPanel id="updatepacks"/> <com.jboss.jbds.installer.DiskSpaceCheckPanel id="diskspacecheck"/> <com.izforge.izpack.panels.SummaryPanel id="summary"/> <com.izforge.izpack.panels.InstallPanel id="install"/> <com.jboss.jbds.installer.CreateLinkPanel id="createlink"> <jrelocation>/usr/lib/jvm/java-1.6.0-sun1.6.0.30.x86_64/jre/bin/java</jrelocation> </com.jboss.jbds.installer.CreateLinkPanel> <com.izforge.izpack.panels.ShortcutPanel id="shortcut"/> <com.jboss.jbds.installer.ShortcutPanelPatch id="shortcutpatch"/> <com.izforge.izpack.panels.SimpleFinishPanel id="finish"/> </AutomatedInstallation>
3.4. Upgrading
Because JBoss Developer Studio 4.0x and 5.0 use different versions of Eclipse, it is not possible to directly upgrade from an older version to JBoss Developer Studio 5.0.
Note
It is possible to run JBoss Developer Studio 4.0x and 5.0 side by side, as long as they have been installed into separate directories.
21
Figure 4 .1. Welcome to JBoss Developer Studio Click Get started with JBoss Central to begin using JBoss Developer Studio.
Figure 4 .2. Usage plug-in pop-up Once enabled, the plug-in will remain active until turned off. T o turn the active plug-in off, navigate to Window Preferences JBoss T ools Usage Reporting. T he gathered data allows JBoss to see how the tools are being used and where they are being used geographically. Currently we are looking into the operating systems being used, screen resolution and
22
how often the tooling environment is started. In the future geographic information will assist in focusing translation resources to areas where the developer environment is most used. T he plug-in uses Google Analytics to track and report data by acting as if you were visiting the site http://jboss.org/tools/usage/. T o view the type of information being collected, refer to Section 4.2.1, Collected usage information guide. T o view the source code of the usage plug-in visit http://anonsvn.jboss.org/repos/jbosstools/trunk/usage/. 4 .2.1. Collected usage information guide Below you will find an outline of the information that is reported and the Goolge Analytics fields that are used to gather this information. Version T he Content field has been modified to report the installed JBoss Developer Studio version. Sample returned values include: jbdevstudio-linux-gtk-x86_64-4.0.0.v201009301221R-H20Beta1.jar and jbdevstudio-linux-gtk-3.0.2.v201009161622R-H138-GA.jar. Installed components T he Keyword field has been modified to report the installed JBoss Developer Studio components. Sample returned values include: JBoss AS, Drools, T eiid and ModeShape. Visitor type T he Visitor type field reports if the current user is new or returning. Language T he Language field reports the localized language the product is being used in. Sample returned values include: en-US, de-DE and fr-FR. Location fields T he location fields report the geographical location where the product is being used based on the continent, country and city. Sample returned values include: Europe (continent), Germany (country) and Munich (city). Eclipse interface and version T he Browser field has been modified to report the Eclipse interface and version being used. Sample returned values include: JBoss Developer Studio: 5.0.0 and JBoss Developer Studio: 5.0.1. Operating System T he Operating System field reports the Operating System and its version that the product is running on (with Linux distribution version reporting conducted through the User Defined Value field). Sample returned values include: Linux, Macintosh 10.6, Macintosh 10.7 and Windows 7.
23
Linux distribution version T he User Defined Value field reports the distribution and version of Linux, if one is being used as the Operating System. Sample returned values include: Red Hat Enterprise Linux 6 and Fedora 16 Screen colors T he Screen colors field reports the color depth being used. Sample returned values include: 32-bit and 24-bit. Screen resolution T he Screen resolution field reports the resolution being used. Sample returned values include: 2048x1536 and 1920x1080. Java version T he Flash version field has been modified to report the Java version used. Sample returned values include: 1.6.0_20. Connection speed T he Connection speed field reports the type of internet connection being used. Sample returned values include: T 1, Cable and DSL. JBoss Central Enabled T he JBoss Central Enabled field reports whether JBoss Central is set to be seen upon startup or not. Returned value is either true or false.
24
Figure 5.2. Search Options Performing a search will launch a web browser as a new tab, displaying the results page. You can interact with the browser as you would any other web browser.
25
Figure 5.3. Search Results From the Create Projects section you can create a Dynam ic Web Project, OpenShift Express Application, Java EE Web Project, Java EE Project, HT ML5 Project, Spring MVC Project, RichFaces Project, GWT Web Project, or any one of many Project Exam ples. T o access a complete list of projects you can create, click on the window icon at the topright of the Create Projects section .
Note
All wizards generate Maven based projects, except for the Dynam ic Web Project wizard.
GWT (Google Web T oolkit) Web Project creation T o create a GWT web project, the latest m2e-wtp and Google plug-ins have to be installed. If these plugins have not been previously installed, the first page of the GWT web project wizard will provide you with the ability to install the plug-ins.
26
Figure 5.5. GWT Web Project creation: plug-in page Under the Project Exam ples section you can expand and view JBoss Quickstarts. Each quickstart is an example to assist first time users.
Figure 5.6. Project Examples For an in-depth look into the installation of project examples go to Section 5.3, Project Example Installation. You can also download other examples and install and set runtime preferences through the Project Exam ples section by using the five buttons at the top-right. T he first button launches a New Project Exam ples wizard. Here you can search and download project examples to assist you with
27
getting started.
By clicking on the second button you will be taken directly to the JBoss T ools Runtim e Detection dialog within Preferences.
28
T he third
button takes you directly to the Server Runtim e Environm ents preferences dialog.
29
T he final button
T he Docum entation section of JBoss Central contains links to help materials such as reference guides, user forums and documentation concerning new features.
Figure 5.10. Documentation links If you do not wish to see JBoss Central at every startup, you can deselect the checkbox Show on Startup in the Settings section.
30
Figure 5.11. Settings section T he News and Blogs sections are updated automatically, bringing you the latest information concerning JBoss technologies.
Note
After using JBoss Central once, the current content will be available offline. T his includes project example archives and descriptors, maven artifacts, and news and blog feeds.
31
Warning
Some software available through this tab is third-party community software that Red Hat has no control over. Installing third-party software may impact the level of support that Red Hat can provide. T o install or update software, select the checkbox beside one or more components.
Once you have selected all the components to update or install, click the button at the bottom left of the tab window. A screen will then appear offering you the option of deselecting a part of the component if you wish.
32
Figure 5.15. Component selection You will then be asked to confirm the selection of components to install. T o accept the selection press the Next button. You can change the components by pressing the Back button.
Figure 5.16. Component verification After pressing the Next button you will need to accept the term s of the license agreem ent for the associated software being installed. T o do this select the corresponding radio button. Click Finish to begin installation.
33
Figure 5.17. Licenses review As the installation process takes place you can choose to have further details displayed or run the installation in the background.
Figure 5.18. Licenses review After the software has been downloaded, you will be asked to verify the installation of the components if the contents are unsigned. Install unsigned third-party components with discretion.
34
Figure 5.19. Installing unsigned content Once installation is complete, restart JBoss Developer Studio by pressing the Restart Now button that appears.
Figure 5.20.
Figure 5.21. Project Examples T his section will guide you through the installation of the Helloworld example. Click on the Helloworld item in the Quickstarts list. An installation wizard for the example will open and automatically search for required components on your system. If a particular component is not found (a plug-in or a required version of the JBoss server), the component will be automatically downloaded for you during example installation.
35
Figure 5.22. Project Examples Click the Next button. You will be asked to define the install location for the example. Your curent workspace will be selected by default.
36
Figure 5.23. Project Examples Click the Finish button to begin installation of the example. Once the example has been installed it will appear in the list of projects within your Project Explorer.
37
Figure 6.1. JBoss Perspective T he JBoss perspective views include: Project Explorer, Outline, Palette, Properties and Servers. Certain menus also see a change in available items. T hese menus include File New, Window Show View and the context menu for a project. A selection of the menu items for File New can be seen in Figure 6.2, JBoss Perspective: File New.
Figure 6.2. JBoss Perspective: File New A selection of the menu items for Window Show View can be seen in Figure 6.3, JBoss Perspective: Window Show View .
38
Figure 6.3. JBoss Perspective: Window Show View A selection of the menu items for the context menu of a project can be seen in Figure 6.4, JBoss Perspective: Context Menu New .
39
40
Note
T his chapter assumes you have a JBoss application server installed on your system. If you do not, consult the installation instructions that accompanied your server.
Figure 7.1. Selecting Server Name and Server T ype T o setup the new runtime, click the Next button. In the next dialog verify the specified information and set local or remote server information.
41
Figure 7.2. JBoss Runtime Summary Lastly, a screen will appear that will allow you yo modify projects that are to be configured for the server. Click the Finish button.
42
Figure 7.3. Configuring Projects A new JBoss Server should now appear in the Servers view.
43
Figure 7.6. Console Output When the server is started you should see Started in the square brackets right next its name in the Servers view.
Figure 7.8. Stopping Server When the server is stopped you will see Stopped in the square brackets next to its name.
44
Here you can specify some common settings: host name, server name, runtime as well as settings related to publishing, timeouts and server ports.
45
Chapter 8. Example of developing a Java EE6, HTML5, Maven application for mobile devices
8.1. Purpose and Target Audience
We illustrate here how to bring together the best features of Java EE 6, HT ML5 and JBoss to create a rich, mobile-optimized and dynamic application https://github.com/jboss/ticket-monster. T hrough this tutorial, you will: Create a Java EE 6 project via a Maven archetype Leverage Maven to Eclipse infrastructure (m2e) and m2e-wtp Create a JPA entity using Forge Utilize Hibernate T ools Generate a database schema Deploy an application to a local JBoss Server Add a JAX-RS endpoint to an application Add a jQuery Mobile client T est the application for mobile compatibility with BrowserSim
46
Chapter 8. Example of developing a Java EE6, HTML5, Maven application for mobile devices
is not already viewable. Select Java EE Web Project from JBoss Central, under Create Projects. T his archetype provides a Maven-based project that can be built outside of the IDE, in continuous integration solutions like Hudson and Jenkins.
Figure 8.2. JBoss Central Once Java EE Web Project has been selected you will be prompted with a dialog box. If you are in a brand new workspace, the application server will not be configured and the checkbox on the server runtime row will not be checked.
47
Figure 8.3. New Project Wizard If you have not downloaded an application server, you can download and install a community server by clicking on the Download and Install button. T o add a JBoss server you have downloaded, click on the Install button. Selecting Install will launch the JBoss Runtime Detection section of Preferences.
48
Chapter 8. Example of developing a Java EE6, HTML5, Maven application for mobile devices
Figure 8.4 . JBoss T ools Runtime Detection Select the Add button and select the main directory of your unzipped JBoss server.
49
Figure 8.6. Searching for runtimes window Select OK. Once runtime detection is complete, you will see the server added to the Paths list.
50
Chapter 8. Example of developing a Java EE6, HTML5, Maven application for mobile devices
Figure 8.7. JBoss T ools Runtime Detection Completed Select OK to close the Preferences Dialog Returning to the New Project Example dialog, it will now have the JBoss application server checkbox selected.
51
52
Chapter 8. Example of developing a Java EE6, HTML5, Maven application for mobile devices
Figure 8.9. New Project Wizard Step 2 T he default Project name is jboss-javaee6-webapp and the T arget Runtime will be empty. If you decide to target a specific Enterprise Application Platform, you will first need to configure the enterprise Maven repositories. T argetting a runtime and configuring Maven repositories is beyond the scope of this guide, however the JBoss Web Framework Kit Maven Repository User Guide available through http://docs.redhat.com/docs/en-US/ would assist in your Maven repository installation. Select Finish and the project will be generated, and imported into your workspace.
53
Figure 8.11. Show In Forge Console You will be prompted with a dialog indicating Forge Not Running; select Yes
54
Chapter 8. Example of developing a Java EE6, HTML5, Maven application for mobile devices
Figure 8.12. Show Forge Not Running If you are not prompted you can start Forge using the green arrow in the Forge Console tab.
Figure 8.13. Forge Console Forge allows you to interactively type commands that generate code and update the IDE. You can complete commands via the T ab key. T he overall commands are as follows:
entity --named Event --package org.jboss.tools.examples.model field string --named name validation setup constraint NotNull --onProperty name constraint Size --onProperty name --min 5 --max 50 --message "Must be > 5 and < 50" field string --named description constraint Size --onProperty description --min 20 --max 1000 --message "Must be > 20 and < 1000" field boolean --named major field string --named picture
At the line [jboss-jbossee6-webapp] model $ type in en and hit the tab key on your keyboard. entity will fill in. Hit tab again and entity --nam ed will appear. T ype in Event and add a space, Forge can not anticipate the name of your new entity. Hit tab again and select --package. Now, hit tab 5 times to fill in org.jboss.tools.exam ples, and since there are multiple entries underneath examples, Forge
55
will display those options. T ype in m and hit tab to select m odel. Press the Enter key to watch the command execute.
Figure 8.14 . Forge new entity T he Event entity will be generated and placed into the m odel package. T he entity will then be opened in the editor.
Note
T he "@Entity public class" line is generated on the same physical line as "import java.lang.Override". At the Forge prompt, you will notice that you have been switched into Event.java T ype ls, providing a list of the fields and methods.
56
Chapter 8. Example of developing a Java EE6, HTML5, Maven application for mobile devices
Figure 8.16. Forge ls Now that the base Event entity has been created, add the fields and their JSR 303 Bean Validation constraints. T his next step involves adding a name property for the Event entity. T ype fie and hit tab to fill in field, if you hit tab again, Forge will list out the possible field types. T ype in s and hit tab, Forge will respond with string. Hit tab again to get --nam ed and type in nam e. T he resulting command should be field string --nam ed nam e and then press the Enter key. T his will add a private String name member variable and the appropriate get/set methods. You should also notice that the toString method is tweaked to include name as well.
Use the Outline view to see the results of Forge on the Event.java JPA entity. T he view is on the rightside when using the JBoss Perspective.
57
58
Chapter 8. Example of developing a Java EE6, HTML5, Maven application for mobile devices
insert into Event (id, name, description, major, picture, version) values (2, 'Rock concert of the decade', 'Get ready to rock...', true, 'http://dl.dropbox.com/u/65660684/640px-Weir%2C_Bob_(2007)_2.jpg', 1);
Right-click on the editor, and from the context menu, select Source Generate Getters and Setters.
59
Figure 8.19. Generate Getters and Setters Menu T his will create getX and setX methods for all private variables, making them accessible by the entity class.
Figure 8.20. Generate Getters and Setters Dialog Select All and OK
60
Chapter 8. Example of developing a Java EE6, HTML5, Maven application for mobile devices
Figure 8.21. Venue.java with gets/sets Right-click on the editor and from the context menu select Source Generate Hibernate/JPA Annotations. If you have not yet saved Venue.java, you will prompted to do so.
61
Figure 8.22. Save Modified Resources T he Hibernate: add JPA annotations wizard will launch. Ensure that Venue is the class you are working on.
62
Chapter 8. Example of developing a Java EE6, HTML5, Maven application for mobile devices
Figure 8.23. Hibernate: add JPA annotations Select Next. T he next step in the wizard will provide a sampling of the refactored sources. T he changes being made to your Venue class will be detailed.
63
Figure 8.24 . Hibernate: add JPA annotations Step 2 Click Finish You can now enter the Bean Validation annotations ( for example, @NotNull) for each variable.
8.6. Deployment
Ensure that you have installed the h2console.war file into the deployments directory. T he WAR file can be copied from the quickstarts directory. You can find the enterprise quickstarts in the Customer Portal, or the unsupported community quickstarts can be downloaded from http://www.jboss.org/jbossas/downloads/.
64
Chapter 8. Example of developing a Java EE6, HTML5, Maven application for mobile devices
Figure 8.25. Quickstarts Directory Layout Drag and drop the h2console.war file into deployments. Notice the .deployed files, if an error occurs you should see a .failed file instead.
Figure 8.26. h2console.war in deployments T o deploy the project, right click on the project name in the Project Explorer and from the context menu select Run As Run on Server. If needed, this will start the application server instance, compile, build and push the application into the JBoss/standalone/deploym ents directory.
65
Figure 8.27. Run As Run on Server By deploying the project in this way, the internal web browser will also be launched with the appropriate URL for the application.
66
Chapter 8. Example of developing a Java EE6, HTML5, Maven application for mobile devices
Figure 8.28. Web browser interaction With a web browser, navigate to http://localhost:8080/h2console
67
Figure 8.29. h2console in browser Enter jdbc:h2:m em :jboss-javaee6-webapp in as the JDBC URL. T his file is found in src\m ain\webapp\WEB-INF\ Set the password to sa and click Connect. Your Event has now been dynamically added into the H2 schema. T o verify that your new EE 6 JPA entity called Event has been added to the system, deployed successfully and created the supporting RDBMS schema, use the SQL statement: select * from event and press the Run button. T he data you previously entered in the im port.sql file will be displayed.
68
Chapter 8. Example of developing a Java EE6, HTML5, Maven application for mobile devices
69
Figure 8.31. New Class EventService Click Finish. T he new EventService.java file will now be opened in the Java editor. Copy the following code into the EventService.java file:
70
Chapter 8. Example of developing a Java EE6, HTML5, Maven application for mobile devices
package org.jboss.tools.examples.rest; @Path("/events") @RequestScoped public class EventService { @Inject private EntityManager em; @GET @Produces(MediaType.APPLICATION_JSON) public List<Event> getAllEvents() { final List<Event> results = em.createQuery( "select e from Event e order by e.name").getResultList(); return results; } }
71
Still in the Java editor, right-click and from the context menu select Source Organize Imports.
Figure 8.33. Source Organize Imports Some of the class names are not unique. You will be prompted with any decisions for an intended class. Select the following: javax.ws.rs.core.MediaT ype org.jboss.tools.examples.model.Event javax.ws.rs.Produces java.util.List java.inject.Inject java.enterprise.context.RequestScoped T he following screenshots illustrate how you handle these decisions. T he description of each screenshot indicates the name of the class you should select.
72
Chapter 8. Example of developing a Java EE6, HTML5, Maven application for mobile devices
73
74
Chapter 8. Example of developing a Java EE6, HTML5, Maven application for mobile devices
Figure 8.39. javax.enterprise.context.RequestScoped You should now see the following code contained within your EventService.java file:
import java.util.List; import import import import import import import javax.enterprise.context.RequestScoped; javax.inject.Inject; javax.persistence.EntityManager; javax.ws.rs.GET; javax.ws.rs.Path; javax.ws.rs.Produces; javax.ws.rs.core.MediaType;
import org.jboss.tools.examples.model.Event;
Save the changes you have made to the EventService.java and you will see it listed under the JAXRS REST Web Services section of the project, in the Project Explorer.
75
Figure 8.4 0. Project Explorer JAX-RS Services You have successfully configured your JAX-RS endpoint. You can deploy your jboss-javaee6-webapp project to your local application server via Run As Run on Server or right-click on the project in the Servers tab and select Full Publish.
Figure 8.4 1. Full Publish Using a web browser navigate to the following URL:http://localhost:8080/jboss-javaee6webapp/rest/events. You will see the results of the query, formatted as JavaScript Object Notation (JSON) returned into the browser.
76
Chapter 8. Example of developing a Java EE6, HTML5, Maven application for mobile devices
Note
T he rest prefix is setup in a file called JaxRsActivator.java and it contains a small bit of code that configures the application for JAX-RS endpoints.
Figure 8.4 3. New HT ML File T he New HT ML File Wizard will launch. Enter the file name as m obile.htm l.
77
Figure 8.4 4 . New HT ML File src/main/webapp Click Next On the Select HT ML T em plate page, select HT ML5 jQuery Mobile Page.
78
Chapter 8. Example of developing a Java EE6, HTML5, Maven application for mobile devices
Figure 8.4 5. Select HT ML5 jQuery Mobile T emplate Click Finish Using a web browser navigate to http://localhost:8080/jboss-javaee6-webapp/mobile.html.
Note
HT ML files are deployed automatically, however if you find it missing, use >Full Publish or Run As Run on Server, as demonstrated in previous steps. You will see a dialog box stating Ready to Go.
79
Figure 8.4 6. jQuery Mobile T emplate T o connect your front-end to your back-end, edit the pageinit JavaScript event and include an invocation of the previously created JAX-RS service, Events. Insert the following block of code directly below the alert()
$.getJSON("rest/events", function(events) { // console.log("returned are " + results); var listOfEvents = $("#listOfItems"); listOfEvents.empty(); $.each(events, function(index, event) { // console.log(event.name); listOfEvents.append("<li><a href='#'>" + event.name + "</a>"); }); listOfEvents.listview("refresh"); });
Notes to assist understanding the above JavaScript code: Uses $.getJSON("rest/events") to interact with EventService.java // console.log has been commented out as it causes problems in Internet Explorer. References listOfItem s, declared in the HT ML using an id attribute .em pty is executed on the list, removing the items: One, T wo and T hree A Found event is appended to the unordered list (UL) in the HT ML listOfItem s is refreshed Refresh your browser to see the results.
80
Chapter 8. Example of developing a Java EE6, HTML5, Maven application for mobile devices
Figure 8.4 7. jQuery Mobile REST Results From within the JBoss Perspective, click on the icon representing a mobile phone to launch BrowserSim .
Figure 8.4 8. Mobile BrowserSim icon BrowserSim allows you to see how your project will be viewed on a range of mobile devices.
81
Figure 8.4 9. Mobile BrowserSim BrowserSim has a Devices menu. From this menu you can change the device type, orientation and browser dimensions.
82
Chapter 8. Example of developing a Java EE6, HTML5, Maven application for mobile devices
Figure 8.51. Mobile BrowserSim on Windows 7 You can also add your own custom device and browser types.
Figure 8.52. Mobile BrowserSim Custom Devices Window You can browse any website using BrowserSim , providing you have an Internet connection. By doing so you can view the source code of other mobile sites by navigating to File View Page Source.
83
84
85
Figure 9.1. Create New Web Project T he jspHello node should appear in the upper-left Package Explorer view.
86
Figure 9.3. Create JSP Page Our hello.jsp page will now appear in the Project Explorer view. 9.2.1. Editing a JSP Page Let's now make a little change so that a JSP page displays "Hello World!" message. Insert this line inside the <body> </body> tag:
<% System.out.println("Hello World!"); %>
Notice that content assist functionality is always available when you are typing:
87
Figure 9.4 . Content Assist in JSP Page After changes made your hello.jsp page should look like this:
Figure 9.5. Hello.jsp Page Source T his line will actually output "Hello World!" message in the Console. T o make the message displayed in the Browser, just replace this line with the simple Hello World!. 9.2.2. web.xml file When you are creating web project the wizard creates the web.xm l file for you automatically. T he web.xml file editor provided by JBoss Developer Studio is available in two modes: T ree and Source.
88
Figure 9.6. Web.xml in Design and Source Mode Both modes are fully synchronized. Let's add a mapping to our hello.jsp page in the web.xm l file. Switch to the Source tab. Add the next code into <welcom e-file-list> :
<welcome-file>hello.jsp</welcome-file>
If you go back to T ree tab you will see that the changes made in the Source tab are automatically reflected. Actually you do not really need to do any configurations right now. 9.2.3. Deploying the project Writing ant scripts and managing the packaging process can be quite a complicated and time consuming task for even the most trivial web applications. However, JBoss Developer Studio relieves you of this burden. All you need is to start your JBoss Server and launch your application in your favorite browser. You can also create a JAR archive with JBoss Developer Studio's Archive T ools and export it to any web server. 9.2.3.1. JAR Config Project archives managing is available through the Project Archives view. Select Window Show view Other JBoss T ools Project archives from the menu bar Select a project in Package Explorer you want to be archived In the Project Archives view you will see the that the project is now listed:
89
Figure 9.7. Project Archives Right click on the project and select the JAR type of archive.
Figure 9.8. Project Archives In the New JAR dialog you can see automatically selected default values.
Figure 9.9. New JAR Archive Click the Finish button. T he .JAR file will appear in Package Explorer and also in Project Archives view as structure tree:
90
Figure 9.11. Archive in Package Explorer Using the Project Archives view you can rebuild the archive:
9.2.3.2. Auto redeploy When you create a web application and register it on the JBoss Server as it is automatically deployed into the /deploy directory of the server. JBoss Developer Studio's auto-redeploy feature ensures you do not need to restart the server. Any changes made in the application in exploded format will trigger a redeployment on the server. You can also use the "Finger touch" button for a quick restart of the project without restarting the server:
91
Figure 9.13. Finger T ouch button T he "Finger" touches descriptors dependent on project (i.e. web.xml for WAR, application.xml for EAR, jboss-esb.xml in ESB projects). 9.2.4 . JSP Page Preview JBoss Developer Studio comes with JSP design-time preview features. When designing JSP pages you can easily preview how they will look during runtime. You can even attach your stylesheet to the Preview. Make a little change to hello.jsp page, e.g. put this code snippet:
<%= new java.util.Date() %>
Click the Save button. Switch to Preview page by clicking the Preview tab at the bottom of the page. You will see how the page will look at runtime. 9.2.5. Launch JSP Project Now launch the project onto a JBoss server: Start a JBoss Server from the Servers view by clicking the Start the server icon ( ).
Click the Run icon or right click your project folder and select Run As Run on Server. If you haven't made any changes in the web.xm l file or cleared it out you can launch the application by
right clicking the hello.jsp page and selecting Run on the Server( You should see the next page in a Browser :
).
Figure 9.14 . Running Project You have learnt how to organize a Dynamic Web Project with a minimal configuration, add new elements to it (in our case it is a JSP page), deploy, and run it on a JBoss Server from within JBoss Developer Studio.
92
Figure 10.1. Create New JSF Project Enter GuessNumber as a project name, in JSF Environment drop down list choose JSF 1.2 Leave everything else as it is and click the Finish button Our project will appear in the Project Explorer and Web Projects views. As you can see JBoss Developer Studio has created the entire skeleton for the project with all required libraries, faces-config.xm l file and web.xm l file.
93
Figure 10.2. New JSF Project As the project has been set up, new JSP pages should now be created.
94
Figure 10.3. Create pages folder Open the faces-config.xm l file. Right click anywhere on the diagram mode From the context menu select New View
95
Figure 10.4 . Create New View T ype pages/inputnumber as the value for the From View ID field Leave everything else as is and click the Finish button In the same way create another JSF view. T ype pages/success as the value for From View ID Select File Save On the diagram you will see two created views.
96
Figure 10.6. Create Connection Click on the pages/inputnumber page icon and then click on the pages/success page icon A transition should appear between the two icons of views.
Figure 10.7. Created Connection Select File Save from the menu bar
97
Every time you build the project, all .properties files will then be copied to the classes folder by default. Right click the JavaSource folder and select New Folder Enter gam e as the Folder name and click the Finish button Your resource file and java bean will be stored in this folder. Right click on the gam e folder and select New Properties File T ype messages as the value for "name" attribute and click the Finish button JBoss Developer Studio will automatically open messages.properties file for editing.
Figure 10.8. Messages.properties File Click the Add button for adding new attribute to your resource file Enter how_to_play for the "name" and Please pick a number between 0 and 100. for the value Click the Finish button Add the following properties using the same process:
makeguess_button=Make Guess trayagain_button=Play Again? success_text=How cool.. You have guessed the number, {0} is correct! tryagain_smaller=Oops..incorrect guess. Please try a smaller number. tryagain_bigger=Oops..incorrect guess. Please try a bigger number.
Select File Save from the menu bar Your .properties file should now look like follows:
98
Figure 10.9. Properties are Added T he Up and Down buttons allow you to move the attributes in the list. T o delete the attribute, select it and press the Delete button. If you want to change a value or a name of your attribute, select it and then click the Edit button. If the .properties file is rather big and there are a lot of entries in it, you can use filtering and regular expressions narrow down the list. T he Filter and Regular Expressions Search is implemented by an expandable panel, closed by default: When "Expression" is not selected (as by default), filter is case insensitive. When "Expression" is selected, filter uses regular expressions which are case sensitive
Figure 10.10. Filter and Regular Expressions Search Panel Enter the characters that should be searched for in the entries to the 'name' or 'value' input fields accordingly. T he filtered results will be displayed in the table below:
99
Figure 10.11. Filter results When using regular expressions please note, that regular expression syntax does not use "*" for any characters and "?" for any one character. It's necessary to use "." for any one character and ".*" for any characters. Symbols "*" and "?" are used to show that the preceding token is not required, for example, "a.a" matches "aba" but not "aa", while "a.?a" or a.*a" matches both; besides "a.*a" matches "abcda". T o find the exact match, use sequences \A and \z in expression. For example, expression "\Adate\z" matches only string "date"; expression "\Adate" matches "date" and "dateline", expression "date\z" matches "date" and "Begin date", and expression "date" matches all of them.
JBoss Developer Studio allows for quick generation of getters and setters for java bean. Right click the Num berBean.java file in the Package Explorer view Select Source Generate Getters and Setters... Check userNumber box and click the OK button
100
Figure 10.12. Generate Getters and Setters Add the declaration of the second variable
int randomNumber;
101
public NumberBean () { randomNumber = (int)(Math.random()*100); System.out.println ( "Random number: "+randomNumber); } public String playagain () { FacesContext context = FacesContext.getCurrentInstance(); HttpSession session = (HttpSession) context.getExternalContext().getSession(false); session.invalidate(); return "playagain"; } public String checkGuess () { // if guessed, return 'success' for navigation if ( userNumber.intValue() == randomNumber ) { return "success"; } else { FacesContext context = FacesContext.getCurrentInstance(); ResourceBundle bundle = ResourceBundle.getBundle("game.messages", context.getViewRoot().getLocale()); String msg = ""; // if number bigger, get appropriate message if ( userNumber.intValue() > randomNumber ) msg = bundle.getString("tryagain_smaller"); else // if number smaller, get appropriate message msg = bundle.getString("tryagain_bigger"); // add message to be displayed on the page via <h:messages> tag context.addMessage (null, new FacesMessage(msg)); // return 'tryagain' for navigation return "tryagain"; } }
102
package game; import import import import javax.faces.context.FacesContext; javax.servlet.http.HttpSession; javax.faces.application.FacesMessage; java.util.ResourceBundle;
public class NumberBean { Integer userNumber; int randomNumber; // random number generated by application public Integer getUserNumber () { return userNumber; } public void setUserNumber (Integer value) { this.userNumber = value; } // constructor, generates random number public NumberBean () { randomNumber = (int)(Math.random()*100); System.out.println ( "Random number: " + randomNumber); } public String playagain () { FacesContext context = FacesContext.getCurrentInstance(); HttpSession session = (HttpSession) context.getExternalContext().getSession(false); session.invalidate(); return "playagain"; } // check if user guessed the number public String checkGuess () { // if guessed, return 'success' for navigation if ( userNumber.intValue() == randomNumber ) { return "success"; } // incorrect guess else { // get a reference to properties file to retrieve messages FacesContext context = FacesContext.getCurrentInstance(); ResourceBundle bundle = ResourceBundle.getBundle("game.messages", context.getViewRoot().getLocale()); String msg = ""; // if number is bigger, get appropriate message if ( userNumber.intValue() > randomNumber ) msg = bundle.getString("tryagain_smaller"); else // if number smaller, get appropriate message msg = bundle.getString("tryagain_bigger"); // add message to be displayed on the page via <h:messages> tag
103
context.addMessage (null, new FacesMessage(msg)); // return 'tryagain' for navigation return "tryagain"; } } }
T he first navigation rule states that from any page (* stands for any page) an outcome of playagain will take you to the /pages/inputnum ber.jsp file. Outcome values are returned from backing bean methods in this example. T he second navigation rule states that if you are at the page /pages/inputnum ber.jsp, and the outcome is success, then navigate to the /pages/success.jsp page.
104
105
Figure 10.13. Insert h:form In the Insert T ag dialog select the id field and click on the second column. A blinking cursor will appear in a input text field inviting to enter a value of id
106
Figure 10.14 . Define Id of Form Enter inputNumbers and click the Finish button In source view you can see the declaration of a form.
Figure 10.15. Created Form First let's declare the properties file in the inputnum ber.jsp page using the loadBundle JSF tag. Add this declaration on the top of a page, right after the first two lines:
107
Figure 10.16. Code Assist Switch to Visual tab, where it is possible to work with the editor through a WYSIWYG interface Click the outputText item from the JSF HT ML group in the JBoss T ools Palette view, drag the cursor over to the editor, and drop it inside the blue box in the editor Select the second column in the value row. Click the ... button next to the value field JBoss Developer Studio will display a list of possible values:
Figure 10.17. Choose Value Expand Resource Bundles msg Select the how_to_play value and click the OK button. T hen click the Finish button.
108
Figure 10.19. Created OutputT ext Component Switch to Source mode and insert a <br/> tag after the <h:outputT ext> component to make a new line Click the Save button On the Palette click on inputText, drag the cursor over to the editor, and drop it inside the editor after the text Select the value row and click in the second column Click the ... button next to the value field Expand Managed Beans NumberBean Select userNumber value and click the OK button Select the Advanced tab Select the id row and click in the second column T ype userNumber in the text field Select the required row and click in the second column Click ... button next to the value field Expand Enumeration and select true as a value
109
Figure 10.20. Add "required" Attribute Click the OK button, then click the Finish button Go to Source mode Add the validation attribute to <f:validateLongRange> for user input validation
<h:inputText id="userNumber" value="#{NumberBean.userNumber}" required="true"> <f:validateLongRange minimum="0" maximum="100"/> </h:inputText>
Click the Save button Again select Visual mode On the Palette, click on commandButton, drag the cursor over to the editor, and drop it inside the editor after the inputT ext component. In the editing dialog select the value row and click on the second column Click the ... button next to the value field Expand Resource Bundles msg and select makeguess_button as a value Click the OK button Select the action row and click in the second column T ype #{NumberBean.checkGuess} in the text field Click the Finish button In Source mode add <br/> tags between the <outputT ext>, <inputT ext> and <com m andButton> components to place them on different lines inputnum ber.jsp page should look like this:
110
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF8"%> <%@ taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@ taglib prefix="h" uri="http://java.sun.com/jsf/html"%> <f:loadBundle basename="game.messages" var="msg"/> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <f:view> <h:form id="inputNumbers"> <h:outputText value="#{msg.how_to_play}"/> <br/> <h:messages style="color: blue" /> <br/> <h:inputText id="userNumber" required="true" value="#{NumberBean.userNumber}"> <f:validateLongRange minimum="0" maximum="100" /> </h:inputText> <br/> <br/> <h:commandButton action="#{NumberBean.checkGuess}" value="#{msg.makeguess_button}"/> </h:form> </f:view> </body> </html>
10.7.2. Editing success.jsp page We now edit the success.jsp page in the same way as we just edited the inputnum ber.jsp file. T he code for the success.jsp page should look like the following:
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> <f:loadBundle basename="game.messages" var="msg"/> <html> <head> <title></title> </head> <body> <f:view> <h:form id="result"> <h:outputFormat value="#{msg.success_text}"> <f:param value="#{NumberBean.userNumber}" /> </h:outputFormat> <br /> <br /> <h:commandButton value="#{msg.trayagain_button}" action="#{NumberBean.playagain}" /> </h:form> </f:view> </body> </html>
Again you can use code assist provided by JBoss Developer Studio when editing jsp page:
111
Figure 10.21. Code Assist for <f:param> T he success.jsp page is shown if you correctly guessed the number. T he <h:outputForm at> tag will get the value of success_text from the properties file. T he {0} in success_text will be substituted for by the value of the value attribute within the <f:param > tag during runtime. In the final result you have a button which allows you to replay the game. T he action value references a backing bean method. In this case, the method only terminates the current session so that when you are shown the first page, the input text box is clear and a new random number is generated. Switch to Preview mode to see how this page will look in a browser:
112
T he index.jsp page is the entry point of our application. It's just forwarding to the inputnum ber.jsp page. Right click the WebContent folder and select New JSP File Enter index for name field and click the Next button. Untick the Use JSP T em plate check box and click the Finish button. Edit the source of the file so it looks like the following:
<!doctype html public "-//w3c//dtd html 4.0 transitional//en"> <html> <body> <jsp:forward page="/pages/inputnumber.jsf" /> </body> </html>
Note the .jsf extension of a page. It means that we trigger the JSF controller servlet to handle the page according the servlet mapping in the faces-config.xm l file.
Figure 10.23. You are Asked to Enter a Number Between 0 and 100
113
Figure 10.24 . Your Input is Validated and an Error Message is Displayed if Invalid Input was Entered
Figure 10.25. After You Enter a Guess, the Application T ells You Whether a Smaller or a Larger Number Should be T ried
114
115
116
12.1. What should I do if the Visual Page Editor does not start under Linux
Linux users may need to do the following to get the Visual Page Editor to work correctly on their machines. 1. On Red Hat based Linux distributions install the libXp.i386 package 2. T ype
ln -s libstdc++.so.5.0.7 libstdc++.so.5
3. and/or use
yum install libXp
4. Open the JBoss Developer Studio perspective. If you see the Help view open, close it and restart JBoss Developer Studio 5. If it doesn't help and you use Fedora with Eclipse Version: 3.4.1, the issue can be produced because the libswt-xulrunner-gtk-34 4 9.so file doesn't present in eclipse-swt-3.4 .15.fc10.x86_64 .rpm /eclipse/plugins/org.eclipse.swt.gtk.linux.x86_64 _3.4 .1 .v34 4 9c.jar. T o add this file to eclipse you should: Decompress eclipse/plugins/org.eclipse.swt.gtk.linux.x86_3.4 .1.v34 4 9c.jar form eclipse-SDK-3.4 .1-linux-gtk-x86_64 .tar.gz Copy libswt-xulrunner-gtk-34 4 9.so file to your Fedora Eclipse location. Open the file jbdevstudio.ini, which can be found in your Fedora Eclipse location and add the following line:
-Dswt.library.path=/usr/lib/eclipse
,where /usr/lib/eclipse is the path to your eclipse folder. 6. If none of these work, do the following: Clear the JBoss Developer Studio log file,<workspace>\.m etadata\.log Start JBoss Developer Studio with the -debug option:
jbdevstudio -debug
Post the JBoss Developer Studio log file(<workspace>\.m etadata\.log) on the forums.
12.2. Visual Editor starts OK, but the Missing Natures dialog appears
117
Figure 12.1. Missing Nature Some functionality of Visual Editor may not work if a project doesn't have org.jboss.tools.jsf.jsfnature or org.jboss.tools.jst.web.kb.kbnature in .project configuration. T o fix this problem and turn off the message box execute next steps: 1. Right mouse button click on a project in Package Explorer. 2. Select Configure Add JSF Capabilities from the context menu. 3. Configure your project using Add JSF Capabilities wizard and press Finish. If you are sure that your project does not need JSF capabilities, just disable this message box by checking Do not show this dialog again! checkbox.
12.3. I have an existing Seam 1.2.1 project. Can I migrate or import the project into a JBoss Developer Studio Seam project?
Use the following steps to manually transfer an existing Seam 1.2.1 project into a new JBoss Developer Studio Seam project: Create a Seam Web project to get the JBoss tools structure T hen from your Seam 1.2.1 seam-gen project start doing the following: Copy src to src Copy view to Web content Copy resources individual files to where they are in the seam web project etc.
12.4. I have an existing Struts or JSF project. Can I open the project in JBoss Developer Studio?
Yes. From main menu select File File Import Other JSF Project (or Struts Project) and follow wizards steps.
12.6. Is it possible to increase the performance of Eclipse after installing your product?
JBoss Developer Studio configures eclipse via the jbdevstudio.ini file to allocate extra memory, but
118
if you for some reason need more memory then by default, you can manually make adjustments in this file. For example:
-vmargs -Xms128m -Xmx512m -XX:MaxPermSize=128m
12.7. How can I add my own tag library to the JBoss Tools Palette?
See the section on Adding T ag Libraries in the Visual Web T ools Guide.
12.8. How to get Code Assist for Seam specific resources in an externally generated project?
T o get Code Assist for Seam specific resources in an externally generated project, you should enable Seam features in Project Preferences. Right click an imported project and navigate Properties Seam Settings. Check Seam support box to enable all available Seam Settings.
119
Additional information:
Be sure to give us your name so that you can receive full credit for reporting the issue.
120
Revision History
Revision History
Revision 5.0.1-35 Rebuild for Publican 3.0 Revision 1-0 Initial creation of book 2012-07-18 Anthony T owns
Isaac Rooskov