Permanent and Temporary Redirects in Java (Servlet/JSP)

Posted 2008-11-08 in Java by Johann.

Redirects in Servlets

To perform a permanent or temporary redirect in a Servlet, set the status property of the HttpServletResponse object to either SC_MOVED_PERMANENTLY (301) or SC_MOVED_TEMPORARILY (302) and set the Location header to the target URL.

response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
response.setHeader("Location", "https://johannburkard.de/");

While the HttpServletResponse object already has a sendRedirect method, the specification says that it sends…

…a temporary redirect response to the client using the specified redirect location URL.

This is why I select the HTTP status code manually.

Redirects in JSPs

JSPs obviously take the same code as Servlets. Here is a sample redirection in a JSP.

<%@ page import="javax.servlet.http.*"><%
response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
response.setHeader("Location", "https://johannburkard.de/"); %>

Redirects using Refresh header

Some web analytics packages do not analyze URL parameters if the HTTP status code is not 200. In this scenario, a redirect using the Refresh header can also be used.

String target = "https://johannburkard.de";
response.setContentType("text/html");
response.setContentLength(13);
response.addHeader("Refresh",
    new StringBuilder(target.length() + 5).append("0;url=").
    append(target).toString());

ServletOutputStream out = response.getOutputStream();
out.print("<html></html>");

This code is taken from my ReDirector servlet which uses XML files for redirection targets.

Debugging Redirection

wget is the Swiss army knife of HTTP tools and I frequently use its debug mode (-d) to solve HTTP problems.

> wget -d http://127.0.0.1:8081/servlet/com.eaio.TestServlet
DEBUG output created by Wget 1.10.2 on Windows.

--10:15:54--  http://127.0.0.1:8081/servlet/com.eaio.TestServlet
           => `com.eaio.TestServlet'
Connecting to 127.0.0.1:8081... seconds 0.00, connected.
Created socket 1952.
Releasing 0x003a49a8 (new refcount 0).
Deleting unused 0x003a49a8.

---request begin---
GET /servlet/com.eaio.TestServlet HTTP/1.0
User-Agent: Wget/1.10.2
Accept: */*
Host: 127.0.0.1:8081
Connection: Keep-Alive

---request end---
HTTP request sent, awaiting response...
---response begin---
HTTP/1.1 301 Moved Permanently
Date: Sat, 08 Nov 2008 09:15:56 GMT
Server: Orion/2.0.7
Connection: Close
Content-Type: text/plain
Location: https://johannburkard.de/

---response end---

Subscribe

RSS 2.0, Atom or subscribe by Email.

Top Posts

  1. DynaCloud - a dynamic JavaScript tag/keyword cloud with jQuery
  2. 6 fast jQuery Tips: More basic Snippets
  3. xslt.js version 3.2 released
  4. xslt.js version 3.0 released XML XSLT now with jQuery plugin
  5. Forum Scanners - prevent forum abuse
  6. Automate JavaScript compression with YUI Compressor and /packer/

Navigation