繁体   English   中英

Java Servlet 返回 JSON 对象作为响应

[英]Java Servlet return JSON Object in response

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

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

在我的 servlet 中,我做了一些事情并创建了一个对象,现在我想返回进行调用的页面并为该页面提供此数据。

所以我目前正在这样做

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 打印出来的对象

那么如何返回提交表单的页面并获取该数据?

谢谢

@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/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM