1

我有一个简单的小程序,我想在与我的服务器和 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",但是当我的小程序尝试加载时它会停止加载。当我运行带有小程序标记的 html 文件时,它可以正常工作。所以看起来servlet是这里的麻烦。我忘了什么吗?

4

1 回答 1

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 初始化参数指向你的类文件所在的路径。

于 2013-01-07T22:31:25.577 回答