【问题标题】:When I'm using RequestDispatcher, instead of processing contents of JSP, JSP page as whole is being rendered on output当我使用 RequestDispatcher 时,不是处理 JSP 的内容,而是在输出上呈现整个 JSP 页面
【发布时间】:2012-06-20 12:25:44
【问题描述】:

当我调用 RequestDispatcher 时,不是处理请求,而是将 JSP 页面本身呈现为输出...JSP 内容出现在“帐户已创建”行之后。

//Servlet 块

if(i==1){
            PrintWriter pw = response.getWriter();
            pw.println("Account Created!!");
            RequestDispatcher rd = request.getRequestDispatcher("Login.jsp");
            rd.include(request, response);
            System.out.println("Record Updated!!!");
        }

//在浏览器上呈现的输出:

Account Created!!

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<link rel="icon" type="image/ico" href="favicon.ico"></link> 
<link rel="shortcut icon" href="favicon.ico"></link>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login Page</title>
</head>
<body>
<form action="./Authentication" method="post">
    <p>Enter username<input type="text" name="Uname"></p>
    <p>Enter password<input type="password" name="Pword"></p>
    <input type="submit" value="Login"> 
</form>
</body>
</html>

【问题讨论】:

    标签: jsp servlets


    【解决方案1】:

    您不应该在 servlet 中获取编写器,也不应该手动向其写入字符串,并且应该使用 RequestDispatcher#forward() 而不是 include()。否则,您会阻止 JSP 设置正确的 text/html 内容类型,因此 Web 浏览器会将所有内容解释为纯文本。

    如下重写该 servlet 块以让 JSP 正常工作:

    if (i == 1) {
        request.getRequestDispatcher("Login.jsp").forward(request, response);
    }
    

    另见:

    【讨论】:

    • @BalusC...能否请您告诉我为什么 include 在这种情况下不起作用?
    • 因为 JSP 无法设置正确的 text/html 内容类型。阅读include() 的javadoc:docs.oracle.com/javaee/6/api/javax/servlet/… 您毕竟只是使用了错误的方式将控件转发到JSP。 include() 不存在,您根本不应该在 servlet 中获取响应编写器,这不是 servlet 的责任。
    【解决方案2】:

    这是因为在将响应发送到浏览器之前,您没有将 contentType 设置为响应。

    设置response.setContentType("text/html"); 它应该适合你。 :)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-18
      • 2019-08-18
      • 2021-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-21
      相关资源
      最近更新 更多