Suhail Gupta
Suhail Gupta

Reputation: 23256

How can I use Gson here to send back the list to the jsp page?

In one case a servlet A sends an IP to a remote server with the hope that the server will send back the list of files shared by that IP :

Servlet A

connection.openConnection(); // Sends the IP as the query parameters
if(connection.getResponseCode() == 200) {  
    requestDispatcher.forward(request,response); // Forward to ShowFiles.jsp
} else { // Error ! }

Note: 'ShowFiles.jsp' is a jsp page that will show the list it will receive from the server.

Okay ! Now the servlet on the server,let us name it B, receives the query parameter and checks if the database has any file corresponding to the IP received. If there is/are files shared it sends back the list of names,otherwise a message suggesting that no file has been shared.

Servlet B (On server that receives IP as query parameter)

String ip = getAttribute("IP");
if( hasSharedFile(ip) ) {
  list = fetchList(ip); // Basically an ArrayList<String>
  // SEND THIS LIST BACK TO THE CLIENT
} else {
   // Return a message saying,No file has been shared till with the server
  }

To send this list by the servlet B (on the remote server) to ShowFiles.jsp (to which the servlet A dispatched the request) I was suggested to use JSON,rather Gson. How can I use Gson to send this list to ShowFiles.jsp ?

I have never used Gson,so I know nothing.

Upvotes: 0

Views: 1506

Answers (1)

farmer1992
farmer1992

Reputation: 8156

Servlet B (On server that receives IP as query parameter)

String ip = getAttribute("IP");
if( hasSharedFile(ip) ) {
  list = fetchList(ip); // Basically an ArrayList<String>
  // SEND THIS LIST BACK TO THE CLIENT

    Gson gson = new Gson();
    gson.toJson(list, resp.getWriter());

} else {
   // Return a message saying,No file has been shared till with the server
  }

Servlet A

if(connection.getResponseCode() == 200) {
    Gson gson = new Gson();
    ArrayList<String> list = gson.fromJson(new InputStreamReader(connection.getInputStream()),ArrayList.class);

.jsp read from reader

<%@page import="com.google.gson.Gson"%>
<%@page import="java.util.ArrayList"%>

<%
Gson gson = new Gson();
ArrayList list = gson.fromJson(request.getReader(), ArrayList.class);
// ...
%>

Upvotes: 2

Related Questions