67

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?

Pascal Thivent
  • 562,542
  • 136
  • 1,062
  • 1,124
Kyle
  • 21,377
  • 37
  • 113
  • 200

3 Answers3

127

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);
}
Ladlestein
  • 6,100
  • 2
  • 37
  • 49
  • 5
    After generating this error, whether user will be redirected to error page if configured in web.xml ? – Voonic Apr 10 '14 at 09:41
7

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);
stacker
  • 68,052
  • 28
  • 140
  • 210
0

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());
}
Aravinthan K
  • 1,763
  • 2
  • 19
  • 22