为什么Servlet页面刷新/重新加载而不是重定向(使用元标记)?

时间:2011-07-24 08:33:24

标签: servlets cookies

*//post method*
protected void doPost (HttpServletRequest req, HttpServletResponse res)
        throws ServletException,IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password"); 
        System.out.println( " Form data recieved .. Now Verifying ");

        if ( loginVerificator ( username, password ) )  {
            Cookie xO = new Cookie ( "username", username );
            Cookie xT = new Cookie ( "password", password );            
            res.addCookie( xO );
            res.addCookie( xT );
            res.setContentType( "text/html" );
            PrintWriter out = res.getWriter( );
            out.println("<meta http-equiv=\"refresh\" content=\"2\";url=\"home\">");
        }

post方法检索表单参数,然后从中创建cookie并将这些cookie添加到响应中。然后它使用元标记重定向页面。

我想知道为什么这个页面正在重新加载而不是重定向。我无法找到我犯错误的地方。

1 个答案:

答案 0 :(得分:0)

out.println("<meta http-equiv=\"refresh\" content=\"2\";url=\"home\">");

在响应中使用以下值写入meta标记:

<meta http-equiv="refresh" content="2";url="home">这是不正确的,因为url未被内容属性值的引号包装。相反,标签应该生成为:

<meta http-equiv="refresh" content="2;url=home">,它要求servlet中的相应行为:

out.println("<meta http-equiv=\"refresh\" content=\"2;url=home\">");


请注意,meta refresh概念已为deprecated by W3C。如果您打算将用户重定向到新页面,最好使用HTTP 302响应,这可以使用HttpServletResponse.sendRedirect(location)方法在Servlet中轻松实现。

相关问题