response.sendRedirect() - Redirect to another Servlet or JSP
in
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.
Redirect to another URL within same application.
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));
- }
- }
Redirect to another site
You can redirect to another site too.
- response.sendRedirect(response.encodeRedirectURL("http://www.google.com"));
web.xml
- <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>
Redirect from JSP
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));
- %>
Reference
HttpServletResponse.sendRedirect - HttpServletResponse
