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

时间:2022-10-09 22:58:02

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错误?我的网络。xml已经指定在有404页面时要显示什么页面,如何从servlet中抛出404 ?

2 个解决方案

#1


110  

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状态代码的方法。是httpletservresponse的sendError方法:

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

#2


5  

In your doGet or doPost method you have a parameter HttpServletResponse res

在doGet或doPost方法中,您有一个参数HttpServletResponse res

404 is a status code which can be set by:

404是一种状态代码,可以通过以下方式设置:

res.setStatus(HttpServletResponse.SC_NOT_FOUND);

#1


110  

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状态代码的方法。是httpletservresponse的sendError方法:

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

#2


5  

In your doGet or doPost method you have a parameter HttpServletResponse res

在doGet或doPost方法中,您有一个参数HttpServletResponse res

404 is a status code which can be set by:

404是一种状态代码,可以通过以下方式设置:

res.setStatus(HttpServletResponse.SC_NOT_FOUND);