Best way to insert headers while writing file in java - java

I have scenario where i have to insert header manually which looks like below
Header:
<%# package="test"
imports="
/* Many imports i know the list*/
"
%>
I have achieved this by string concatenation like sample below:
String header="<%# jet package"+"="+"\"Testmodule\"" +"\n"+"imports"+"="+"\"java.io.File"+"\n"+
"utils.ProjectUtils"+"\n"
+"\""+" parallel="+"\"true\""+"%>"+"\n";
Note: I have more than 10 imports.This is just sample.
since the text is more and requires also proper alignment(like each import on next line and also escape "") when i am inserting header into other file, I want to know if there are any alternatives to do this in efficient way in java.

I assume this is a JSP Question
If it is, then use a static include (A static include is resolved at compile time)
<%#include file="includes/header.jsp" %>
or for for dynamic inclusion:
<jsp:include page="..." />

Related

The code of method ... is exceeding the 65535 bytes limit

Inside a jsp I have a small header :
<%# page import="java.util.*"%>
<% HttpSession CurrentSession =
request.getSession();
...
%>
...and a big html
<html>
...
</html>
If I try to read it as is I get an error of "...is exceeding the 65535 bytes limit".I have to break it up.Since I am new to java I cannot figure it out how to do it.Could you please indicate me the way?
The JSP is converted into a normal Servlet java source, and some generated method is too large, as there is a 64 KB limit (on the byte code) on method lengths.
If possible change static includes (really embedding an other JSP source) with dynamic includes.
The solution (and probably good style) is too introduce a couple of methods into which pieces of the general code is moved. For instance to generate a HTML table row with <tr>:
<%#
void tableRow(String... cellValues) {
%><tr><%
for (String cellValue : cellValues) {
%> <td><%= cellValue %></td>
<%
}
%></tr>
<%
}
%>
...
<%
tableRow("one", "unu", "un");
tableRow("two", "du", "deux");
tableRow("three", "tri", "trois");
%>
P.S.
The above method is too small scale to save much, taking a large piece and create a method
like createResultsTable is more effective.
JSPs get compiled into servlet code, which are then compiled into actual java .class files. JSP code will be put into one big doGet() method, and if your JSP file is really big, it will hit the method size limit of 65535. The limit is coming from JVM specification ("The value of the code_length item must be less than 65536").
You should split the file into several files. I wouldn't split it into different methods as proposed in this thread, since it can make the code logic even more complex in this case, but do a jsp:include for the HTML part(s) like proposed by McDowell.
The <jsp:include page="foo.html" %> standard action can be used to include content at runtime - see some random documentation.

Storing html file in a String in java

I am sending emails using amazon java sdk. I have to send html template as mail. I have written a program for this and it is working fine. But now I am storing the whole html code in a single String. But whenever i need to edit the template, I have to edit the program (I mean the String variable). And also I have to take care the special characters like " \ ...etc in that html code. Please suggest me an elegant way to solve this issue.
Use a template engine for that and store your template externally either in class path or on a file system. Here is a question that may help you selecting one: https://stackoverflow.com/questions/2381619/best-template-engine-in-java
Use Apache Common Lang api's StringEscapeUtils#escapeHtml, It escapes the characters in a String using HTML entities and return a new escaped String, null if null string input.
For example:
"US" & "UK"
becomes:
"US" & "UK".
Check the Apache Velocity Project. You can create template for several things. From it's user-guide page
Velocity can be used to generate web pages, SQL, PostScript and other output from templates. It
can be used either as a standalone utility for generating source code and reports, or as an
integrated component of other systems.
You can use a VTL(Velocity Template Language) . A example from above link
<HTML>
<BODY>
Hello $customer.Name!
<table>
#foreach( $mud in $mudsOnSpecial )
#if ( $customer.hasPurchased($mud) )
<tr>
<td>
$flogger.getPromo( $mud )
</td>
</tr>
#end
#end
</table>
Better and easiest way is reading the html file line by line using simple file reading operation and append this each line to a single String. And also I found this solution (also a better one, if you are ready to add one more library file to your project) from SO.

JSP exception, "quote symbol expected"

