How to create a 301 redirect with Java Server Pages (JSP)?

Creating a 301 redirect as part of the server configuration is always the best solution. But if you only need to build a local redirection, only from one specific file of your server, it can be useful to make it in a scripting language such as JSP, rather than configuring the whole server for an exceptional behaviour.

This page describes the few steps you'll need to follow in order to set up a 301 redirect using Java Server Pages language. In fact, the main steps of this process only consist of a a few lines code you'll have to paste on top of the file you need to redirect. That's all.

Defining the 301 code and the target address.
As JSP is a server side language, it can easily compute some data even before any answer has been sent to the client browser from the server. Using this behaviour, and some adequate commands, it's then easy to dynamically write a new header for a request and define it as a 301.

To achieve this, first open the file from which you want to set up the redirection. This file must, of course, be a JSP file in order to be able to execute Java Server Pages code on your server. Then, copy the following code, as the very first lines of your JSP file, and replace the by the real destination address of your 301.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
response.setHeader( "Location", "h;
response.setHeader( "Connection", "close" );

In the JSP language, response object is used to define the answer of the server to a specific request, and so can be used to define a 301 redirect. This way, the first information your client will receive is the relocation command. Obeying to the redirection code, it will not keep in consideration any line of the following page.

Dynamically defining the redirection target.
If the response object must be the first instruction to be sent to the client, it's not necessarly the first one to be executed by the server. Using JSP redirection, you are free to use any command you need before the response object setting, as long as you don't send any data to the client browser.

You can then easily imagine that the target address of the redirection is defined following attributes present in the original page address, session's values or any database entry. Storing this new address in a JSP variable is then easy, and reusing it in the response location is a matter of a single line modification.

Creative Commons License
This site is available uder Creative Commons licence.