简体   繁体   English

正确的语法没有“返回任何东西”的servlet?

[英]Correct syntax for a servlet that doesn't “return anything”?

What is the correct way of terminating a servlet that doesn't return any data to the client? 终止不向客户端返回任何数据的servlet的正确方法是什么?

The purpose of the servlet in question is to recive some data from an Ajax request and fire off a TCP message to a piece of hardware to tell it to change it's state. 有问题的servlet的目的是从Ajax请求中恢复一些数据并将TCP消息发送到一块硬件,告诉它改变它的状态。

Do you have to specify a response at all? 您是否必须指定响应?

I've opted for getting a reference to the Output stream and closing it, is this correct? 我选择获取输出流的引用并关闭它,这是正确的吗?

Should I send back a "hey that worked" message? 我应该发回“嘿那工作”的消息吗?

If you just want to provide a "success" status just return HTTP code 200. You don't have to return any stream since you just want to say "OK". 如果您只想提供“成功”状态,只需返回HTTP代码200.您不必返回任何流,因为您只想说“确定”。

public void doGet(...) {
    response.setStatus(HttpServletResponse.SC_OK); 
}

I think responding is nice, if you watch something like gmail you'll notice a lot of POSTs that get 我觉得回复很好,如果你看一下像gmail这样的东西,你会注意到很多POST

ok

as the response, I like this. 作为回应,我喜欢这个。 It is simple and concise. 它简单而简洁。

The other thing to think about is how will you deal with the case where your request fails in some way, I think your client should probably report something to the user if it is unsuccessful, and therefore it'll need a response from the servlet. 要考虑的另一件事是你将如何处理你的请求以某种方式失败的情况,我认为你的客户端应该向用户报告一些不成功的事情,因此它需要来自servlet的响应。

Your servlet is going to send the response headers with the status code and whatnot in any case, I don't see why you should output anything on top of that. 您的servlet将发送带有状态代码的响应头,无论如何,我不明白为什么你应该输出任何东西。 :) :)

In these situations I generally return a success message, ie something like (in JSON) 在这些情况下,我通常会返回一条成功消息,例如(在JSON中)

{ success: true }

I find it helps sometimes with debugging! 我发现它有时会有助于调试! I don't think there is a 'correct' response though, provided that your servlet returns a 200 response code (which I think they do unless you specify otherwise) then there is no problem. 我不认为有一个'正确'的响应,只要你的servlet返回200响应代码(除非你另有说明,我认为他们会这样做)然后没有问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM