The integration of Flex into Java EE java+Flex separation configuration

Recommended for you: Get network issues from WhatsUp Gold. Not end users.
How to integrate Flex into the Java EE application? Now, we want to replace the existing Servlet and JSP pages with Flex, you need to make Flex and Java EE back-end communication. Flex supports multiple remote calls, including HTTP, Web, Services and AMF. However, according to the Java EE server application development, through the integration of BlazeDS, make full use of the AMF protocol and can easily exchange data with the Flex front end
1 download jar package
2 create project java_flex
First we need to download the jar from the Internet packet blazeds-bin-4.0.1.21287.zip jar unpacked the Lib inside all copy jar to a project's lib directory,
And then modify the web.xml file to add HttpFlexSession and Servlet mapping in web.xml. HttpFlexSession is a Listener BlazeDS, responsible for monitoring the Flex remote calls, and perform some initialization settings:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>java_flex</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <listener>
      <listener-class>flex.messaging.HttpFlexSession</listener-class>
  </listener>
  <servlet><!Configuration flexservlet->
      <servlet-name>messageBroker</servlet-name>
      <servlet-class>flex.messaging.MessageBrokerServlet</servlet-class>
      <init-param>
          <param-name>services.configuration.file</param-name>
          <param-value>/WEB-INF/flex/services-config.xml</param-value>
      </init-param>
      <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
      <servlet-name>messageBroker</servlet-name>
      <url-pattern>/messagebroker/*</url-pattern>
  </servlet-mapping>
</web-app>

All configuration files required for BlazeDS are placed in the /WEB-INF/flex/ directory. BlazeDS will read the services-config.xml configuration file, the file also cited the remoting-config.xml, proxy-config.xml and messaging-config.xml 3 configuration file, therefore, need a total of 4 configuration file.

services-config.xml :


<?xml version="1.0" encoding="UTF-8"?>
<services-config>

	<services>
		<service-include file-path="remoting-config.xml" />
		<service-include file-path="proxy-config.xml" />
		<service-include file-path="messaging-config.xml" />
	</services>

	<security>
		<login-command class="flex.messaging.security.TomcatLoginCommand"
			server="Tomcat" />
		<!-- Uncomment the correct app server <login-command class="flex.messaging.security.TomcatLoginCommand" 
			server="JBoss"> <login-command class="flex.messaging.security.JRunLoginCommand" 
			server="JRun"/> <login-command class="flex.messaging.security.WeblogicLoginCommand" 
			server="Weblogic"/> <login-command class="flex.messaging.security.WebSphereLoginCommand" 
			server="WebSphere"/> -->

		<!-- <security-constraint id="basic-read-access"> <auth-method>Basic</auth-method> 
			<roles> <role>guests</role> <role>accountants</role> <role>employees</role> 
			<role>managers</role> </roles> </security-constraint> -->
	</security>

	<channels>

		<channel-definition id="my-amf"
			class="mx.messaging.channels.AMFChannel">
			<endpoint
				url="http://{server.name}:{server.port}/{context.root}/messagebroker/amf"
				class="flex.messaging.endpoints.AMFEndpoint" />
			<properties>
				<polling-enabled>false</polling-enabled>
			</properties>
		</channel-definition>

		<channel-definition id="my-secure-amf"
			class="mx.messaging.channels.SecureAMFChannel">
			<endpoint
				url="https://{server.name}:{server.port}/{context.root}/messagebroker/amfsecure"
				class="flex.messaging.endpoints.SecureAMFEndpoint" />
			<properties>
				<add-no-cache-headers>false</add-no-cache-headers>
			</properties>
		</channel-definition>

		<channel-definition id="my-polling-amf"
			class="mx.messaging.channels.AMFChannel">
			<endpoint
				url="http://{server.name}:{server.port}/{context.root}/messagebroker/amfpolling"
				class="flex.messaging.endpoints.AMFEndpoint" />
			<properties>
				<polling-enabled>true</polling-enabled>
				<polling-interval-seconds>4</polling-interval-seconds>
			</properties>
		</channel-definition>

		<!-- <channel-definition id="my-http" class="mx.messaging.channels.HTTPChannel"> 
			<endpoint url="http://{server.name}:{server.port}/{context.root}/messagebroker/http" 
			class="flex.messaging.endpoints.HTTPEndpoint"/> </channel-definition> <channel-definition 
			id="my-secure-http" class="mx.messaging.channels.SecureHTTPChannel"> <endpoint 
			url="https://{server.name}:{server.port}/{context.root}/messagebroker/httpsecure" 
			class="flex.messaging.endpoints.SecureHTTPEndpoint"/> <properties> <add-no-cache-headers>false</add-no-cache-headers> 
			</properties> </channel-definition> -->
	</channels>

	<logging>
		<target class="flex.messaging.log.ConsoleTarget" level="Error">
			<properties>
				<prefix>[BlazeDS] </prefix>
				<includeDate>false</includeDate>
				<includeTime>false</includeTime>
				<includeLevel>false</includeLevel>
				<includeCategory>false</includeCategory>
			</properties>
			<filters>
				<pattern>Endpoint.*</pattern>
				<pattern>Service.*</pattern>
				<pattern>Configuration</pattern>
			</filters>
		</target>
	</logging>

	<system>
		<redeploy>
			<enabled>false</enabled>
			<!-- <watch-interval>20</watch-interval> <watch-file>{context.root}/WEB-INF/flex/services-config.xml</watch-file> 
				<watch-file>{context.root}/WEB-INF/flex/proxy-config.xml</watch-file> <watch-file>{context.root}/WEB-INF/flex/remoting-config.xml</watch-file> 
				<watch-file>{context.root}/WEB-INF/flex/messaging-config.xml</watch-file> 
				<watch-file>{context.root}/WEB-INF/flex/data-management-config.xml</watch-file> 
				<touch-file>{context.root}/WEB-INF/web.xml</touch-file> -->
		</redeploy>
	</system>

</services-config>

Because the BlazeDS needs to be exposed to the Java interface of FlexService Flex front end, therefore, we as a service in the configuration file for remoting-config.xml, FlexService interface declaration:

remoting-config.xml:
<?xml version="1.0" encoding="UTF-8"?>
<service id="remoting-service" 
    class="flex.messaging.services.RemotingService">

    <adapters>
        <adapter-definition id="java-object" class="flex.messaging.services.remoting.adapters.JavaAdapter" default="true"/>
    </adapters>

    <default-channels>
        <channel ref="my-amf"/>
    </default-channels>
    <destination id="test">
<properties>
<source>org.demo.service.impl.FlexServiceImpl</source> <!Note that the path - ->
<scope>application</scope>    
</properties>
</destination>
</service>



proxy-config.xml :

<?xml version="1.0" encoding="UTF-8"?>
<service id="proxy-service" 
    class="flex.messaging.services.HTTPProxyService">

    <properties>
        <connection-manager>
            <max-total-connections>100</max-total-connections>
            <default-max-connections-per-host>2</default-max-connections-per-host>
        </connection-manager>
        <allow-lax-ssl>true</allow-lax-ssl>
    </properties>

    <adapters>
        <adapter-definition id="http-proxy" class="flex.messaging.services.http.HTTPProxyAdapter" default="true"/>
        <adapter-definition id="soap-proxy" class="flex.messaging.services.http.SOAPProxyAdapter"/>
    </adapters>

    <default-channels>
        <channel ref="my-amf"/>
    </default-channels>

    <destination id="DefaultHTTP">
    </destination>

</service>



messaging-config.xml:

<?xml version="1.0" encoding="UTF-8"?>
<service id="message-service" 
    class="flex.messaging.services.MessageService">

    <adapters>
        <adapter-definition id="actionscript" class="flex.messaging.services.messaging.adapters.ActionScriptAdapter" default="true" />
        <!-- <adapter-definition id="jms" class="flex.messaging.services.messaging.adapters.JMSAdapter"/> -->
    </adapters>

    <default-channels>
        <channel ref="my-polling-amf"/>
    </default-channels>

</service>
Next we write java code (here I don't use framework).
BaseDao

package org.demo.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.jsp.jstl.sql.ResultSupport;


import org.apache.tomcat.dbcp.dbcp.BasicDataSource;

public class BaseDao {
	
	
	
	private static BasicDataSource bds = new BasicDataSource();
	
	static {
		bds.setDriverClassName("com.mysql.jdbc.Driver");
		bds.setUrl("jdbc:mysql://localhost:3306/myweb");
		bds.setUsername("root");
		bds.setPassword("123456");
	}
	
	public Connection getConnection(){
		try {
			//Class.forName("oracle.jdbc.driver.OracleDriver");
			//return DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:ORCL","liu","liu");
			return bds.getConnection();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public void closeReSources(ResultSet rs,Statement st,Connection conn){
		
			try {
				if(rs!=null)rs.close();
				if(st!= null) st.close();
				if(conn != null)conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
	}
	
	public int excuteUpdate(String sql,Object...params){
		Connection conn = null;
		PreparedStatement pst = null;
		int rt = 0;
		try{
			conn = getConnection();
			pst = conn.prepareStatement(sql);
			if(params != null && params.length>0){
				for (int i = 0; i <params.length; i++) {
					pst.setObject(i+1, params[i]);
				}
			}
			rt = pst.executeUpdate();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			closeReSources(null,pst,conn);
		}
		return rt;
	}
	
	public javax.servlet.jsp.jstl.sql.Result excuteQuery(String sql,Object...params){
		Connection conn = null;
		PreparedStatement pst = null;
		ResultSet rs = null;
		javax.servlet.jsp.jstl.sql.Result r = null;
		try{
			conn = getConnection();
			pst = conn.prepareStatement(sql);
			if(params != null && params.length>0){
				for (int i = 0; i <params.length; i++) {
					pst.setObject(i+1, params[i]);
				}
			}
			rs = pst.executeQuery();
			//Packaging ResultSet into Result
			r = ResultSupport.toResult(rs);
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			closeReSources(rs,pst,conn);
		}
		return r;
	}
}
The FileInfo entity:
package org.demo.po;

import java.sql.Timestamp;

public class FileInfo {
	
	private Integer id;
	private String name;
	private String realPath;
	private Timestamp date;
	
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getRealPath() {
		return realPath;
	}
	public void setRealPath(String realPath) {
		this.realPath = realPath;
	}
	public Timestamp getDate() {
		return date;
	}
	public void setDate(Timestamp date) {
		this.date = date;
	}
	
}
To expose to the interface of FlexService flex:

package org.demo.service;

import java.util.List;

import org.demo.po.FileInfo;

public interface FlexService {
	
	public List<FileInfo> getData(int num);
}

FlexServiceImpl class FlexServiceI:

package org.demo.service.impl;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.SortedMap;

import javax.servlet.jsp.jstl.sql.Result;

import org.demo.dao.BaseDao;
import org.demo.po.FileInfo;
import org.demo.service.FlexService;

public class FlexServiceImpl extends BaseDao implements FlexService {

	@Override
	public List<FileInfo> getData(int num) {
		List<FileInfo> files = new ArrayList<FileInfo>();
		try {
			Result r = super.excuteQuery("select * from tb_uploads limit "+num);
			if(r.getRowCount()!=0&&r!=null){
				
				for(SortedMap row :r.getRows()){
					FileInfo f = new FileInfo();
					f.setId(Integer.valueOf(row.get("id").toString()));
					f.setName(row.get("name").toString());
					f.setRealPath(row.get("realpath").toString());
					f.setDate(Timestamp.valueOf(row.get("date").toString()));
					files.add(f);
				}
				
			}
			
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return files;
	}

}
The project is structured as follows:

The Java code is completed, the next is to create a flex project (here I create a project called java_flex)
Create a new flex project - the first step

Create a new flex project - the second step


Therefore, the web root directory need to fill in the java_flex project, this directory must exist /WEB-INF/flex/. Click the "verify configuration" verify that the configuration file is correct, only through the verification, in order to continue. Flex Builder default to generate the Flash file to a java_flex project's java_flex-debug directory, click finish.
The following flex project structure:


In order to realize the remote call in Flex, we need to define a RemoteObject object. You can create the object through the ActionScript code, can be directly define a RemoteObject object in MXML


<s:RemoteObject id="flexServiceRo" destination="test" result="resultHandler(event)" fault="faultHandler(event)"/>

The java_flex.mxml code is as follows:

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx=" ; 
			   xmlns:s="library://ns.adobe.com/flex/spark" 
			   xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600"
			   initialize="init()">
	<fx:Style source="java_flex.css"/>
	
	<fx:Script>
		<![CDATA[
			import mx.collections.ArrayCollection;
			import mx.controls.Alert;
			import mx.rpc.events.FaultEvent;
			import mx.rpc.events.ResultEvent;
			import mx.utils.ArrayUtil;
			
			[Bindable]
			private var arr:ArrayCollection;
			
			private function init():void
			{
				var num:int = 10;
				flexServiceRo.getData(num);
			}
			protected function getData_clickHandler(event:MouseEvent):void
			{
				
			}
			//Get data
			protected function flexService_resultHandler(event:ResultEvent):void
			{
				var obj:Object = new Object;
				
				arr = event.result as ArrayCollection;
				DataTable.dataProvider=arr;
			}
			protected function faultHandler(event:FaultEvent):void
			{
				Alert.show(event.fault.toString());
			}
			
		]]>
	</fx:Script>
	
	
	<fx:Declarations>
		<!-- non visual elements (such as service, value object) here -->
		<s:RemoteObject id="flexServiceRo" destination="test" result="flexService_resultHandler(event)" fault="faultHandler(event)"/>	
	</fx:Declarations>
	<s:Button id="getData" y="70" width="107" height="45" label="Get data"
			  click="getData_clickHandler(event)" horizontalCenter="-89"/>
	<s:DataGrid id="DataTable" width="876" height="417" horizontalCenter="-46" requestedRowCount="4"
				verticalCenter="-73">
		<s:columns>
			<s:ArrayList>
				<s:GridColumn width="100" dataField="id" headerText="id"></s:GridColumn>
				<s:GridColumn width="100" dataField="name" headerText="name"></s:GridColumn>
				<s:GridColumn width="300" dataField="realPath" headerText="realPath"></s:GridColumn>
				<s:GridColumn width="100" dataField="date" headerText="date"></s:GridColumn>
			</s:ArrayList>
		</s:columns>
		<s:typicalItem>
			<fx:Object dataField1="Sample data sample data " dataField2=" " dataField3=" sample data"></fx:Object>
		</s:typicalItem>
		<s:ArrayList>
		</s:ArrayList>
	</s:DataGrid>
</s:Application>
Result after operation.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Eden at November 28, 2013 - 9:07 PM