我想創建一個簡單的Java Web應用程序響應GET請求/用JSON字符串測試。Java Web服務器響應與JSON
我的環境是Java,Intellij和Tomcat 8.5.4。
到目前爲止,我有3個班已經:
- CSV - 爲CSV以JSON轉換
- 清理 - 一類實際上轉換數據
- 的Servlet - 即響應一個GET類請
我的Servlet類:
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(name = "Servlet")
public class Servlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("GET request received");
CleanUp cleanup = new CleanUp();
cleanup.cleanupData();
// Logic needed here to send the data to client
}
}
個
清理階級當前並將所得的數據來安慰一樣:
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
mapper.writeValue(System.out, list);
我farily新甚至不知道如果我想什麼可以做的javax.http.servlet的一部分或需要其他的依賴?
因此,您收到了需要回復的GET請求。您需要決定要將內容類型發送回客戶端。數據可以寫入Response.getOutputStream()。如果它的文本或HTML,那麼你不需要其他庫。 –
它的JSON,所以我可以把它作爲純文本? 在doPost中就像添加Response.getOutPutStream(mapper.writeValue(System.out,list))一樣簡單; ? –
是的,如果您將JSON對象轉換爲String,則可以寫入響應。如果你不關心發佈的內容,你的doPost()可以調用doGet()。 –