JSP中元素顺序的问题

4
几天前,我开始学习Java EE和Web开发(首先是Tomcat、Servlets和JSP)。
现在我有了这个JSP页面的代码。正如你所看到的,标题“Hello World with JSP”会出现在<% ... %>块之前。
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="java.util.*" %>

<html>
<body>
<h1 align=”center”>Hello World with JSP</h1>
<br>
<%
    List styles = (List)request.getAttribute("styles");
    for(Object style: styles){
    response.getWriter().println("<br>try: " + style);
    }
%>

</body>
</html>

但是,结果页面中来自<% ... %>的结果会出现在Hello World with JSP标题之前。为什么呢?

screenshot

附言:对术语不熟悉,抱歉。我是一个新手。

3个回答

5
JSP使用隐式的JspWriter实例来写入输出流,该实例称为"out"。它与从response.getWriter()获取的PrintWriter实例并不完全相同,因为它在实际写入流之前进行了一些额外的缓冲。当您直接打印到PrintWriter时,基本上是在JspWriter缓冲被清空之前就已经写入了流,因此您的List会在"Hello World" HTML之前被打印出来。相反,您需要使用隐式的JspWriter实例"out"。
<%
    List styles = (List)request.getAttribute("styles");
    for(Object style: styles){
        out.println("<br>try: " + style);
    }
%>

顺便提一下,JSP中的脚本片段 <% %>已经不建议使用了。请考虑使用JSP EL和JSTL标签。


2
一个JSP会被编译成一个Java servlet。当你执行以下脚本代码时:
response.getWriter().println(...);

您正在获取HttpServletResponsePrintWriter,它直接写入OutputStream,在任何HTML(来自JSP)被编写之前进行操作。看这个例子。
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="java.util.*" %>

<html>
<head>

</head>
<body>
<%
    response.getWriter().println("hellllooooooooo"); // using response.getWriter().println()
%>
the time is now
<h1 align=”center”>Hello World with JSP</h1>
<br>
<%
    List styles = (List)request.getAttribute("styles");
    for(Object style: styles){
        out.println("<br>try: " + style); // using out.println()
    }
%>

</body>
</html>

你将会收到的响应内容是:
hellllooooooooo



<html>
<head>

</head>
<body>

the time is now
<h1 align=”center”>Hello World with JSP</h1>
<br>
<br>try: asdaS
<br>try: asdasdasda


</body>
</html>

注意,在任何东西之前都会打印出“hellllooooooooo”。JSP会给你一个类型为JspWriterout变量,允许你按预期顺序输出。请参见上面的示例,以从请求属性styles中编写元素。 重要提示 这是scriplets不被推荐的原因之一。考虑改用JSTL

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接