I’m trying to send some simple string to test data transfer between my servlet and an applet
(servlet -> applet, not applet -> servlet), using Json format and Gson library.
The resulting string in the applet should be exactly the same as the original message, but it isn’t.
I’m getting 9-character < !DOCTYPE string instead.
edit: It looks like the servlet returned HTML web page instead of JSON, didn’t it?
edit2: The message is correctly displayed in a browser, when lauching the servlet using “Run File” command in NetBeans.
Could you please take a look at my code:
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
Applet:
//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
The problem is that you’re not sending JSON from your servlet, as you have figured out from your comments. And this is because …
Gsonis very confused as to what you’re trying to do.If you test your JSON serialization (the output from
toJson()) in your servlet, you’ll find that … it’s not doing anything and simply returning the contents of yourStringwith quotes around it. JSON is based around a textual representation of an object (the class’ fields to values), and it certainly doesn’t want to do that with aStringobject; the default serialization there is to get the contents of theStringto be put into the resulting JSON.Edit to add: A typical use for Gson would be something like:
…
The resulting JSON would be: