0

I am calling a java servlet when a form is submitted like this

<form action="/doStuff" method="post" enctype="multipart/form-data">

In side my servlet I do some stuff and make a Object, and now I want to go back to the page where the call was made and give that page this data.

So I am currently doing this

String json = new Gson().toJson(packingListData);
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(json);
        response.sendRedirect("/home.jsp");

If I leave of response.sendRedirect("/home.jsp"); this line I see the object printed out of the page localhost:9080/doStuff

So how can I go back to the page the form was submitted on and get that data?

Thanks

iqueqiorio
  • 1,149
  • 2
  • 35
  • 78
  • Possible duplicate of [How do you return a JSON object from a Java Servlet](http://stackoverflow.com/questions/2010990/how-do-you-return-a-json-object-from-a-java-servlet) – choasia Dec 06 '16 at 00:54

1 Answers1

-1
@WebServlet(urlPatterns = {"/jsonResponse"})
public class JsonResponse extends HttpServlet {

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
Student student = new Student(12, "Ram Kumar", "Male", "1234565678");
Subject subject1 = new Subject(1, "Computer Fundamentals");
Subject subject2 = new Subject(2, "Computer Graphics");
Subject subject3 = new Subject(3, "Data Structures");
Set subjects = new HashSet();
subjects.add(subject1);
subjects.add(subject2);
subjects.add(subject3);
student.setSubjects(subjects);
Address address = new Address(1, "Street 23 NN West ", "Bhilai", "Chhattisgarh", "India");
student.setAddress(address);
Gson gson = new Gson();
String jsonData = gson.toJson(student);
PrintWriter out = response.getWriter();
try {
    out.println(jsonData);
} finally {
    out.close();
}

}
}

Might be helpful from post https://stackoverflow.com/a/56714860/876739 https://stackoverflow.com/a/29512675/876739

see at https://www.ebhor.com/servlet-json-response/

xrcwrn
  • 5,339
  • 17
  • 68
  • 129