Java Servlet返回JSON对象作为响应

时间:2016-12-05 23:34:40

标签: java json jsp servlets

当像这样提交表单时,我正在调用java servlet

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

在我的servlet中,我做了一些东西并创建了一个Object,现在我想回到调用的页面,并为该页面提供这些数据。

所以我现在正在做这个

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

如果我离开response.sendRedirect("/home.jsp");这一行我看到对象打印出页面localhost:9080 / doStuff

那么我怎样才能回到提交表单的页面并获取该数据?

由于

1 个答案:

答案 0 :(得分:-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();
}

}
}

发布后可能会有所帮助 https://stackoverflow.com/a/56714860/876739 https://stackoverflow.com/a/29512675/876739

请参阅 https://www.ebhor.com/servlet-json-response/