Free servlet jsp tutorials
response.sendRedirect sends a temporary redirect response to the client using the specified redirect location URL. This method can accept relative or absolute URL. Servlet container converts relative URL to absolute URL before sending response to client. If the location is relative without a leading '/' the container interprets it as relative to the current request URI. If the location is relative with a leading '/' the container interprets it as relative to the servlet container root.
This code snippet shows how to redirect to another URL from a servlet. The destination can be any URL, within the same application or out of it.
Following snippet shows how to redirect to another JSP file.
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class RedirectServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/*
* Destination, it can be any relative or context specific path.
* if the path starts without '/' it is interpreted as relative to the current request URI.
* if the path starts with '/' it is interpreted as relative to the context.
*/
String destination ="/jsp/destination.jsp";
response.sendRedirect(response.encodeRedirectURL(destination));
}
}You can redirect to another site too.
response.sendRedirect(response.encodeRedirectURL("http://www.google.com"));<servlet> <servlet-name>RedirectServlet</servlet-name> <servlet-class>RedirectServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>RedirectServlet</servlet-name> <url-pattern>/redirect</url-pattern> </servlet-mapping>
Redirecting from JSP is same as above. Just put the call to response.sendRedirect() inside a scriptlet.
<% String destination ="/jsp/destination.jsp"; response.sendRedirect(response.encodeRedirectURL(destination)); %>
HttpServletResponse.sendRedirect - HttpServletResponse