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

JavaServlets

Java Problem Overview


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 Solutions


Solution 1 - Java

The Servlet API gives you a method to send a 404 or any other HTTP status code. It's the sendError method of HttpServletResponse:

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

Solution 2 - Java

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

404 is a status code which can be set by:

res.setStatus(HttpServletResponse.SC_NOT_FOUND);

Solution 3 - Java

For adding Request URL with 404 use this below code

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKyleView Question on Stackoverflow
Solution 1 - JavaLadlesteinView Answer on Stackoverflow
Solution 2 - JavastackerView Answer on Stackoverflow
Solution 3 - JavaAravinthan KView Answer on Stackoverflow