flex与java通信的三种方式:
1.通过httpService:你访问一个xml或者servlet,然后flex接收返回的xml数据 2.通过webService:你访问一个webService服务,然后获得文本信息 3.通过RemoteObject:可以通过blazeds来访问远程service接口方法,Flex接收一个对象。
建立项目:(来自百度文库的《flex(eclipse)开发配置手册.pdf》)
flexHttpService访问定义在javaFlex里面的httpservice方法:
1、在javaFlex中定义一个servlet,该servlet返回一个xml
package my.servlet;
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;
@SuppressWarnings("serial")
public class HttpServiceServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/xml");
resp.setCharacterEncoding("utf-8");
PrintWriter out = resp.getWriter();
out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
out.println("<rows>");
out.println("<row>");
out.println("<id>");
out.println("1");
out.println("</id>");
out.println("<msg>");
out.println("hello");
out.println("</msg>");
out.println("</row>");
out.println("<row>");
out.println("<id>");
out.println("2");
out.println("</id>");
out.println("<msg>");
out.println("haha");
out.println("</msg>");
out.println("</row>");
out.println("</rows>");
out.close();
}
}
在web.xml中配置servlet:
<servlet>
<servlet-name>MyHttpServiceServlet</servlet-name>
<servlet-class>my.servlet.HttpServiceServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyHttpServiceServlet</servlet-name>
<url-pattern>/MyHttpServiceServlet</url-pattern>
</servlet-mapping>
2、在flexHttpService中定义并访问 MyHttpServiceServlet:
定义:
<fx:Declarations>
<!-- 将非可视元素(例如服务、值对象)放在此处 -->
<s:HTTPService id="getData" method="POST"
url="http://localhost:8080/javaFlex/MyHttpServiceServlet" useProxy="false"/>
</fx:Declarations>
也可以不指定url而在proxy-config中配置:
在proxy-config.xml配置HTTPService要请求的URL地址,在程序中用“destination”映射关系来访问该URL
访问:
<s:Button label="Get data" click="getData.send()"/>
得到结果:
<mx:DataGrid width="332" height="160" dataProvider="{getData.lastResult.rows.row}">
3、结果:
---------------------------------------------------------华丽丽的分割线-------------------------------------------------------------------------------
上面没有解决跨域访问的问题:
沙箱效应的方法:
1、利用useProxy属性和crossdomain.xml可以跨域访问,这是解决之一。
2、写一个JS或PHP脚本,用Ajax(XMLHTTP Object) 去访问跨域URL。
<mx:HTTPService id="srv" destination="catalog" useProxy="true"/>
WEB-INF\flex\proxy-config.xml :
<destination id="catalog">
<properties>
<url>/{context.root}/testdrive-httpservice/catalog.jsp</url>
</properties>
</destination>
其他: flash跨域策略文件crossdomain.xml配置详解