简体   繁体   English

从servlet获取对象到flex

[英]Getting object from servlet to flex

i have a flex web application which requests a servlet and servlet sends back an arraylist. 我有一个Flex Web应用程序,该应用程序请求一个Servlet,然后Servlet发送回一个arraylist。 I got data in string in result event. 我在结果事件中得到了字符串数据。 I want to get arraycollection in flex end. 我想在flex端获取arraycollection。 how should i do that. 我应该怎么做。 Meanwhile just let me know, can it be done in the way as I did? 同时,请让我知道,可以像我一样做吗? bellow is the code 波纹管是代码

flex end: 弯曲端:

<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" minWidth="955" minHeight="600">

    <fx:Script>
        <![CDATA[
            import mx.controls.Alert;
            import mx.rpc.events.ResultEvent;
            import mx.rpc.http.HTTPService;
            import mx.utils.ObjectUtil;
            protected function callBackEnd(event:MouseEvent):void
            {
                var params:Object = {name: 'debarshi',password:'banerjee'};
                rawFileServlet.send(params);
                rawFileServlet.addEventListener(ResultEvent.RESULT,onResult);
            }

            private function onResult(ev:ResultEvent):void
            {
                Alert.show(ObjectUtil.toString(ev.result));

            }
        ]]>
    </fx:Script>

    <fx:Declarations>
        <s:HTTPService url="http://192.168.1.66:8484/HelloWorldServlet/TestServlet"
                       id="rawFileServlet"
                       method="POST"
                       showBusyCursor="true"/>
    </fx:Declarations>
    <s:Button click="callBackEnd(event)" label="Click"/>

</s:Application>

Object class in flex end: flex结束中的对象类:

package
{
    [Bindable]
    [RemoteClass(alias="com.rit.test.java.model.Employee")]
    public class Employee
    {
        private var id:int;
        private var name:String;
        private var address:String;
        private var salary:int;

        public function setId(_id:int):void
        {
            this.id = _id;
        }

        public function getId():int
        {
            return this.id;
        }

        public function setName(_name:String):void
        {
            this.name = _name;
        }

        public function getName():String
        {
            return this.name;
        }

        public function setAddress(_address:String):void
        {
            this.address = _address;
        }

        public function getAddress():String
        {
            return this.address;
        }

        public function setSalary(_sal:int):void
        {
            this.salary = _sal;
        }

        public function getSalary():int
        {
            return this.salary;
        }

        public function Employee()
        {
        }
    }
}

java servlet class: java servlet类:

package com.rit.test.java;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import flex.messaging.io.ArrayCollection;
import flex.messaging.io.amf.translator.ASTranslator;
import com.rit.test.java.model.Employee;

/**
 * Servlet implementation class TestServlet
 */
public class TestServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private ArrayList<Employee> list = new ArrayList<>();

    /**
     * @see HttpServlet#HttpServlet()
     */
    public TestServlet() {
        super();
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        populateList();
        ASTranslator ast = new ASTranslator();
        out.println(ast.convert(list, ArrayCollection.class));
        out.flush();
    }

    private void populateList(){
        Employee emp = new Employee();
        emp.setId(1);
        emp.setName("Benay");
        emp.setAddress("chinar park");
        emp.setSalary(100);
        list.add(emp);

        emp = new Employee();
        emp.setId(2);
        emp.setName("Debarghya");
        emp.setAddress("baguihati");
        emp.setSalary(70);
        list.add(emp);

        emp = new Employee();
        emp.setId(3);
        emp.setName("Debarshi");
        emp.setAddress("garia");
        emp.setSalary(60);
        list.add(emp);

        emp = new Employee();
        emp.setId(4);
        emp.setName("Tamal");
        emp.setAddress("howrah");
        emp.setSalary(50);
        list.add(emp);

        emp = new Employee();
        emp.setId(5);
        emp.setName("Sanket");
        emp.setAddress("keshtopur");
        emp.setSalary(40);
        list.add(emp);
    }

}
object class in java end:





 package com.rit.test.java.model;

    public class Employee {
        private int id;
        private String name;
        private String address;
        private int salary;

        public void setId(int _id)
        {
            this.id = _id;
        }

        public int getId()
        {
            return this.id;
        }

        public void setName(String _name)
        {
            this.name = _name;
        }

        public String getName()
        {
            return this.name;
        }

        public void setAddress(String _address)
        {
            this.address = _address;
        }

        public String getAddress()
        {
            return this.address;
        }

        public void setSalary(int _sal)
        {
            this.salary = _sal;
        }

        public int getSalary()
        {
            return this.salary;
        }


    }

