【问题标题】:Google App Engine how to get an object from the servlet?Google App Engine 如何从 servlet 中获取对象?
【发布时间】:2011-02-12 21:14:37
【问题描述】:

我在 Google App Engine 的数据存储中有以下类对象,我可以从“数据存储查看器”中看到它们:

import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

@PersistenceCapable(identityType=IdentityType.APPLICATION)
public class Contact_Info_Entry implements Serializable
{
  @PrimaryKey
  @Persistent(valueStrategy=IdGeneratorStrategy.IDENTITY)
  Long Id;
  public static final long serialVersionUID=26362862L;
  String Contact_Id="",First_Name="",Last_Name="",Company_Name="",Branch_Name="",Address_1="",Address_2="",City="",State="",Zip="",Country="";
  double D_1,D_2;
  boolean B_1,B_2;
  Vector<String> A_Vector=new Vector<String>();

  public Contact_Info_Entry() { }
......
}

我的 java 应用程序如何从 servlet url 获取对象?例如,如果有一个 Contact_Info_Entry 实例,其 Contact_Id 为“ABC-123”,而我的 App Id 为:nm-java

当我的java程序访问url时:

 "http://nm-java.appspot.com/Check_Contact_Info?Contact_Id=ABC-123

Check_Contact_Info servlet 如何从数据存储中获取对象并将其返回到我的应用程序?

public class Check_Contact_Info_Servlet extends HttpServlet
{
  static boolean Debug=true;

  public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException
  {

  }
...
  protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { doGet(request,response); }
}

对不起,我需要更具体,如何在响应中发送对象?

  public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException
  {
    PrintWriter out=response.getWriter();

    Contact_Info_Entry My_Contact_Entry;
    ... get My_Contact_Entry from datastore ...

    ??? How to send it out in the "response" ???


  }

弗兰克

【问题讨论】:

    标签: google-app-engine servlets object


    【解决方案1】:

    由于Contact_Id不是主键,所以需要创建query

    Query query = pm.newQuery(Contact_Info_Entry.class);
    query.setFilter("Contact_Id == idParam");
    query.declareParameters("String idParam");
    
    try {
    
        List<Contact_Info_Entry> results = (List<Contact_Info_Entry>) 
            query.execute("ABC-123");
    
        // note that this returns a list, there could be multiple,
        // DataStore does not ensure uniqueness for non-primary key fields
    
    } finally {
        query.closeAll();
    }
    

    如果您可以使用 Long Id 值(即主键),您可以直接通过实体键加载它。

    如果你想将实体从 Servlet 发送到 Java 客户端,你可以使用 Java 的序列化(你的类是可序列化的)。

    【讨论】:

    • 谢谢,我也需要这部分!
    • @BalusC : 是的,我之前在其他程序中使用过 OutputStream 或 Writer,但我用它们来发送 beck html 字符串,而不是对象的实例,在这种情况下,“PrintWriter out=response.getWriter();"发回“Contact_Info_Entry My_Contact_Entry”?这就是我卡住的地方。
    • @Frank:看看 ObjectOutputStream
    猜你喜欢
    • 1970-01-01
    • 2011-05-16
    • 2014-12-11
    • 1970-01-01
    • 2011-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-05
    相关资源
    最近更新 更多