【问题标题】:Send data in the doPost() response?在 doPost() 响应中发送数据?
【发布时间】:2015-08-04 12:30:25
【问题描述】:

我是网络编程的初学者。我使用 Eclipse Java EE 和在 localhost 中运行的 Tomcat 服务器创建了一个应用程序。

应用程序的目标是从客户端获取信息并发送回其他信息。

我开发了一个 servlet 并实现了一个完美运行的 doPost() 方法。我获得了保存在名为 USSDPull 的 bean 中的信息,并将其写入名为 log.txt 的文本文件中。

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


USSDPull ussdpull = new USSDPull();
                ussdpull.setUssdstring(request.getParameter("ussdstring"));
                ussdpull.setSessionid(Integer.parseInt(request.getParameter("sessionid")));
                ussdpull.setMsisdn(request.getParameter("msisdn"));
                ussdpull.setUssdcode(request.getParameter("ussdcode"));
                ussdpull.setEncoding(Integer.parseInt(request.getParameter("encoding")));

                response.setContentType("text/text");
                response.setCharacterEncoding( "UTF-8" );
                PrintWriter out = response.getWriter();
                out.flush();

                out.println("POST received : " + ussdpull.getUssdstring()+" "+ussdpull.getSessionid()+" "+ussdpull.getMsisdn()+" "+ussdpull.getUssdcode()+" "+ussdpull.getEncoding());

                //WRITE IN FILE
                FileWriter fw = new FileWriter("D:/Users/Username/Documents/log.txt", true);
                BufferedWriter output = new BufferedWriter(fw);
                output.write(dateFormat.format(date)+";"+ussdpull.getUssdstring()+";"+ussdpull.getSessionid()+";"+ussdpull.getMsisdn()+";"+ussdpull.getUssdcode()+";"+ussdpull.getEncoding()+"\n");  
                output.flush();
                output.close();
}

我需要 servlet 将 2 个特定的布尔值和 1 个字符串发送回客户端。我不知道该怎么做。是否可以使用 HttpServletResponse 发送数据?还是我需要找到一种方法来“调用”doGet() 方法?

【问题讨论】:

  • 您已经在示例代码中发回了数据(“POST received”等)。你到底有什么问题?
  • 我写这个只是为了检查数据。 Println() 是否足以真正发送数据?我以为只是在命令行中显示信息,因为我使用 curl 来模拟交互。基本上,数据来自设备。接下来,数据进入服务并重新发送到我的应用程序。如果我收到所需的信息,我需要从服务器发回数据以告知服务。
  • 好吧,您通过获取响应编写器并打印到它来发回字符数据。 Curl 只是显示它得到的响应,如果你在浏览器中运行它,你会看到它是文本。现在由您决定如何发送数据。作为文本表示(甚至可能是 JSON)或作为二进制数据(尽管与您发送的数据量无关)。
  • 非常感谢卡亚曼!我将更深入地搜索 JSON 和二进制数据以完成我的应用程序。

标签: java servlets http-post tomcat7 eclipse-jee


【解决方案1】:

HttpServletResponse 本身除了某些标头(例如响应代码)之外,没有为您提供将数据写回客户端的方法。

但是,它有一个名为 getOutputStream 的方法和一个名为 getWriter() 的方法,可以为您提供相应的服务。 OutputStreamPrintWriter。您可以使用它们将数据写入响应。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多