Jan 30 2009

Create Flex Applications with NetBeans 6.5 and FlexBean

Published by Siegfried Bolz at 11:36 pm under NetBeans, adobe flex



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: , , , , ,


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

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

  2. Mallikon 15 Apr 2009 at 9:02 am

    This is very help full to all.

  3. kalpaon 30 May 2009 at 8:15 am

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

  4. Ericon 03 Jun 2009 at 5:27 pm

    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ücelon 06 Jun 2009 at 12:58 pm

    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. Marcelon 28 Sep 2009 at 8:08 pm

    Thanks for share your knowladge with us.

  7. Flex y Adobe Air | Yo, programadoron 14 Feb 2010 at 2:50 pm

    [...] 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. danion 16 Feb 2010 at 3:24 pm

    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. Muralikrishnanon 04 Mar 2010 at 11:35 am

    Hi dani ..

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

  10. [...] http://blog.jdevelop.eu/2009/01/30/create-flex-applications-with-netbeans-65-and-flexbean/ [...]

  11. Furqanon 11 May 2010 at 7:02 am

    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:\Users\Username\Documents\NetBeansProjects\SimpleFlexApp\src\Main.mxml(8): Error: The style ‘borderColor’ is only supported by type ‘mx.core.Application’ with the theme(s) ‘halo, spark’.

    C:\Users\Username\Documents\NetBeansProjects\SimpleFlexApp\src\Main.mxml(8): Error: The style ‘backgroundGradientAlphas’ is only supported by type ‘mx.core.Application’ with the theme(s) ‘halo’.

    C:\Users\Username\Documents\NetBeansProjects\SimpleFlexApp\src\Main.mxml(8): Error: The style ‘backgroundGradientColors’ is only supported by type ‘mx.core.Application’ with the theme(s) ‘halo’.

    C:\Users\Username\Documents\NetBeansProjects\SimpleFlexApp\build.xml:82: The following error occurred while executing this line:
    C:\Users\Username\Documents\NetBeansProjects\SimpleFlexApp\build.xml:179: exec returned: 3
    BUILD FAILED (total time: 8 seconds)

  12. javalupoon 22 May 2010 at 12:09 am

    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

  13. Joeon 15 Jun 2010 at 10:20 pm

    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:\…\NetBeansProjects\SimpleFlexApp\build.xml:82: The following error occurred while executing this line:
    C:\…\NetBeansProjects\SimpleFlexApp\build.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

  14. FlexBean « Bruno Farinaon 01 Jul 2010 at 5:03 pm

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

  15. shlok25on 12 Jul 2010 at 4:25 pm

    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?

Trackback URI | Comments RSS

Leave a Reply

*
To prove that you're not a bot, enter this code
Anti-Spam Image

Note: To submit your comment you have to preview it at first!