我想将一些数据从我的 Applet 发送到一个特定的 Servlet,该 Servlet 应该连接到 MySQL 数据库并存储传输的数据。在 Applet 端,我使用这种方法将数据从 applet 传输到 servlet:
public void sendData() {
try {
URL postURL = new URL("http://localhost:8080/MyApplet/mydb");
HttpURLConnection conn = (HttpURLConnection) postURL.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.connect();
String param1 = "data1";
String param2 = "data2";
String param3 = "data3";
PrintWriter out = new PrintWriter(conn.getOutputStream());
out.write("param1=" + URLEncoder.encode(param1, "UTF-8")
+ "¶m2=" + URLEncoder.encode(param2, "UTF-8")
+ "¶m3=" + URLEncoder.encode(param3, "UTF-8"));
out.flush();
} catch (Exception e) {
System.err.println(e.getMessage());
JOptionPane.showMessageDialog(GameApplet.this, e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
}
}
MyApplet/mydb 是我的Selrvet 的路径。在 Servlet 方面,我编写了以下代码:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String parameter1 = request.getParameter("param1");
String parameter2 = request.getParameter("param2");
String parameter3 = request.getParameter("param3");
connectToDB();
insert(parameter1, parameter2, parameter3);
// insert("X", "Y", "Z");
closeDB();
}
从和processRequest()
调用_ 当我直接从其 http 链接调用 Servlet 并毫无问题地填充数据库时,Servlet 可以正常工作,但是当我从 applet 调用它时,什么也没有发生,甚至没有任何异常!老实说,他们无法相互交流,我真的很困惑。doGet()
doPost()