Servlet SendRedirect
The sendRedirect() method belongs to HttpServletResponse interface which use to redirect response to other resource.
e.g. If request comes to a servlet and redirect to other URL because of below code snippet:
response.sendRedirect(“http://www.google.com”);
sendRedirect() accepts both relative as well as absolute URL.
Example
- Open eclipse and Click on File as highlighted below.
File → New → Other
2. Select “Dynamic Web Project” and click on “next” button will help us to create project related to servlet.
3. Provide the project name and click on finish will help us to create project. On current example we have given as “ServletDemo”.
4. Don’t make any change and click on Next.
5. Check the checkbox to generate web.xml and click on Finish button will create project.
6. Right click on below highlighted folder and create a package having name com.javadoubts.servlet
7. Inside package com.javadoubts.servlet, create LoginServlet.java class and type below content.
8. Place below content in web.xml file
9. Now, its time to run application.
Right click on the project and select Run As and then Run on Server to run application on Apache Tomcat.
On hitting below URL will redirect us to Google page because of sendRedirect() method statement written in LoginServlet.java class.
Imran Khan, Adobe Community Advisor, AEM certified developer and Java Geek, is an experienced AEM developer with over 11 years of expertise in designing and implementing robust web applications. He leverages Adobe Experience Manager, Analytics, and Target to create dynamic digital experiences. Imran possesses extensive expertise in J2EE, Sightly, Struts 2.0, Spring, Hibernate, JPA, React, HTML, jQuery, and JavaScript.