the alert i got in flex end is: "[com.rit.test.java.model.Employee@1ae209, com.rit.test.java.model.Employee@edd06a, com.rit.test.java.model.Employee@10df737, com.rit.test.java.model.Employee@1e17d0b, com.rit.test.java.model.Employee@d89588] 我在弹性端收到的警报是:“ [[com.rit.test.java.model.Employee @ 1ae209,com.rit.test.java.model.Employee @ edd06a,com.rit.test.java.model.Employee @ 10df737,com.rit.test.java.model.Employee @ 1e17d0b,com.rit.test.java.model.Employee @ d89588]

"

I added five blaze DS .jar file in my java lib folder (flex-messaging-common,flex-messaging-core,flex-messaging-opt,flex-messaging-proxy,flex-messaging-remoting). 我在我的java lib文件夹中添加了五个blaze DS .jar文件(flex-messaging-common,flex-messaging-core,flex-messaging-opt,flex-messaging-proxy,flex-messaging-remoting)。 Using these five .jar file I translated into flex arraycollection in java end and sends. 使用这五个.jar文件,我在Java端将其翻译为flex arraycollection并发送。 Is this the right way that I can approach? 这是我可以采取的正确方法吗? please help 请帮忙

I don't think servlet will serve your purpose here. 我认为servlet在这里不会满足您的目的。 As servlet's println() writes string to the output stream. Servlet的println()将字符串写入输出流。 If you pass an object to println() , the toString() function of that object is called and the result is outputted to println() . 如果将对象传递给println() ,则会调用该对象的toString()函数,并将结果输出到println() As @RIAstar suggested that you should use AMF remoting. 正如@RIAstar建议您应该使用AMF远程处理。 I am presenting here the steps to use AMF remoting using BlazeDS. 我在这里介绍了使用BlazeDS使用AMF远程处理的步骤。

First transfer all logic in your servlet to some POJO class and define a function that returns your list of Employees. 首先,将Servlet中的所有逻辑转移到某个POJO类,然后定义一个返回雇员列表的函数。

My POJO class is named TestMain.java 我的POJO类名为TestMain.java

package com.rit.test.java;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.rit.test.java.model.Employee;

public class TestMain {

    private ArrayList<Employee> list = new ArrayList<Employee>();

    public TestMain()
    {
        populateList();
    }

    public List<Employee> getEmployeeList()
    {
        return list;
    }


    private void populateList(){
        Employee emp = new Employee();
        emp.setId(1);
        emp.setName("Benay");
        emp.setAddress("chinar park");
        emp.setSalary(100);
        list.add(emp);

        emp = new Employee();
        emp.setId(2);
        emp.setName("Debarghya");
        emp.setAddress("baguihati");
        emp.setSalary(70);
        list.add(emp);

        emp = new Employee();
        emp.setId(3);
        emp.setName("Debarshi");
        emp.setAddress("garia");
        emp.setSalary(60);
        list.add(emp);

        emp = new Employee();
        emp.setId(4);
        emp.setName("Tamal");
        emp.setAddress("howrah");
        emp.setSalary(50);
        list.add(emp);

        emp = new Employee();
        emp.setId(5);
        emp.setName("Sanket");
        emp.setAddress("keshtopur");
        emp.setSalary(40);
        list.add(emp);
    }
}

