繁体   English   中英

快速Java Servlet和HTTP Q(使用Titanium Appcelerator)

[英]Quick Java Servlet and HTTP Q (with Titanium Appcelerator)

我创建了一个基本的Java Servlet页面,该页面仅显示您好世界

我试图学习和理解的是基本上如何从Web服务器上提取信息并将其显示在移动设备上(然后希望将信息发布回Web页面)。

我在这里有一些示例代码,当应用程序运行时没有连接错误,一切都按计划进行,警报消息显示Hello World,我猜这是'this.response.text)

我已经阅读了Appcelerator Titanium提供的文档,但发现使用JSON文件和解析等内容很难理解。

问:因此,如果有人可以帮助我理解如何从servlet页面中拉出“ Hello World”并在标签/文本字段中进行显示,则非常感谢,希望您的回答将帮助我理解如何从移动客户端获取数据并发送到网页上的信息

var xhr = Ti.Network.createHTTPClient({
onload : function(e){
    Ti.API.info('Received text: ' + this.responseText);
    alert(this.responseText);


},
onerror: function(e) {
    Ti.API.info('error, HTTP status = ' + this.status);
    alert('error');
},
timeout:5000
});

xhr.open("GET", "http://130.206.127.43:8080/HelloWorld");
xhr.send();

我认为您想要的是将Java Servlet的结果作为JSON字符串返回,以便可以在Titanium中正确读取它。

首先创建一个Map或带您想返回给客户的信息。

{message=Hello world, action=display, extra=extra}

然后将其转换为JSON字符串( 示例

现在,在Titanium应用程序中,您可以将结果解析为JSON并使用您返回的信息:

onload : function(e){
    var result = JSON.parse(this.responseText);
    alert(result.message);
    alert(result.action);
    alert(result.extra);
},

编辑:替换了eval

我认为它不会响应,因为您尝试提取Servlet页面中不存在的json形式

您需要使用的是一个Web服务页面,其中包含JSON格式的数据,例如:

[{"message" : "Hello World"}]

因此,如果您对j2ee有很好的了解,请尝试编写包含json形式的Web服务页面

然后在onload函数里面放这个:

var json = eval('('+this.responseText+')');

并使用alert(json.message);显示数据alert(json.message);

感谢您的回答,这是基本的servlet类

// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class
public class HelloWorld extends HttpServlet {

private String message;

public void init() throws ServletException
{

  message = "Hello World";
}

public void doGet(HttpServletRequest request,
                HttpServletResponse response)
        throws ServletException, IOException
{
  // Set response content type
  response.setContentType("text/html");

  // Actual logic goes here.
  PrintWriter out = response.getWriter();
  out.println("<h1>" + message + "</h1>");
}

不幸的是,我对j2ee并不了解,但是我现在会查找它,但是我需要更改吗

public void init() throws ServletException
{

  message = "Hello World";
}
...to
public void init() throws ServletException
{

  [{"message" : "Hello World"}]
}

以及

response.setContentType("text/html");
...to
response.setContentType("application/json");

暂无
暂无

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

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