Java Tutorial/Servlet/Redirect
Redirect Servlet Based on Path Info And Query String
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class MyServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
// Determine the site where they want to go
String site = req.getPathInfo();
String query = req.getQueryString();
// Handle a bad request
if (site == null) {
res.sendError(res.SC_BAD_REQUEST, "Extra path info required");
}
// Cut off the leading "/" and append the query string
// We"re assuming the path info URL is always absolute
String url = site.substring(1) + (query == null ? "" : "?" + query);
// Log the requested URL and redirect
log(url); // or write to a special file
res.sendRedirect(url);
}
}
Redirect Servlet by Setting Response Location
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class MyServlet extends HttpServlet {
Vector sites = new Vector();
Random random = new Random();
public void init() throws ServletException {
sites.addElement("http://www.jexp.ru/Code/Java/CatalogJava.htm");
sites.addElement("http://www.jexp.ru/Tutorial/Java/CatalogJava.htm");
sites.addElement("http://www.jexp.ru/Article/Java/CatalogJava.htm");
sites.addElement("http://www.jexp.ru/Product/Java/CatalogJava.htm");
}
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
int siteIndex = Math.abs(random.nextInt()) % sites.size();
String site = (String)sites.elementAt(siteIndex);
res.setStatus(res.SC_MOVED_TEMPORARILY);
res.setHeader("Location", site);
}
}