如何从 Java servlet 中抛出 404 错误?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3258942/
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
How do I throw a 404 error from within a java servlet?
提问by Kyle
How do I throw a 404 error from within a java servlet? My web.xml already specifies what page to show when there is a 404, how do I throw a 404 from within a servlet?
如何从 Java servlet 中抛出 404 错误?我的 web.xml 已经指定了出现 404 时要显示的页面,如何从 servlet 中抛出 404?
采纳答案by Ladlestein
The Servlet API gives you a method to send a 404 or any other HTTP status code. It's the sendError method of HttpServletResponse:
Servlet API 为您提供了一种发送 404 或任何其他 HTTP 状态代码的方法。这是 HttpServletResponse 的 sendError 方法:
public void doGet(HttpServletRequest request, HttpServletResponse response) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
回答by stacker
In your doGet
or doPost
method you have a parameter HttpServletResponse res
在您的doGet
ordoPost
方法中,您有一个参数HttpServletResponse res
404 is a status code which can be set by:
404 是一个状态码,可以通过以下方式设置:
res.setStatus(HttpServletResponse.SC_NOT_FOUND);
回答by Aravinthan K
For adding Request URL with 404 use this below code
要使用 404 添加请求 URL,请使用以下代码
public void doGet(HttpServletRequest request, HttpServletResponse response) {
response.sendError(HttpServletResponse.SC_NOT_FOUND, request.getRequestURI());
}