如何获取servlet中java类中生成的动态字符串值?

时间:2013-05-27 12:07:10

标签: java servlets dynamic-values


我正在开发一个简单的Web应用程序。这个应用程序有一个功能'ping',我们通常在命令提示符下执行。

因此在我的jsp页面中我会给出一个像'www.google.com'这样的地址,然后点击提交发送地址到我的servlet'PingServlet'。我的servlet收到地址并发送到一个java类,它将处理该地址的ping。

    ip="www.google.com"; //Got from servlet
    String pingCmd = "ping " + ip;
    //ArrayList<String> pingRsult = new ArrayList<String>();
    //pingRsult.add("Pinging Data");
    try {
        Runtime r = Runtime.getRuntime();
        Process p = r.exec(pingCmd);

        BufferedReader in = new BufferedReader(new InputStreamReader(p
                .getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            System.out.println(inputLine);//i want to send this string to servlet
        }
        in.close();

    }// try
    catch (IOException e) {
        System.out.println(e);
    }


在处理地址时,在while循环中它会产生一些字符串值,我想在生成时将每个字符串值发送到servlet。我搜索了很多谷歌。但我没有发现任何想法....

请帮帮我......!

2 个答案:

答案 0 :(得分:0)

你可以放一个ArrayList pingResults;作为会话变量......

然后你只需要从jsp页面阅读。

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

            ArrayList<String> pingResult=new ArrayList<>();
            HttpSession s = request.getSession();

            //Add your values
            s.setAttribute("Values", values);
            //Redirect to jsp where you show the strings
            response.sendRedirect("exemple.jsp");
}

然后在你的jsp中你只需要调用会话变量Values

如果您想要实时打印,可以使用以下代码:

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

    PrintWriter out = response.getWriter();

    out.println("<HTML>");
    out.println("<HEAD><TITLE>Ping Result</TITLE></HEAD>");
    out.println("<BODY>");


    ip="www.google.com"; //Got from servlet
    String pingCmd = "ping " + ip;
    ArrayList<String> pingRsult = new ArrayList<String>();
    pingRsult.add("Pinging Data");
    try {
        Runtime r = Runtime.getRuntime();
        Process p = r.exec(pingCmd);

        BufferedReader in = new BufferedReader(new InputStreamReader(p
                .getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            System.out.println(inputLine);
            out.println("<p>"+inputLine+"</p>");
        }
        in.close();                        
            out.println("</BODY></HTML>");
    }// try
    catch (IOException e) {
        System.out.println(e);
    }
}

这样servlet读取的每一行,都将它打印在servlet页面上。

答案 1 :(得分:0)

使用Request范围或会话范围来存储值并在servlet中使用它。