In this tutorial, you will learn how to redirect Requests to Other Resources using SendRedirect in java servlet.
In this tutorial, you will learn how to redirect Requests to Other Resources using SendRedirect in java servlet.In this tutorial, you will learn how to redirect Requests to Other Resources using SendRedirect in java servlet.
SendRedirect() :
Response provide method sendRedirect() which sends a redirect response to the
client using the given redirect location. You can specify relative or absolute
URL to sendRedirect().
Example : In this example we are using sendRedirect() method to redirect into new page.
SendRedirectExample.java -
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 SendRedirectExample extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.sendRedirect("home.html"); } }
home.html -
<html> <head> <title>Home Page</title> </head> <body> <h2 align="center">Welcome</h2> <h3>This is your home page.</h3> </body> </html>
web.xml -
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>SendRedirect</display-name> <servlet> <description></description> <display-name>SendRedirectExample</display-name> <servlet-name>SendRedirectExample</servlet-name> <servlet-class>SendRedirectExample</servlet-class> </servlet> <servlet-mapping> <servlet-name>SendRedirectExample</servlet-name> <url-pattern>/SendRedirectExample</url-pattern> </servlet-mapping> </web-app>
Output :