Whizu

jQuery Mobile in Java

View project on GitHub
Whizu Download
jQuery Mobile widgets
Pages Accordions Buttons Collapsibles
Check out my latest project at www.whizu.me and stop typing passwords with Kee Password Manager. Just like that.

How to programmatically throw a 404 error from a servlet

Written by Rudy D'hauwe on June 10, 2013.

This article explains how to throw and send a 404 status code from within a Java servlet. A 404 status code is most commonly set on the HTTP response when a page or resource is requested that cannot be found.

Http Status Codes

When a web server responds to a request from a browser or other web client, the response typically consists of a status line, some response headers, a blank line, and the document.

Here is a minimal example:

HTTP/1.1 200 OK 
Content-Type: text/plain

Hello World

The status line consists of the HTTP version, an integer that is interpreted as a status code, and a very short message corresponding to the status code. In most cases, all of the headers are optional except for Content-Type, which specifies the MIME type of the document that follows.

Servlets can perform a variety of tasks by manipulating the status line and the response headers. For example, they can forward the user to other sites; indicate that the attached document is an image, an Adobe Acrobat file, or most commonly an HTML file; tell the user that a password is required to access the document; and so forth.

This article explains how to set the status code from within a Java servlet indicating that a page or resource cannot be found.

It's easy :-)

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

public void doGet(HttpServletRequest req, HttpServletResponse res) {
    res.sendError(HttpServletResponse.SC_NOT_FOUND);
}
Written by Rudy D'hauwe | Copyright © 2013-2014 | All rights reserved.