java - 配置tomcat接受post请求

标签 java jsp tomcat servlets

如何配置 tomcat,以便在发出 post 请求时将请求参数输出到 jsp 文件?我需要一个转发到 jsp 的 servlet 还是可以在 jsp 文件中处理?

这是我将 post 请求发送到 tomcat 服务器的方法 -

 public void sendContentUsingPost() throws IOException {

        HttpConnection httpConn = null;
          String url = "http://LOCALHOST:8080/services/getdata";
     //   InputStream is = null;
        OutputStream os = null;

        try {
          // Open an HTTP Connection object
          httpConn = (HttpConnection)Connector.open(url);
          // Setup HTTP Request to POST
          httpConn.setRequestMethod(HttpConnection.POST);

          httpConn.setRequestProperty("User-Agent",
            "Profile/MIDP-1.0 Confirguration/CLDC-1.0");
          httpConn.setRequestProperty("Accept_Language","en-US");
          //Content-Type is must to pass parameters in POST Request
          httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");


          // This function retrieves the information of this connection
          getConnectionInformation(httpConn);

                  String params;
          params = "?id=test&data=testdata";
                      System.out.println("Writing "+params);
          //            httpConn.setRequestProperty( "Content-Length", String.valueOf(params.length()));

          os = httpConn.openOutputStream();

          os.write(params.getBytes());

 } finally {
          if(os != null)
            os.close();
      if(httpConn != null)
            httpConn.close();
    }

        }

谢谢

最佳答案

首先,您的查询字符串无效。

params = "?id=test&data=testdata";

应该是

params = "id=test&data=testdata";

? 只有当您将它作为 GET 查询字符串连接到请求 URL 时才有效。当你想把它写成 POST 请求体时,你不应该使用它。

也就是说,如果该服务不应该返回 HTML(例如纯文本、JSON、XML、CSV 等),则使用 servlet。这是一个发出明文的示例。

String id = request.getParameter("id");
String data = request.getParameter("data");
response.setContentType("text/plain");
response.setContentEncoding("UTF-8");
response.getWriter().write(id + "," + data);

如果此服务应该返回 HTML,则使用 JSP。将 URL 更改为指向 JSP 的 URL。

String url = "http://LOCALHOST:8080/services/getdata.jsp";

然后在JSP模板中添加如下内容打印请求参数。

${param.id}
${param.data}

无论哪种方式,您都应该能够通过读取 URLConnection#getInputStream() 获得结果(响应主体)。

另见:


与具体问题无关,您没有仔细考虑字符编码。我强烈建议这样做。另请参阅上面的链接以获取详细示例。

关于java - 配置tomcat接受post请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5122531/

相关文章:

java - 为什么 Tomcat 服务器没有最新的 HTML 更新?

Hibernate内存数据+数据库

java - 只有在应用程序启动并运行后,如何才能使 RMI 服务可用?

java - 对两个 ArrayList 中的元素进行排序和交换 (Java)

java - Struts 2 jquery sj :select and json result

java - 未找到声音文件,不在目录中?

通过 MySQL 的 Javascript DateTimePicker

javascript - jsp获取表行索引的方法

java - 按钮在 Android 警报 View 中不起作用?

java - 使用 green Dao 时出错