Several days ago I started to learn Java EE and web development (firstly: Tomcat, Servlets, JSP).
So now I have this JSP page code.
As you can see, the header Hello World with JSP
stay before <% ... %>
block.:
<%@ 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>
But in result web page result from <% ... %>
stay before the Hello World with JSP
header. Why?
P.S. Sorry for terminology but I'm really new in web development.
JSPs use an implicit JspWriter
instance called out
to write to the output stream. It's not exactly the same as the PrintWriter
instance you receive from response.getWriter()
as it does some additional buffering before it actually writes to the stream.
When you directly print to PrintWriter
you've basically written to the stream before the JspWriter
buffer was flushed and hence your List
gets printed before the "Hello World" HTML.
What you need instead is to use the implicit JspWriter
instance out
as
<%
List styles = (List)request.getAttribute("styles");
for(Object style: styles){
out.println("<br>try: " + style);
}
%>
By the way, scriptlets <% %>
in JSPs are deprecated now. Please, look into JSP EL and JSTL tags.
I think you want to use out.println instead of response.getWriter().println. See How to output HTML from JSP <%! … %> block?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With