是否可以在 Java 中明确返回 401 Unauthorized 响应代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14393574/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible in Java to return the 401 Unauthorized response code explicitly
提问by Patan
I am working on a web service. I want to return the 401: Unauthorized
response to the user for invalid credentials.
我正在开发一个网络服务。我想将401: Unauthorized
无效凭据的响应返回给用户。
How do I manually return this response code?
如何手动返回此响应代码?
回答by Bogdan Calmac
For error status codes like 401, use the more specific sendError():
对于 401 之类的错误状态代码,请使用更具体的sendError():
httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "your message goes here");
This takes care of everything, it sets the status code and also writes the response.
这会处理所有事情,它设置状态代码并写入响应。
回答by Austin Greco
assuming you are using servlets, you would set the http status to 401 using the setStatus
method:
假设您正在使用 servlet,您可以使用以下setStatus
方法将 http 状态设置为 401 :
httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
回答by Luis Limas
I've learned the following from both Austin'sand Bodgananswers, this may save some minutes for someone else looking for this answer.
我从Austin和Bodgan 的答案中了解到以下内容,这可能会为其他寻找此答案的人节省一些时间。
For me, the correct answer is Bodgand's:
对我来说,正确答案是Bodgand 的:
httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "your message goes here");
The reason is that responses being thrown using the sendError
method are catched by the web.xml
filters
原因是使用该sendError
方法抛出的响应被web.xml
过滤器捕获
So if you had specified at your web.xml
filter this:
因此,如果您在web.xml
过滤器中指定了以下内容:
<error-page>
<error-code>401</error-code>
<location>/errors/401.jsp</location>
</error-page>
You will only see that error-page when you use the sendError
method.
您只会在使用该sendError
方法时看到该错误页面。