I'm beginning to work with JSTL-spring. It's wonderful, however I need to review the HTML code that it generates. I have a method that appends to a string all the HTML code, so when I <c:out>
the string it prints one big line, the browser int开发者_高级运维erprets it fine, but not me, and I need to, to accurately debug and make a clean code.
In other words I need linebreaks for the HTML string, not linebreaks for the interpreted html (not <br>
tag). I tried /n
but it just prints /n
. Here is code example:
productThumbnails+="<div class=\"prod_box\">";
productThumbnails+="<div class=\"top_prod_box\"></div>";
productThumbnails+="<div class=\"center_prod_box\">";
productThumbnails+="<div class=\"product_title\"><a href=\"details.html\">"+productTemp.getProductName()+"</a></div>";
productThumbnails+="<div class=\"product_title\"><a href=\"details.html\">"+productTemp.getProductModel()+"</a></div>";
productThumbnails+="<div class=\"product_img\"><a href=\"details.html\"><img width=\"90\" alt=\""+productTemp.getProductName()+"\" src=\""+productTemp.getProductImage()+"\"/></a></div>";
productThumbnails+="</div>";
productThumbnails+="</div>";
In the view, I print everything with:
<c:out value="${productThumbnails}" escapeXml="false" />
There are two ways:
This is actually servletcontainer specific, but based on your question history you're using Tomcat. Add the following initialization parameter to the
JspServlet
entry inTomcat/conf/web.xml
.<init-param> <param-name>trimSpaces</param-name> <param-value>true</param-value> </init-param>
This way any whitespace which is left by taglibs (JSTL and so on) will be trimmed. This is not perfect, but generally sufficient. This does however not cover HTML which is written in the wrong place (i.e. not in JSP).
Use
jTidyFilter
. Drop jtidyservlet.jar in/WEB-INF/lib
and declare the filter in yourWebapp/WEB-INF/web.xml
as per its documentation.
Coming back to the comment that you're approaching this wrong: the proper approach would be to put List<Product>
in the request scope (if necessary by a Spring bean) and use JSTL <c:forEach>
to iterate over it.
<c:forEach items="${products}" var="product">
...
<div class="center_prod_box">
<div class="product_title"><a href="details.html"><c:out value="${product.productName}" /></a></div>
<div class="product_title"><a href="details.html"><c:out value="${product.productModel}" /></a></div>
<div class="product_img"><a href="details.html"><img width="90" alt="${product.productName}" src="${product.productImage}"/></a></div>
</div>
...
</c:forEach>
That yields more clean and better maintainable code (and HTML output ;) ).
精彩评论