简体   繁体   English

如何从 Java servlet 中抛出 404 错误?

[英]How do I throw a 404 error from within a java servlet?

How do I throw a 404 error from within a java servlet?如何从 Java servlet 中抛出 404 错误? My web.xml already specifies what page to show when there is a 404, how do I throw a 404 from within a servlet?我的 web.xml 已经指定了出现 404 时要显示的页面,如何从 servlet 中抛出 404?

The Servlet API gives you a method to send a 404 or any other HTTP status code. Servlet API 为您提供了一种发送 404 或任何其他 HTTP 状态代码的方法。 It's the sendError method of HttpServletResponse:这是 HttpServletResponse 的 sendError 方法:

public void doGet(HttpServletRequest request, HttpServletResponse response) {
    response.sendError(HttpServletResponse.SC_NOT_FOUND);
}

In your doGet or doPost method you have a parameter HttpServletResponse res在您的doGetdoPost方法中,您有一个参数HttpServletResponse res

404 is a status code which can be set by: 404 是一个状态码,可以通过以下方式设置:

res.setStatus(HttpServletResponse.SC_NOT_FOUND);

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());
}

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

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