如何从jsp接收数据作为GET Call

时间:2016-10-20 08:49:18

标签: java jsp http-get

我有2个jsp页面。 我将数据从1个jsp发送到另一个作为GET请求。 现在我想在第二个jsp中显示输出数据,但我无法做到。

这是我的第一个jsp,即index.jsp

    <%-- 
    Document   : Spago
    Created on : 14 Oct, 2016, 2:06:12 PM
    Author     : ndoshi
--%>

<%@page import="java.io.InputStreamReader"%>
<%@page import="java.io.BufferedReader"%>
<%@page import="java.net.*"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
        <script>
            setTimeout(function () {
                document.location = "http://localhost:8080/demo/index.jsp";
            }, 60000); // <-- this is the delay in milliseconds
        </script>
    </head>
    <body>
        <%
            try {
                String machine = InetAddress.getLocalHost().getCanonicalHostName();
                String user="Niket";
                URL url = new URL("http://localhost:8080/demo/db.jsp?machine=" + machine+"&user="+user);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setRequestProperty("Accept", "application/json");

                BufferedReader in = new BufferedReader(
                new InputStreamReader(conn.getInputStream()));
                String inputLine;
                StringBuffer response1 = new StringBuffer();

                while ((inputLine = in.readLine()) != null) {
                    response1.append(inputLine);
                }

                System.out.println(inputLine);

                out.println("Index : "+inputLine);
                in.close();

                if (conn.getResponseCode() != 200) {

                }
            } catch (Exception e) {
            }
        %>
    </body>
</html>

这是我的第二个jsp,即db.jsp

<%-- 
    Document   : db.jsp
    Created on : 20 Oct, 2016, 1:29:47 PM
    Author     : ndoshi
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <%
            out.println("Response : "+request.getParameter("machine")+","+request.getParameter("user"));
        %>
    </body>
</html>

1 个答案:

答案 0 :(得分:1)

您需要使用新代码修改以下代码。

旧代码:

String inputLine;
                StringBuffer response1 = new StringBuffer();

                while ((inputLine = in.readLine()) != null) {
                    response1.append(inputLine);
                }

                System.out.println(inputLine);

新代码

String inputLine;
String Line="";
while ((inputLine = in.readLine()) != null) {
    Line+=inputLine;
}
out.println(Line);

StringBuffer在这种情况下不起作用。