response.sendRedirect无效

Ama*_*mar 5 jsp jdbc response

方法response.sendRedirect()在我的程序中不起作用.

代码通过并成功打印out.println("wrong user");,但重定向到谷歌分页不起作用.

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);
}   
Run Code Online (Sandbox Code Playgroud)

任何答案?

Har*_*hra 16

你应该return重定向后.

response.sendRedirect("http://www.google.com");
return;
Run Code Online (Sandbox Code Playgroud)

调用sendRedirect()后它不会自动返回.

  • 我知道已经过了一年,但这对我有用。我也在if语句中使用它,而没有意识到其余代码仍在执行。在尝试时,它仍然可以正常工作而不会返回。谢谢! (3认同)

Ram*_*PVK 5

HttpServletResponse.sendRedirect() 的工作原理如下:

  • 如果 URL 是绝对的http://www.google.com,它将重定向到http://www.google.com.
  • 如果 URL 不是绝对的,它将相对于当前 URL 进行重定向。如果 URL 开头,则/相对于上下文根重定向,否则重定向到当前 url

根据以上规则in your case it redirects to http://currenturl/www.google.com

而是像这样修改你的代码

response.sendRedirect("http://www.google.com");
return;
Run Code Online (Sandbox Code Playgroud)