o7planning

Redirect 301 Permanent redirect in Java Servlet

  1. What is Redirect 301?
  2. Redirect 302 vs Redirect 301
  3. Redirect 301 example

1. What is Redirect 301?

Redirect 301 is to redirect permanently old site address to a new site address. For example, Your current post has the URL:
  • http://yourdomain.com/document/123/java-servlet
And you want move old URLs to new ones permanently:
  • https://yourdomain.com/article/123/java-servlet-tutorial
In case you need to process Redirect 301. When users visit the old address, it will be redirected to new one with a state code 301. The state code 301 is to inform with users' browser as well as google search engine. Normally, the search engine takes some days to replace the old links with the new ones.
Note: Redirect 301 will reduce the site's ranking slightly.
Redirect 301 is a good way helping you to move and entire website from the old domain to a new domain, and it takes 1 to 2 weeks for google search engine to replace all the old URLs. And ranking of sites can decreases slightly.

2. Redirect 302 vs Redirect 301

In Servlet you are familiar with response.sendRedirect () method. This is the method of redirecting a user's request to a new page, it is also called Redirect 302 (temporary redirect).
** Redirect 302
// Temporary Redirect (Redirect 302)
response.sendRedirect(newURL);
** Redirect 301
// Redirect 301.

response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
response.setHeader("Location", newUrl);

3. Redirect 301 example

The following is simple project using Redirect 301.
DataUtils is an utility class getting out map between old URLs and new URLs, you can also store and retrieve this information from the database.
DataUtils.java
package org.o7planning.redirect301;

import java.util.HashMap;
import java.util.Map;

public class DataUtils {

	// Old URL - New URL
	private static Map<String, String> redirect301Map;

	public static Map<String, String> getRedirect301Map() {

		if (redirect301Map == null) {
			redirect301Map = new HashMap<String, String>();

			redirect301Map.put("http://localhost:8080/Redirect301/document/123/java-servlet",
					"http://localhost:8080/Redirect301/article/123/java-servlet-tutorial");

			redirect301Map.put("http://localhost:8080/Redirect301/document/111/java-io-tutorial",
					"http://localhost:8080/Redirect301/article/111/java-io-tutorial");
		}

		return redirect301Map;
	}

}
MyServlet simulates a your web page.
MyServlet.java
package org.o7planning.redirect301;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/*")
public class MyServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public MyServlet() {
        super();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html");
        String text = "<h2>Hello</h2>"//
                + "You are in URL: <br/>"//
                + "<h3>" + request.getRequestURL() + "</h3>";
       
        response.getWriter().print(text);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

}
Redirect301Filter is the filter checking URLs given to server, if URL is old one, it is redirected 301 to new URL.
Redirect301Filter.java
package org.o7planning.redirect301;

import java.io.IOException;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebFilter("/*")
public class Redirect301Filter implements Filter {

	public Redirect301Filter() {
	}

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
			throws IOException, ServletException {

		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;

		// Incomming URL.
		String url = request.getRequestURL().toString();
		System.out.println("Incomming URL = " + url);

		Map<String, String> redirect301Map = DataUtils.getRedirect301Map();

		// Find new URL.
		String newUrl = redirect301Map.get(url);

		if (newUrl != null) {

			// Redirect 301.
			response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
			response.setHeader("Location", newUrl);
			return;
		}

		chain.doFilter(req, resp);
	}

	@Override
	public void init(FilterConfig fConfig) throws ServletException {
	}

}
Running example: