HttpServlet是否必须响应请求?

时间:2018-04-18 14:04:24

标签: java servlets

我有几个服务器端的服务器端。在一些我只是编码一些不必要的数据并将其发回,这似乎毫无意义。你有回应吗?当你说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;
        }
    } 

1 个答案:

答案 0 :(得分:3)

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
}