Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

servlets

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?

like image 624
Kyle Avatar asked Jul 15 '10 18:07

Kyle


People also ask

How do you trigger a 404?

There are several reasons why you might be getting an HTTP 404 code: One typical trigger for an error 404 message is when the page has been deleted from the website. The page was moved to another URL and the redirection was done incorrectly. You entered an incorrect URL address.

What is Servlet Error 404 Eclipse?

This error indicates that the server could not find the desired resource. This resource can be any file such as JSP, HTML, or image resource. Usually, the resource is present, but it is referenced incorrectly. In most cases, you can fix this by correcting the URL.

When would you use 404 error code?

This 404 error page shows the user the error code, what it means and potential ways to navigate around it. 404 error codes are generated when a user attempts to access a webpage that does not exist, has been moved, or has a dead or broken link.


2 Answers

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); } 
like image 148
Ladlestein Avatar answered Sep 20 '22 07:09

Ladlestein


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); 
like image 24
stacker Avatar answered Sep 20 '22 07:09

stacker