日期:2014-05-18  浏览次数:20720 次

求助:Applet和Servlet 通信问题

Applet的程序:
package   servlet;
import   java.applet.Applet;
import   java.awt.Graphics;
import   java.awt.TextField;
import   java.io.BufferedReader;
import   java.io.InputStreamReader;
import   java.net.URL;

public   class   TestApplet   extends   Applet   {
    private   String   line;
    TextField   messageText;
    public   void   init()   {
        try   {
            URL   url   =   new   URL( "http://localhost:7001/Applet/TestServlet?name=vickie ");
            BufferedReader   in   =   new   BufferedReader(new   InputStreamReader(url
                    .openStream()));
            line   =   in.readLine();
            in.close();
            line   =   url.toString();
            line   =   line   +   "\n "   +   url.openStream();
        }   catch   (Exception   e)   {
            e.printStackTrace();
        }
    }

    public   void   paint(Graphics   g)   {
        g.drawString(line,   20,   40);
    }
}
Servlet的程序:
package   servlet;
import   java.io.IOException;
import   java.io.PrintWriter;
import   javax.servlet.http.*;
import   javax.servlet.*;

public   class   TestServlet   extends   HttpServlet   {
    public   void   doGet(HttpServletRequest   req,   HttpServletResponse   res)
            throws   ServletException,   IOException   {
        res.setContentType( "text/plain ");
        PrintWriter   out   =   res.getWriter();
        out.println( "Hello     "   +   req.getParameter( "name ")+   ",servlet   talking! ");
        out.close();
    }
    public   void   doPost(HttpServletRequest   req,   HttpServletResponse   res)
            throws   ServletException,   IOException   {
        this.doGet(req,res);
    }
}
预期的结果应该是:
applet上显示“Hello   vickie,       servlet       talking!”
但运行的结果是:applet小程序已经打开,但是却是个空。也没有出错信息。

------解决方案--------------------
先检查是不是URL地址有问题,如果没有加上一句 :URL url = new URL( "your url ");
URLConnection urlconnection = url.openConnection();
BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(urlconnection.getInputStream()