![](/img/trans.png)
[英]Ajax HTTPServlet request does not pass information from ajax to controller
[英]Does a HttpServlet have to respond to a request?
我有幾個在服務器端執行操作的servlet。 我只對一些不必要的數據進行編碼,然后將其發送回去,這似乎毫無意義。 您需要回應嗎? 當您只說return
時會發生什么? 我之前已經做過,似乎沒什么問題,但是我對servlet還是比較陌生。 僅僅歸還我頭上的東西會有后果嗎? 當您返回時究竟發生了什么?
if(request.getParameter("name").equals("saveusedcards")) {
String sessId = request.getSession().getId();
//encode request with confirmation that cards were successfully updated
if(usersUpdatedCards.get(sessId).isEmpty()){
//no cards were seen
}
boolean success = DataDAO.updateCards(usersUpdatedCards.get(sessId));
if(success){
System.out.println("Data base update successfull!");
String responseMessage = new Gson().toJson("card successfully udpated");
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
System.out.println("updated cards response message: "+responseMessage);
response.getWriter().write(responseMessage);
return;
} else {
System.out.println("Data base update failed...");
String responseMessage = new Gson().toJson("card was not successfully updated");
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
System.out.println("updated cards response message: "+responseMessage);
response.getWriter().write(responseMessage);
return;
}
}
Servlet必須為客戶端生成HTTP響應,但是完全不接受響應主體中的任何內容是可以接受的。 這樣做時,您的servlet應該通過發送響應代碼204(無內容)來向客戶端表明這一點。 參考: https : //httpstatuses.com/204
這是如何從doGet
方法設置響應代碼的示例。 您可以通過doPost
或service
方法執行相同的操作。
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
// Do whatever work you need to do here...
res.setStatus(HttpServletResponse. SC_NO_CONTENT); // This returns a 204
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.