我有一个简单的小程序,我想在与我的服务器和 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是这里的麻烦。我忘了什么吗?