gpt4 book ai didi

java - HttpServlet 是否必须响应请求?

转载 作者:行者123 更新时间:2023-12-01 19:54:59 26 4
gpt4 key购买 nike

我有几个在服务器端执行操作的 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 方法设置响应代码的示例。您可以通过 doPostservice 方法执行相同的操作。

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

关于java - HttpServlet 是否必须响应请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49901805/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com