Your Employee.java is as it is. 您的Employee.java保持不变 Nothing is changed. 一切都没有改变。

package com.rit.test.java.model;

public class Employee {
    private int id;
    private String name;
    private String address;
    private int salary;

    public void setId(int _id)
    {
        this.id = _id;
    }

    public int getId()
    {
        return this.id;
    }

    public void setName(String _name)
    {
        this.name = _name;
    }

    public String getName()
    {
        return this.name;
    }

    public void setAddress(String _address)
    {
        this.address = _address;
    }

    public String getAddress()
    {
        return this.address;
    }

    public void setSalary(int _sal)
    {
        this.salary = _sal;
    }

    public int getSalary()
    {
        return this.salary;
    }

}

Change your Flex Employee.as Class as follows. 如下更改您的Flex Employee.as类。 Otherwise ReferenceError: Error #1056: Cannot create property id on Employee Error will occur for all the Employee properties. 否则ReferenceError: Error #1056: Cannot create property id on Employee对于所有Employee属性,都会发生错误。

package
{
    [Bindable]
    [RemoteClass(alias="com.rit.test.java.model.Employee")]
    public class Employee
    {
        public var id:int;
        public var name:String;
        public var address:String;
        public var salary:int;


        public function Employee()
        {
        }
    }
}

Change your Flex-end Application logic to use RemoteObject as below. 更改您的Flex-end Application逻辑以使用RemoteObject ,如下所示。

<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" minWidth="955" minHeight="600">

    <fx:Script>
        <![CDATA[
            import mx.collections.ArrayCollection;
            import mx.controls.Alert;
            import mx.controls.DataGrid;
            import mx.rpc.events.FaultEvent;
            import mx.rpc.events.ResultEvent;
            import mx.rpc.http.HTTPService;
            import mx.utils.ObjectUtil;
            protected function callBackEnd(event:MouseEvent):void
            {
                ro.getEmployeeList();
            }

            private function onResult(ev:ResultEvent):void
            {
                var ac:ArrayCollection = ev.result as ArrayCollection;
                trace(ac);
                for each(var emp:Employee in ac)
                trace(ObjectUtil.toString(emp))
            }

            private function onFault(evt:FaultEvent):void
            {
                Alert.show(""+evt.message);

            }
        ]]>
    </fx:Script>

    <fx:Declarations>
        <!--<s:HTTPService url="http://192.168.1.66:8484/HelloWorldServlet/TestServlet"
                       id="rawFileServlet"
                       method="POST"
                       showBusyCursor="true"/>-->

        <s:RemoteObject id="ro" destination="SOTestEmployee"   
                        result="onResult(event)" fault="onFault(event)" >
            <s:channelSet>
                <s:ChannelSet>
                    <s:channels>
                        <s:AMFChannel url="http://localhost:8400/blazeds/messagebroker/amf" />
                    </s:channels>
                </s:ChannelSet>
            </s:channelSet>
        </s:RemoteObject>
    </fx:Declarations>
    <s:Button click="callBackEnd(event)" label="Click"/>

</s:Application>

Now put All your java *.class files in WEB-INF/classes folder with their package structure. 现在,将所有Java * .class文件及其包结构放入WEB-INF/classes文件夹中。

Now add the following XML node to remoting-config.xml in WEB-INF/flex folder under <service></service> tag. 现在,将以下XML节点添加到<service></service>标记下的WEB-INF / flex文件夹中的remoting-config.xml中。

<destination id="SOTestEmployee">
        <properties>
            <source>com.rit.test.java.TestMain</source>
        </properties>
        <adapter ref="java-object"/>
    </destination>

I think thats all for now. 我认为目前为止。 Search the web for some good tutorial on flash remoting. 在网上搜索有关Flash远程处理的一些很好的教程。 Probably I am not a good teacher...haha. 可能我不是一个好老师...哈哈。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM