gpt4 book ai didi

java - 我的小程序无法连接到 Servlet 和传输数据

转载 作者:行者123 更新时间:2023-11-30 23:21:18 25 4
gpt4 key购买 nike

我想将一些数据从我的 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")
+ "&param2=" + URLEncoder.encode(param2, "UTF-8")
+ "&param3=" + 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()doGet()doPost() 调用。当我直接从它的 http 链接调用它并毫无问题地填充数据库时,Servlet 工作正常,但是当我从 applet 调用它时,没有任何反应,甚至没有任何异常!老实说,他们无法相互交流,我真的很困惑。

最佳答案

最后我用这段代码发送了多个参数:(这只是一个建议,也许还有更好的解决方案,但它对我有用)

Applet side:

    URL helloServletURL = new URL(getCodeBase().toString() + "mydb");
URLConnection urlConnection = helloServletURL.openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setUseCaches(false);

String param1 = "data1";
String param2 = "data1";
String param3 = "data1";

ObjectOutputStream objOut = new ObjectOutputStream(urlConnection.getOutputStream());
objOut.writeUTF(param1 + "%" + param2 + "%" + param3);

objOut.flush();

Servlet side:

    ObjectInputStream dataInput = new ObjectInputStream(request.getInputStream());
String param = dataInput.readUTF();

dataInput.close();

String[] values = param.split("%");

关于java - 我的小程序无法连接到 Servlet 和传输数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15345628/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com