【发布时间】:2013-01-11 17:22:33
【问题描述】:
我正在尝试发送一些简单的字符串来测试我的 servlet 和小程序之间的数据传输 (servlet -> applet,不是 applet -> servlet),使用 Json 格式和 Gson 库。 小程序中的结果字符串应该与原始消息完全相同,但事实并非如此。 我得到的是 9 个字符的 字符串。
编辑:看起来 servlet 返回的是 HTML 网页而不是 JSON,不是吗?
编辑 2:在 NetBeans 中使用“运行文件”命令启动 servlet 时,该消息在浏览器中正确显示。
请看一下我的代码:
小服务程序:
//begin of the servlet code extract
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter out = response.getWriter();
try
{
String action;
action = request.getParameter("action");
if ("Transfer".equals(action))
{
sendItToApplet(response);
}
}
finally
{
out.close();
}
}
public void sendItToApplet(HttpServletResponse response) throws IOException
{
String messageToApplet = new String("my message from the servlet to the applet");
String json = new Gson().toJson(messageToApplet);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
Writer writer = null;
writer = response.getWriter();
writer.write(json);
writer.close();
}
//end of the servlet code extract
小程序:
//begin of the applet code extract
public void getItFromServlet() throws MalformedURLException, IOException, ClassNotFoundException
{
URL urlServlet = new URL("http://localhost:8080/Srvlt?action=Transfer");
URLConnection connection = urlServlet.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestProperty("Content-Type", "application/json");
InputStream inputStream = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
JsonReader jr = new JsonReader(br);
String retrievedString = new Gson().fromJson(jr, String.class);
inputStream.close();
jtextarea1.setText(retrievedString); //jtextarea is to display the received string from the servlet in the applet
}
//end of the applet code extract
【问题讨论】:
-
那么......当您使用浏览器或 curl 测试您的 servlet 时,它会返回什么?
-
返回简单格式的页面,值为
String messageToApplet,仅此而已。 -
如果您只需要在Servlet和Applet之间传输一个字符串,那么使用JSON不是必需的,而是开销。顺便说一句,你需要清理你的代码。
标签: java json serialization gson