我現在創建一個簡單的Servlet來回答表單子表單。這個servlet接收POST請求並應該響應Application/JSON數據。這很好。 我現在想要將錯誤管理添加到我的servlet中:如果servlet接收到錯誤的請求參數,我希望它通過簡單的{"error":"ERROR MESSAGE"}
JSON響應來回答客戶端400 - 「錯誤請求」響應。HttpServletResponse#sendError如何更改ContentType
我使用HttpServletResponse#sendError(int,String)
來正確發送錯誤,但ContentType
的響應始終設置爲text/html
,即使我以前使用HttpServletResponse#setContentType("application/json")
。
這是使用Servets發送錯誤的好方法嗎?我怎樣才能強制ContentType
的迴應application/json
?
編輯:我測試的Servlet的doPost()方法的示例代碼:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("application/json;charset=UTF-8");
PrintWriter out = response.getWriter();
out.print("{\"error\":1}");
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
}
感謝您的快速回復! 我嘗試了你的解釋。不知道如果做得好,因爲它沒有按預期工作。 :( 不確定關於「寫入緩衝區」部分我編輯了第一篇文章,其中包含我用於測試目的的代碼示例 – pdegand59
這不適用於我sendError會忽略之前寫的任何內容 –