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?
Asked
Active
Viewed 7.2k times
3 Answers
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
-
5After 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