Jan 30 2009

Create Flex Applications with NetBeans 6.5 and FlexBean

Published by at 11:36 PM under adobe flex,NetBeans



In this Blog i will show you how to develop Adobe Flex Applications with the NetBeans 6.5 IDE. The used plugin FlexBean is still under development by Arnaud Vincent . Many features are missing in the Version 1.0.1 used in this Blog, for example syntax highlighting and a GUI-Designer.


Please note:
I have contributed this blog to the NetBeans Community.


Table of contents



Introduction

In this “proof-of-concept” you will create a Flex Application which sends Login-Data to a Java-Servlet (also created with NetBeans 6.5). The Servlet returns an answer which will be interpreted by the Flex Application. It is a very simple Application, you should only see how easy it is to go productive with FlexBean.


FlexBean Plugin

Before you can create Flex Applications with NetBeans, you have to install the FlexBean Plugin. Follow the Instructions for the Installation.


Create the Flex Application

Create a new “Flex Application”-Project.

bild1


Name the Project “SimpleFlexApp” and hit “Finish“.

bild2


You see now the new Project with the opened MXML-File.

bild3


Replace the Content of “Main.mxml” with this Code:


Main.mxml

<?xml version="1.0" encoding="utf-8"?>
<!-- Simple Flex App which sends login-data to a Servlet
	 located at: http://localhost:8084//simplelogin/loginservlet

	 @author Siegfried Bolz
-->

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" applicationComplete="" color="#FFFFFF" layout="absolute" borderColor="#FDFEFF" backgroundGradientAlphas="[1.0, 1.0]" backgroundGradientColors="[#205CF6, #01013D]" width="400" height="300">

	<mx:Script>
		<![CDATA[

			import mx.events.ValidationResultEvent;
			import mx.controls.Alert;
 			import mx.rpc.events.FaultEvent;
         	import mx.rpc.events.ResultEvent;


			private function validateID(event:MouseEvent):Boolean{
				 if (idValidator.validate().type == ValidationResultEvent.VALID) {
				 	return true;
			     } else{
				 	Alert.show("Please insert an ID !");
				 	return false;
				 }
			}


			private function validatePassword(event:MouseEvent):Boolean {
				 if (passValidator.validate().type == ValidationResultEvent.VALID){
				 	return true;
			     } else{
				 	Alert.show("Please insert a Password !");
				 	return false;
				 }
			}


			private function checkLoginData(event:MouseEvent):void {
			     if (validateID(event)==true && validatePassword(event)==true) {
			 		submitLoginData(txtID.text,txtPassword.text);
			 	 }
			}



			private function submitLoginData(id:String, password:String):void {
				lblError.visible = false;
				var login:LoginVO = new LoginVO(id,password);
				loginService.cancel();
				loginService.send(login);
			}


			private function onResult(event:ResultEvent):void{
				var resultObj:Object = event.result;
			 	var result:String = resultObj.message;

			 	if (result=="true") {
			 		Alert.show('Login successful!');
			 	} else {
			 		Alert.show('Login denied!');
			 	}

			}


	        private function serverFault(evt:FaultEvent):void {
				lblError.visible = true;
	        }


		]]>
	</mx:Script>


    <!-- Connection to the Server -->
    <mx:HTTPService id="loginService" useProxy="false" method="POST" resultFormat="object"
    	url="http://localhost:8084//simplelogin/loginservlet" result="onResult(event)"
    	fault="serverFault(event);" />

   	<!-- Validators -->
    <mx:StringValidator id="idValidator" source="{txtID}" property="text" triggerEvent=""/>
    <mx:StringValidator id="passValidator" source="{txtPassword}" property="text" triggerEvent=""/>

    <!-- GUI Elements -->
    <mx:Label text="Please insert your Login data" fontWeight="bold" x="122.5" y="32" fontSize="12"/>
    <mx:Label text="ID" x="72" y="71" fontSize="11" fontWeight="bold"/>
    <mx:Label text="Password" x="72" y="129" fontSize="11" fontWeight="bold"/>
    <mx:TextInput x="72" y="87" editable="true" color="#010000" id="txtID"/>
    <mx:TextInput x="72" y="144" color="#020000" displayAsPassword="true" id="txtPassword" editable="true"/>
    <mx:Button x="72" y="195" label="Submit" id="cmdSubmit" click="checkLoginData(event)"/>
    <mx:Label x="72" y="242" text="Error, wrong login data!" width="222" id="lblError" color="#FF0000" fontSize="16" fontWeight="bold" visible="false"/>

</mx:Application>


Create a new ActionScript-File, name it “LoginVO” and paste this code into it:


LoginVO.as

/**
 * Transfer-Object for the HTTPService-call.
 *
 * @author Siegfried Bolz
 */
