Introduction
Flex provides 3 classes to communicate with servers namely HttpService,WebService and RemoteObject HTTPService component of Flex 4 can be used with any kind of server-side technology, including PHP pages, ColdFusion Pages, JavaServer Pages (JSPs), Java servlets. This article aims at discussing the httpservice component with JSP for the following task.
- To send a request to retrive data from Database
- To send a request with parameters to insert data into the database.
also read:
To send a request to retrive data from Database
First let us look at the HttpService tag
<S:HTTPService id="No default." method="GET|POST|HEAD|OPTIONS|PUT|TRACE|DELETE" resultFormat="object|array|xml|e4x|flashvars|text" url="No default." fault="No default." result="No default." >
Explanation
- id-refers to the name of the HttpService instance.
- Method-Mentions the way how the request is send to the server.
- resultFormat-configured to specify the format the way the result is expected
- URL-The URL to which the request is send
- Fault-A event handling mechanism which makes a call to the handlercode if there is a exception.
- result-A event handling mechanism which makes a call to the handlercode when the result is recieved from the server.
Example:
The Example shows a Flex application which invokes a JSP page that retrives data from database. The data is formated by JSP code as XML and sent to the flex application and displayed on a data provider.
Files in the project
- FlexJSPdemo.mxml:The Flex application that invokes a JSP page
- Itemlist.jsp :The JSP page that retrieves data from database using JPA and formats the result in XML format
- Product.java :The Entity class that is mapped to Product Table in the database using JPA.
- ProductRetriever.java:The Java class that is contacted by JSP to interact with database using JPA.
FlexJSPDemo.mxml
<?xml version="1.0" encoding="utf-8"?> <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx" color="#196F82" fontWeight="bold"> <fx:Style source="CopyofFlex4_demos2.css"/> <fx:Declarations> <s:HTTPService id="myserv" url="http://localhost:8080/JSPDEMONET/ItemList.jsp"/> </fx:Declarations> <s:Panel x="26" y="97" width="705" height="350" title="Using the HttpService"> <mx:DataGrid dataProvider="{myserv.lastResult.Data.Item}" width="508" height="158" enabled="true" color="#3B8FA1" x="81" y="40"/> <s:Button label="Fetch Data" click="myserv.send()" x="248" y="235"/> </s:Panel>
ItemList.jsp
<%@page import="a.ProductRetriever, a.Product, java.util.*"%> <?xml version="1.0" encoding="utf-8"?> <Data> <% ProductRetriever srv = new ProductRetriever(); List list = null; list = srv.getData(); for (int i=0; i<list.size(); i++) { Product product = (Product)list.get(i); %> <Item itemid='<%= product.getProductId()%>'> <name><%= product.getProductCode() %></name> <description><%= product.getDescription() %></description> </Item> <%}% > </Data>
Product.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package a; import java.io.Serializable; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; /** * * @author RekhaKG_Nair */ @Entity @Table(name = "PRODUCT") @NamedQueries({@NamedQuery(name = "Product.findAll", query = "SELECT p FROM Product p"), @NamedQuery(name = "Product.findByProductId", query = "SELECT p FROM Product p WHERE p.productId = :productId"), @NamedQuery(name = "Product.findByProductCode", query = "SELECT p FROM Product p WHERE p.productCode = :productCode"), @NamedQuery(name = "Product.findByDescription", query = "SELECT p FROM Product p WHERE p.description = :description")}) public class Product implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @Column(name = "PRODUCT_ID") private Integer productId; @Column(name = "PRODUCT_CODE") private String productCode; @Column(name = "DESCRIPTION") private String description; public Product() { } public Product(Integer productId) { this.productId = productId; } public Integer getProductId() { return productId; } public void setProductId(Integer productId) { this.productId = productId; } public String getProductCode() { return productCode; } public void setProductCode(String productCode) { this.productCode = productCode; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @Override public int hashCode() { int hash = 0; hash += (productId != null ? productId.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Product)) { return false; } Product other = (Product) object; if ((this.productId == null && other.productId != null) || (this.productId != null && !this.productId.equals(other.productId))) { return false; } return true; } @Override public String toString() { return "a.Product[productId=" + productId + "]"; } }
ProductRetriever.java
package a; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.persistence.Query; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author RekhaKG_Nair */ public class ProductRetriever { EntityManagerFactory emf; EntityManager em; public ProductRetriever() { emf = Persistence.createEntityManagerFactory("JSPDEMOPU"); em=emf.createEntityManager(); } public List getData() { Query q=em.createNamedQuery("Product.findAll"); return q.getResultList(); } }
Persistence.xml
<?xml version="1.0" encoding="UTF-8"?> <persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"> <persistence-unit name="JSPDEMOPU" transaction-type="RESOURCE_LOCAL"> <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider> <class>a.Product</class> <exclude-unlisted-classes>true</exclude-unlisted-classes> <properties> <property name="eclipselink.jdbc.password" value="rekha"/> <property name="eclipselink.jdbc.user" value="rekha"/> <property name="eclipselink.jdbc.driver" value="org.apache.derby.jdbc.ClientDriver"/> <property name="eclipselink.jdbc.url" value="jdbc:derby://localhost:1527/JPA"/> </properties> </persistence-unit> </persistence>
Output:
How to insert data to a database using Flex and JSP?
In the last section we have seen how to make a request to the server and retrieve the information. This sesction
we will look at sending some parameters as well with our request.We will modify our previous application by
- creating a new mxml file(SendtoJSPDemo.mxml) to capture input from the user and send it to the server.
- Modify the ProductRetriver.Java class to perform the insertion operation.
- Creating a Upload.jsp which gets the request from our Flex code.
SendtoJSPDemo.mxml.
<?xml version="1.0" encoding="utf-8"?> <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx" color="#196F82" fontWeight="bold"> <fx:Style source="CopyofFlex4_demos2.css"/> <fx:Declarations> <s:HTTPService id="myservsd" url="http://hydhtc130252d:8080/JSPDEMONET/upload.jsp" resultFormat="text" fault="faulthand(event)" result="callme(event)" > <s:request xmlns=""> <PID> {PID.text} </PID> <Name> {Name.text} </Name> <Disc> {Disc.text} </Disc> </s:request> </s:HTTPService> </fx:Declarations> <fx:Script> <![CDATA[ import mx.collections.ArrayCollection; import mx.controls.Alert; import mx.rpc.events.FaultEvent; import mx.rpc.events.ResultEvent; function callme(event:ResultEvent) { var k:String=event.result.toString(); msg.text=k.substr(42,k.length); } function faulthand(faulte:FaultEvent) { mx.controls.Alert.show(faulte.fault.faultString); } ]]> </fx:Script> <s:Panel x="20" y="110" width="726" height="350" chromeColor="#D5CECE"> <s:TextInput x="141" y="88" id="PID" width="150"/> <s:TextInput x="141" y="158" id="Name"/> <s:TextInput x="141" y="219" id="Disc" width="154"/> <s:Button x="120" y="268" label="ok" click="myservsd.send()"/> <s:Label x="14" y="98" text="Productid :" width="95" color="#101212"/> <s:Label x="9" y="158" text="Product Code:" width="124" color="#0B0C0C"/> <s:Label x="10" y="219" text="Description :" color="#101212"/> <s:Label x="62" y="25" text="Item Detail Form" width="159" color="#090B0B"/> <s:Label x="466" y="66" text="Message:" width="149" color="#0C0D0D"/> <s:RichText x="470" id="msg" y="99" text="Wait....." width="208" height="157" color="#9B2929"/> </s:Panel> <s:Label x="184" y="68" text="HttpService" width="329" fontSize="35" color="#111111"/> </s:Application>
Explanation:
- Look at the HTTPService instance that was created ,there is the request tag which configures the data that can be posted.
<s:request xmlns=""> <PID> {PID.text} </PID> <Name> {Name.text} </Name> <Disc> {Disc.text} </Disc> </s:request>
Here the code shows that we are sending the parameters PID,Name,Disc so formating as XML.
- The Event handler code when a result or fault event is generated by HttpService
The highlighted code below shows the string returned by our JSP code.
function callme(event:ResultEvent) { var k:String=event.result.toString(); msg.text=k.substr(42,k.length); } function faulthand(faulte:FaultEvent) { mx.controls.Alert.show(faulte.fault.faultString); }
ProductRetriver.Java
Let us Modify the ProductRetriver.Java to add the Java code to insert data to the database using JPA and sends a boolean value true if insertion was successful otherwise sends false.
public boolean insertProduct(Product p) { boolean b =true; try { em.getTransaction().begin(); em.persist(p); em.getTransaction().commit(); } catch(Exception e) { em.getTransaction().rollback(); b=false; } if(b) return true; else return false; }
Upload.jsp.
<%@page import="a.ProductRetriever, a.Product, java.util.*"%> <?xml version="1.0" encoding="utf-8"?> <% Product product = new Product(); System.out.println("1"+request.getParameter("PID")); System.out.println("2"+request.getParameter("Name")); product.setProductId(Integer.parseInt(request.getParameter("PID"))); product.setProductCode(request.getParameter("Name")); product.setDescription(request.getParameter("Disc")); boolean b=new ProductRetriever().insertProduct(product); if(b) { out.print("done saved the data about:["+product.getProductId()+","+product.getProductCode()+","+product.getDescription()+"]"); } %>
Output:
Conclusion
Flex can not only connect to java but even other server-based applications like ColdFusion, PHP, ASP.NET.
You can retrieve plain text or XML data using HTTP.