Using jade(pug) to create jsp - java

I would like to write a fast and easy to maintain html/jsp code, so I read about html processors and jade(pug), which seems to be ok for me.
But now I have a problem because I can't/don't know how to:
create file with JSP extension using pug
inject "<%# page contentType="text/html;charset=UTF-8" language="java" %>" from pug to my jsp file
Or maybe there is a different approach for this?
Ok I just solved my problem:
for extension we need to use this
pug index1.pug --extension jsp --pretty
We can just insert this to pug file

From an edit to the question:
Ok I just solved my problem:
for extension we need to use this:
pug index1.pug --extension jsp --pretty
We can just insert this to pug file

Related

Using ArrayList in a sub-template on .jsp page

I have a JSP home page with a menu. I want that menu to be on multiple pages so I created a menu.jsp template. I imported, all static source code appears but the <c:forEach /> tag is not picking it up. When I print (just put it plainly in the html) out my ${allCategories} variable I get all the data correctly.
In a controller, I set model.addAttribute("allCategories", categoryService.getPrimaryCategories());
home.jsp where the categories were before is importing <jsp:include page="menu.jsp"/>
in menu.jsp I am unable to get <c:forEach items="${allCategories}" var="category"> to work but when I just put <p>${allCategories}</p> at the beginning of the file it shows stuff like [Category(id=1281, name=Bundles, image=https://images...
How do I get the data correctly in the sub-template so it works like directly on the page?
You could try using the JSP include directive. It is used to include a file during the translation phase. For example,
<%# include file = "menu.jsp" >

jsp ${pageContext.request.contextPath} dosent get requested

Currently i have a .jsp project where my welcome page is a servlet
<welcome-file>frontpage</welcome-file>
The servlet sets gets two ressources, a header file containing the < nav> and a footer containing the < footer>
request.setAttribute("header1", sc.getResource("/includes/nav.jsp").toString());
request.setAttribute("footer", sc.getResource("/includes/footer.jsp").toString());
And forwards to the index.jsp page
getServletContext().getRequestDispatcher("/WEB-INF/jsp/index.jsp").forward(request, response);
My question is.
When i get the ressource (footer.jsp), how can i in the footer.jsp dynamically import / include images?
I tried the following
<img src="${pageContext.request.contextPath}/images/picture1.png" alt="picture1"/>
But the expression ${pageContext.request.contextPath} gets treated as a string instead of a command, and does not get the context path.
I suspect its because the content of the footer.jsp is fetched in this manner and their for the context path isint actually ever requested within the footer.jsp.
But how do i solve this?
add <%# page isELIgnored="false" %> in top of your JSP page, to enable expression language.
and to include a JSP page with other use <jsp:include like:
<jsp:include page="/includes/nav.jsp"/>
<jsp:include page="/includes/footer.jsp"/>
This is not the way to include stuff. Use jsp:include action to include the header/footer. If for some reason you really want to do it in the servlet, see this post. As long as you just grab a resource like you do, you're reading the file like any text, there is no JSP compilation/evaluation.

Is there any difference between a JSP file and a JSP page?

I was reading the JSP Specification 2.1, the chapters about the JSP include directive and JSP include tag, a lot of places talk about the "JSP file" and "JSP page" seperately, such like:
Is there any difference between them?
Usually, there is no difference when we speak about jsp file or jsp page but a good observation from LuiggiMendoza is:
JSP file is the physical file stored in your hard drive while the JSP
page is the result of evaluating the JSP file from an application
server.
But there is a difference when using directives:
<jsp:include page="page.html" /> and also <%#include file="page.html"%>.
You can find an interesting post about it:
What is the difference between <jsp:include page = ... > and <%# include file = ... >?
And a nice explanation here:
<%# include file="filename" %> is the JSP include directive. At JSP
page translation time, the content of the file given in the include
directive is ‘pasted’ as it is, in the place where the JSP include
directive is used. Then the source JSP page is converted into a java
servlet class. The included file can be a static resource or a JSP
page. Generally JSP include directive is used to include header
banners and footers. The JSP compilation procedure is that, the source
JSP page gets compiled only if that page has changed. If there is a
change in the included JSP file, the source JSP file will not be
compiled and therefore the modification will not get reflected in the
output.
< jsp:include page="relativeURL" /> is the JSP include action element.
The jsp:include action element is like a function call. At runtime,
the included file will be ‘executed’ and the result content will be
included with the soure JSP page. When the included JSP page is
called, both the request and response objects are passed as
parameters. If there is a need to pass additional parameters, then
jsp:param element can be used. If the resource is static, its content
is inserted into the calling JSP file, since there is no processing
needed.
JSP page refers to a "top-level JSP file", which, as defined in JSP.1.1.8:
invoked directly by the client or dynamically included by another page or servlet
While JSP file may refer to a file which, for example, gets statically included.
To illustrate your quote, consider following directory structure:
dir/
file1.jsp
file2.jsp
file2.jsp
index.jsp
Let's say you have <%#include file="dir/file1.jsp" %> in your index.jsp. If you put <%#include file="file2.jsp" %> in dir/file1.jsp, it will include dir/file2.jsp, while if you put <jsp:include page="file2.jsp" />, it will include file2.jsp next to index.jsp.
Single JSP page may be built from several JSP files.
So JSP page is not the same as JSP file.
I believe following is what that means -
JSP file - the actual .jsp file, file as in the filesystem.
JSP page - the result of compilation of the .jsp file, that's currently serving the request
Please also check this answer here - https://stackoverflow.com/a/14763794/738746.
The include directive:
<%# include file="header.html" %>
Static: adds the content from the value of the file attribute to the
current page at translation time. The directive was originally
intended for static layout templates, like HTML headers.
The <jsp:include> standard action
<jsp:include page="header.jsp" />
Dynamic: adds the content from the value of the page attribute to the
current page at request time. Was intended more for dynamic content
coming from JSPs.

Include a View in Spring MVC

In my JSP-Template I want to include another JSP-Template, but I don't want to include it by it's path but by it's view name
Not:
<jsp:include page="/WEB-INF/jsp/include/header.jsp"/>
But:
<xxx:yyyyyyyyy page="include/header" />
Is that possble?
You can use TagFiles for that. Tag Files contain only fragments of a JSP page and can be parametrized. They have the file ending *.tag and are most commonly stored at WEB-INF/Tags.
See also:
http://docs.oracle.com/javaee/1.4/tutorial/doc/JSPTags5.html
So in your case create a file /WEB-INF/tags/header.tag and add the following to your JSP:
<%# taglib tagdir="/WEB-INF/tags" prefix="h" %>
...
<h:header/>
From your problem statement, I understand that you are trying to render a view which is a combination of multiple views, Apache Tiles is package that lets you do exactly that pretty easily. It integrates well with spring as well. Here is a simple tutorial.

How to use JSP/JSTL to create a CSV file

I have created a jsp file, with a simple table on it.
I would like to create another jsp file that users can open in Excel or save as an xls.
This is my entire jsp file, this creates a csv file which opens in Excel when a link is clicked:
<%# page contentType="text/html;charset=windows-1252"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="fmt"uri="http://java.sun.com/jsp/jstl/fmt" %>
<% response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition","attachment; filename=" + "online-dashboard.csv" ); %>
<jsp:useBean id="ReportInfo" class="com.reports.ReportLister" scope="request" />
${ReportInfo.reportType},M,W,Other
<c:forEach var="rrow" items="${ReportInfo.list}" varStatus="rowCounter">
${rrow.subjectCode},${rrow.MCount},${rrow.WCount},${rrow.OCount}
</c:forEach>
Totals,${ReportInfo.totalMSections},${ReportInfo.totalWSections},${ReportInfo.totalOSections}
When I open it in Excel, each row is separated by 2 lines.
Is there an easy way to create an excel file this way?
Is there an easy way to add some formatting ( like bold text for the column headers )?
A better way would be Spring and its JExcelView.
An easy way is to use the fact that Excel can understand HTML. So simply format your data as an HTML Table and send it as an XLS file. Something like
<table>
<c:forEach var="rrow" items="${ReportInfo.list}" varStatus="rowCounter">
<tr><td><b>${rrow.subjectCode}</b></td>
<td>${rrow.MCount}</td>
<td>${rrow.WCount}</td>
<td>${rrow.OCount}</td></tr>
</c:forEach>
</table>
The reason you're getting empty lines is that JSP is rendering empty lines inside your loop. You could eliminate them by packing your loop into one line:
<c:forEach var="rrow" items="${ReportInfo.list}" varStatus="rowCounter">${rrow.subjectCode},${rrow.MCount},${rrow.WCount},${rrow.OCount}</c:forEach>
Or you could add a servlet filter that would strip empty lines from the response.
However, if you want to add special formatting, I believe that goes beyond the comma-separated values format, and you'd need to generate excel native files as suggested by others.
EDIT: Instead of packing your loop into one line, try adding the following directive to your page:
<%#page trimDirectiveWhitespaces="true"%>
In order to create a .xls file, you'll need something heavier-duty than JSTL. Apache POI and JExcelApi are two open-source libraries for generating native Excel format files. POI can generate both .xls and .xlsx; I don't have experience with JExcelApi, but it appears to only support .xls.
As duffymo alluded to, Spring has an AbstractExcelView which you can extend and use with either library. If you're not using Spring, though, you can still use one of the libraries to generate a Workbook object and write its contents to the OutputStream of a ServletResponse. They will also let you format your data in various ways (including bold text) and even create comments and other Excel elements.
For a .xls file you'll want to set the content-type to application/vnd.ms-excel, and for .xlsx application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.
JSP is not entirely the right tool for this. Use a servlet class. To save some bytes in Stackoverflow's database, here's just a link to an answer I posted before on the subject: Export to excel using JSP.
That said, I have a few comments on your code and the other answers:
Do not use XLS content type when returning CSV. This will lead to warnings during opening the file. Use the CSV content type: text/csv. Excel perfectly understands this.
Do not render HTML along a wrong content type (the one indicating a XLS(X) file). You're then basically fooling Excel. Since Excel version 2007, it will display warnings about that.

Categories

Resources