Servlet SendRedirect

The servlet 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

  1. 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.

http://localhost:8082/ServletDemo/login

Imran Khan

Specialist Master (Architect) with a passion for cutting-edge technologies like AEM (Adobe Experience Manager) and a proven track record of delivering high-quality software solutions.

  • Languages: Java, Python
  • Frameworks: J2EE, Spring, Struts 2.0, Hibernate
  • Web Technologies: React, HTML, CSS
  • Analytics: Adobe Analytics
  • Tools & Technologies: IntelliJ, JIRA

🌐 LinkedIn

📝 Blogs

📧 Imran Khan