Servlet无法提供简单的applet

时间:2013-01-07 22:21:52

标签: java servlets jetty japplet

我有一个简单的小程序,我希望在与我的服务器和servlet连接的本地网页上显示。

小程序代码:

public class MyApplet extends JApplet implements ActionListener {
    JPanel panel = new JPanel();
    JButton btnPush;

    public MyApplet() {}

    public void init() {
        createGUI();
    }

    public void createGUI() {
        getContentPane().add(panel, BorderLayout.CENTER);
        panel.setLayout(null);
        btnPush = new JButton("Push");
        btnPush.addActionListener(this);
        btnPush.setBounds(54, 94, 89, 23);
        panel.add(btnPush);
        setSize(200, 200);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getSource() == btnPush) {
            JOptionPane.showMessageDialog(this, "Button was pushed");
        }

    }
}

这是servlet /服务器代码:

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;

public class MyServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html; chaset=utf-8");
        Writer writer = response.getWriter();

        writer.write("<applet codebase=\"bin\" code=\"MyApplet.class\" width=\"200\" height=\"200\">" + 
                "If your browser was Java-enabled, a button would appear here. </applet>");
    }

    public static void main(String... args) throws Exception {
        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.addServlet(MyServlet.class, "/");

        MyApplet applet = new MyApplet();
        applet.init();
        applet.start();

        Server server = new Server(8080);
        server.setHandler(context);
        server.start();
        server.join();

    }
}

我正在使用servlet-api3.0和jetty 8。 我可以连接到http://“localhost:8080”,但是当我的applet尝试加载它时会停止加载。 当我运行带有applet标签的html文件时,它可以正常运行。所以似乎servlet就是麻烦。我忘记了什么吗?

1 个答案:

答案 0 :(得分:1)

服务器的配置只能响应Servlet本身。 没有DefaultServlet设置来实际返回正在请求的MyApplet.class文件。

ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
server.setHandler(context);

// Serve content from bin directory (where the classes are compiled into)
ServletHolder holder = context.addServlet(DefaultServlet.class,"/*");
holder.setInitParameter("resourceBase","bin");
holder.setInitParameter("pathInfoOnly","true");

// Serve some hello world servlets
context.addServlet(MyServlet.class,"/*");

有关1 Servlet + 1 DefaultServlet的更完整示例,请参阅嵌入式示例。 http://git.eclipse.org/c/jetty/org.eclipse.jetty.project.git/tree/example-jetty-embedded/src/main/java/org/eclipse/jetty/embedded/OneServletContext.java?h=jetty-8

请确保您的resourceBase init参数指向您的类文件所在的路径。