Redirect Servlet Based on Path Info And Query String : Redirect « Servlet « Java Tutorial






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);
  }
}
<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
    "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

<web-app>
    <servlet><servlet-name>MyServletName</servlet-name>
             <servlet-class>MyServlet</servlet-class>

             
    </servlet>
    
    <servlet-mapping><servlet-name>MyServletName</servlet-name>
        <url-pattern>/index.html</url-pattern>
    </servlet-mapping>
</web-app>
  Download:  ServletRedirectBasedOnPathInfoAndQueryString.zip( 89 k)








25.15.Redirect
25.15.1.Redirect Servlet by Setting Response Location
25.15.2.Redirect Servlet Based on Path Info And Query String