response.sendRedirect not working

41,470

Solution 1

You should return after redirecting.

response.sendRedirect("http://www.google.com");
return;

It does not return automatically after calling sendRedirect().

Solution 2

HttpServletResponse.sendRedirect() works like this:

  • if the URL is absolute http://www.google.com , it redirects to http://www.google.com.
  • If the URL is not absolute , it redirects relative to the current URL. If the URL starts with / it redirects relative to the context root, Else it redirects to the current url

Based on above rules in your case it redirects to http://currenturl/www.google.com.

Instead modify your code like this

response.sendRedirect("http://www.google.com");
return;

Solution 3

Try this

<% response.sendRedirect("http://www.google.com/"); %>
Share:
41,470
Amar
Author by

Amar

Updated on July 05, 2022

Comments

  • Amar
    Amar almost 2 years

    The method response.sendRedirect() is not working in my program.

    The code go through and sucessfully print out.println("wrong user");, but the redirect to the google paged doesn't work.

    String id="java";
    
    try 
    {
        query = "select Id from Users where Id= ?";
        ps  =Database.getConnection().prepareStatement(query);
        ps.setString(1, id);
        rs  =   ps.executeQuery();
    
        if(rs.next())
        {
            out.println(rs.getString(1));
        }
        else 
        {
            out.println("wrong user");
            response.sendRedirect("www.google.com");
        }
        rs.close();
    }
    catch(Exception e)
    {
        //e.printStackTrace();
        System.out.print(e);
    }   
    

    Any answers?

  • DerpyNerd
    DerpyNerd about 11 years
    I know it's a year later but, this worked for me. I was using it in an if-statement too, without realizing the rest of the code is still executed. In a catch-clause of a try it does still work without return. Thanks!
  • Hardik Mishra
    Hardik Mishra about 11 years
    @RobbieVercammen: You are Wel-come. Good to hear that. :)
  • Kalaiarasan Manimaran
    Kalaiarasan Manimaran over 10 years
    it is working fr me. good, small mistake i have done +1 for that
  • Rafael Santos
    Rafael Santos almost 5 years
    Worked for me too (7 years after the reply - I'm rewriting some legacy code).
  • Hardik Mishra
    Hardik Mishra almost 5 years
    @RafaelSantos: Happy to hear that!!