<%# page import="java.util.*" %>
<html>
<body>
<h1 align="center">blablalblalblab</h1>
<p>
<%
List styles = (List)request.getAttribute("styles");
Iterator it = styles.iterator();
while(it.hasNext()) {
out.print("<br>try: " + it.next());
}
%>
</p>
</body>
</html>
after executing my servlet request i'm getting error
org.apache.jasper.JasperException: /result.jsp (line: 1, column: 18) quote symbol expected
org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:42)
can't find any quotes that are not on right place.
Make sure all your quotes are straight quotes, not curvy ones.
Don't use Java in JSPs, please. That's what the standard tag library is for.
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<body>
<h1 align="center">blablalblalblab</h1>
<p>
<c:forEach items="${styles}" var="style">
<br>try: ${style}
</c:forEach>
</p>
</body>
</html>
In more detail:
Embedding Java code in a JSP makes the page difficult to read (JSP is a tag-oriented language), difficult to maintain, and difficult to debug.
The standard tag libraries are already debugged, have plentiful documentation and examples, and probably already Do What You Want To Do.
If you truly have some logic that needs to be performed in Java and no pre-existing tags exist, you can either a) put the logic in a bean and call it via JSTL or b) write your own tag using tagfiles.
Why is Java code better in a bean or tag library than in a JSP?
Testing is a big factor: beans and tag libraries can be tested
outside of a running servlet environment with ease.
Tag libraries are reusable and significantly cleaner than JSP includes.
I guess you have copy pasted it from somewhere, make sure the double quotes are proper. I had the same issue when I copied it from a PDF, it was resolved once I corrected my double quotes.
Your JSP works just fine with Tomcat 6. So, it's probably either some include-related issue or some previously compiled classes are not getting recompiled.
Try to clean up your Tomcat work directory and try again.
Check " if you copied it from somewhere. I had the same error because of ".
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%#page isELIgnored=”false” %>
double quotes around the false are the wrong ones. Change it to " and it will work.
While I agree with Scott A's admonition to use JSTL instead of putting Java directly into the JSP the question deserves being explored a little further. I just encountered this myself for the first time and had to dig a bit ot answer it.
Technically the error means what it says. You're missing some quotes somewhere. The simplest would be something like in your h1 tag if it read:
<h1 align=center>
instead of what you have.
<h1 align="center">
Obviously there is nothing in the code snippet that you pasted which is missing quotes so I would explore a couple of things.
First, what does the output of your it.next() look like? Since you're pulling in a list called styles I wonder if something in there is making jasper think it's a style tag instead of text you are trying to render.
Second, I would explore Pradeep's answer and see what if there is some subtle issue pasting that was resolved when you pasted it here on stackoverflow. Specifically I would look for 'smart quotes' IE many text editors (including outlook and most of office) like to use different quotes on the front and back of quoted text.
IE
'this is quoted text'
becomes
`this is quoted text'
which can be difficult to notice.

How to write trivial JSP that just returns static XML page

I'm trying to write a trivial JSP that returns the contents of a static xml file. I need to run this in tomcat. Eventually, this will be more dynamic, but at first, I just want to return an xml file. Can anyone point me to a demo for such a trivial beast, I'm trying to learn what are the minimum chunks I need to create the web app and install in tomcat.
Mucho appreciato,
pawpaw17
Following this document is always a good start.
But you may have issues.
First, it's basically trivial to do something like:
http://example.com/app/mydynamicxml.jsp
that returns an XML blob. Just paste the XML in to that file.
But it won't have an XML content type. You can fix that by adding directives to the JSP:
<%#page contentType="application/xml" %>
However, that brings on MORE problems.
Specifically, an XML file CAN NOT start with white space. It MUST start with <?.
That directive will very likely insert a blank line in to you XML file.
So, what you really want is:
<%#page contentType="application/xml" %><?xml version...
Finally, there IS a JSPX version of JSP, which uses an XML syntax, and avoids all of those white space issues. There's also a directive to Tomcat that can eliminate the white space issue. But, out the gate, this is the fastest, "obvious" tact to take.
The main thing would be to specify the content type as <%# page contentType="text/xml" %>
<%-- Set the content type
--%><%# page contentType="text/xml" %><%--
--%><?xml version="1.0" encoding="UTF-8"?>
<root><entry key="key1" value="value1" /><entry key="key2" /></root>
Check out the article on Sun site
Tried adding a trimDirectiveWhitespaces="true" page directive, but that wasn't supported on my server.
The solution was simply to remove any newlines after any page directives.

Using a jsp fmt tag in another tag

I'd like to be able to include the return value of a fmt tag in another tag:
<local:roundedBox boxTitle="<fmt:message key="somekey"/>">
content
</roundedBox>
I've run into this problem multiple times and it just seems like a stupid limitation of jsp. Is there a simple way around this?
Use an intermediate variable to store the result like this (code not tested)
<fmt:message key="somekey" var="formattedvarname" />
<local:roundedBox boxTitle="${formattedvarname}">
content
</roundedBox>

Categories