package
{
	public class LoginVO {

		public var id:String;
		public var password:String;


		// Konstruktor
		public function LoginVO(id:String,password:String) {

			this.id = id;
			this.password = password;

		}

	}
}


bild5a1


Your Project have to look like this:

bild4


Build the Project to see that everything is working.

bild5c


If you get this error: “Error: could not find a JVM“:

bild5d


your Flex SDK Configuration File is invalid. Open the file “jvm.config” located in your “<SDK>/BIN” -directory and check that the variable “java.home=” is set to a valid Java JRE directory (remove the last slash!). Here is an example:

java.home=C:/Program Files/Java/jre1.6.0_07



Java Servlet

Create a new Java Web Application Project, name it “SimpleLogin” and add a Servlet (LoginServlet.java) with URL-Pattern “/loginservlet“.

bild5b


Paste this Code into the file:

LoginServlet.java

package eu.jdevelop.blog.flexbean;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Login Servlet
 *
 * @author Siegfried Bolz
 */
public class LoginServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {

            String id = request.getParameter("id");
            String password = request.getParameter("password");

            System.out.println("received data from the Flex Application: id=" + id + " password=" + password);

            if (id==null || password==null) {
                out.println("<message>false</message>");
            } else {
                out.println("<message>true</message>");
            }

        } catch (Exception x) {
            System.out.println("Error: " + x.getMessage());
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}


bild6


Start the Application

First start the Java Servlet and than the Flex Application.

bild7


The Flash Player opens.

bild8


Insert some data and click on “Submit” to send the input to the Java Servlet.

bild9


If the connection is set up alright (check the HTTPService in “Main.mxml“) you will receive a positive answer.

bild10


As you can see, it is possible to work with NetBeans in the Flex Environment, but there are many improvements necessary to replace the Adobe Flex Builder with the FlexBean-Plugin. Arnaud Vincent has enriched the NetBeans-Community with a new way, how NetBeans can be used for the Development today. It shows how flexible the NetBeans-Platform is, to fit the needs of the future.


Downloads

NetBeans 6.5 Flex Project: download
NetBeans 6.5 Java Servlet Project: download
Adobe Flex Builder 3 Project: download

Technorati Tags: , , , , ,

24 responses so far

