Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems with elements order in JSP

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?

screenshot

P.S. Sorry for terminology but I'm really new in web development.

like image 353
Petr Shypila Avatar asked Jan 13 '23 09:01

Petr Shypila


2 Answers

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.

like image 183
Ravi K Thapliyal Avatar answered Jan 14 '23 23:01

Ravi K Thapliyal


I think you want to use out.println instead of response.getWriter().println. See How to output HTML from JSP <%! … %> block?

like image 39
Jeff Miller Avatar answered Jan 14 '23 21:01

Jeff Miller