24 Responses to “Create Flex Applications with NetBeans 6.5 and FlexBean”

  1. [...] Siegfried Bolz No TweetBacks yet. (Be the first to Tweet this [...]

  2. Mallik sagt:

    This is very help full to all.

  3. kalpa sagt:

    Thanks for share your knowladge with us.I am engineering undergraduate so i am highly interested in this kind of stuffs.Thanks again.

  4. Eric sagt:

    Followed the instructions in the tutorial and was receiving a FaultEvent due to security.
    Had to add a crossdomain.xml to the ROOT of my tomcat where the servlet was deployed as per:

    http://kb2.adobe.com/cps/142/tn_14213.html

  5. Yücel sagt:

    Hello together,

    i tried this nice tutorial. But this works only with IE and not with Firefox 3. Does anybody know a way to solve this problem?

  6. Marcel sagt:

    Thanks for share your knowladge with us.

  7. [...] embargo, con Flex, trabajas con Flex Builder (un plugin para Eclipse, de pago), o con IntelliJ o Netbeans o con el bloc de notas. Tienes una estructura de clases y paquetes como en Java, y tienes tus [...]

  8. dani sagt:

    hi, i installed your plugin on my netbeans, under linux ubuntu, but… once i create a new flex project i can not choose the FlexSDK path, it appears empty with any options.
    I have installed the sdk and added to my root path but no works at all. :(

    any clues?

    PD: great job !

  9. Hi dani ..

    Go to Tools—> Flex Platforms —-> Add your Flex SDK path location thts it

  10. Furqan sagt:

    I able to set everything up but when I build the code it gives me warning about event handler is empty and then whole bunch of errors that says this:

    C:UsersUsernameDocumentsNetBeansProjectsSimpleFlexAppsrcMain.mxml(8): Error: The style ‘borderColor’ is only supported by type ‘mx.core.Application’ with the theme(s) ‘halo, spark’.

    C:UsersUsernameDocumentsNetBeansProjectsSimpleFlexAppsrcMain.mxml(8): Error: The style ‘backgroundGradientAlphas’ is only supported by type ‘mx.core.Application’ with the theme(s) ‘halo’.

    C:UsersUsernameDocumentsNetBeansProjectsSimpleFlexAppsrcMain.mxml(8): Error: The style ‘backgroundGradientColors’ is only supported by type ‘mx.core.Application’ with the theme(s) ‘halo’.

    C:UsersUsernameDocumentsNetBeansProjectsSimpleFlexAppbuild.xml:82: The following error occurred while executing this line:
    C:UsersUsernameDocumentsNetBeansProjectsSimpleFlexAppbuild.xml:179: exec returned: 3
    BUILD FAILED (total time: 8 seconds)

  11. javalupo sagt:

    Furgan,i got same problem and solve it. I tried to post here, but for some reason my xml code disapear. send me a mail, and i will help you. capalupo.java@yahoo.com

  12. Joe sagt:

    Hello,

    I have got the following problem with the tutorial:

    When clicking on ‘Build Flex’ to see if Flex has been configured properly, I receive the following error:

    C:…NetBeansProjectsSimpleFlexAppbuild.xml:82: The following error occurred while executing this line:
    C:…NetBeansProjectsSimpleFlexAppbuild.xml:179: exec returned: 3

    The XML to this errors is this:

    And this:

    In file ‘jvm.config’, I inserted the following:
    java.home=C:/Programme/Java/jdk1.6.0_17

    I`m using 6.9

    Does anybody know what`s going wrong?

    Best regards,
    Joe

  13. [...] para quem quer ver este post que me fascinou, clique aqui para ter acesso ao [...]

  14. shlok25 sagt:

    I am trying to install the Flexbean plugin, but after I download the zip file from the link provided and unzip it, there is no .nbm file? There’s only .jar and other files? How do I install the Flexbean plugin?

  15. Christian Myrstad sagt:

    I got the same problem as Joe, the test build (before creating the Simple Login project above) fails with
    /home/dfox/dev/SimpleFlexApp/build.xml:82: The following error occurred while executing this line:
    /home/dfox/dev/SimpleFlexApp/build.xml:179: exec returned: 3

    My Netbeans environment works perfectly for ordinary Java Web applications. I’m running Netbeans 6.8

    Any suggestions, anyone?

  16. Christian Myrstad sagt:

    Regarding my previous post – the problem seems to be that the example is flex 3, and I have installed flex 4. Trying to understand how the Application tag should be built now :-)

  17. neopreno sagt:

    I solved it.
    I had to install java5 32 bit version only. Now I have java6 for netbeans 6.9.1 and java5 for flex :-/

  18. SeAn sagt:

    hi im having this problem.
    could anyone help me out?

    C:UsersDocumentsNetBeansProjectsSimpleFlexAppsrcMain.mxml(8): Warning: Event handler is empty.

    C:UsersDocumentsNetBeansProjectsSimpleFlexAppsrcMain.mxml(8): Error: The style ‘borderColor’ is only supported by type ‘mx.core.Application’ with the theme(s) ‘halo, spark’.

    C:UsersDocumentsNetBeansProjectsSimpleFlexAppsrcMain.mxml(8): Error: The style ‘backgroundGradientAlphas’ is only supported by type ‘mx.core.Application’ with the theme(s) ‘halo’.

    C:UsersDocumentsNetBeansProjectsSimpleFlexAppsrcMain.mxml(8): Error: The style ‘backgroundGradientColors’ is only supported by type ‘mx.core.Application’ with the theme(s) ‘halo’.

    C:UsersDocumentsNetBeansProjectsSimpleFlexAppbuild.xml:82: The following error occurred while executing this line:
    C:UsersDocumentsNetBeansProjectsSimpleFlexAppbuild.xml:179: exec returned: 3

    email me at sean_rio16@hotmail.com thanx

  19. rie sagt:

    when i run flex app, it can’t be start. the error message :

    java.lang.NullPointerException
    at org.netbeans.module.flexbean.modules.project.actions.FlexProjectBuildCommand.getAntProperties(FlexProjectBuildCommand.java:211)
    at org.netbeans.module.flexbean.modules.project.actions.FlexProjectBuildCommand$1.run(FlexProjectBuildCommand.java:88)
    [catch] at java.lang.Thread.run(Thread.java:619)

    please for help…

  20. term paper sagt:

    I had no problems with the tutorial. If you read everything carefully, it’l work fine.

  21. nish sagt:

    Remove the backgroundGradientColors property values from your Main.mxml
    application. You’re trying to compile in Flex 4 an application created with a
    Flex 3 sdk.

    remove this line from your Main.mxml

    borderColor=”#FDFEFF” backgroundGradientAlphas=”[1.0, 1.0]” backgroundGradientColors=”[#205CF6, 01013D]“

  22. Akhilesh sagt:

    Anybody will suggest me the required settings in Tomcat. Can we compile Flex and Java code sententiously. And how we can configure Tomcat and Catalina settings on the local machine. Can we do it in Visual Studio 2010.

  23. I would like to thank you for the efforts you have made in writing this article. I am hoping the same best work from you in the future as well. In fact your creative writing abilities has inspired me to start my own BlogEngine blog now. Really the blogging is spreading its wings rapidly. Your write up is a fine example of it.