I have a unique problem to solve. I need to dynamically create HTML based reports using a standard template. The contents of the report are created by a Java program so it makes sense to create a new class which uses JSP* to make a static HTML output file.
Here is the gist:
MyObject me = new MyObject();
me.process();
MyJSP jsp = new MyJSP(me);
File output = jsp.renderFrom("templateFile.jsp");
And output is a static, self contained HTML file which I can open in IE/Firefox and see the report.
What pattern/framework should I follow to allow me to best accomplish this?
Some notes: This is actually not a webapp. I am creating HTML based reports, but this won't be used as a webapp. I would also rather not use String.format(".. giant template string .. ", args) as this is very clumsy. I would much rather have a template file like this:
<html>
<head><title>First JSP</title></head>
<body>
<%
double num = Math.random();
if (num > 0.95) {
%>
<h2>You'll have a luck day!</h2><p>(<%= num %>)</p>
<%
} else {
%>
<h2>Well, life goes on ... </h2><p>(<%= num %>)</p>
<%
}
%>
<h3>Try Again</h3>
</body>
</html>
Where the "dynamic" aspects of the template can use MyObject properties, etc.
Lastly, I plan to use Java 7 for this due to some issues I am having with Java 8. If there is some better way to do this in Java 8, let me know...
*After some negative comments against JSP, perhaps JSP is not the right option. Some other library is fine too, as long as it works with Java.
Use a template engine for this!
I would recommend Freemarker, Velocity or StringTemplate. Just google it. Any of these engines will cover your needs.
Related
I have a jsp code, where I fetch some JSON data from JAVA Class file. [Basically openfire users]
Now I get the data successfully, but I want to show this data in HTML table format.
How do I Do this ?
My JSP Code :
<%# page language="java" import="prov.*, java.util.*, java.io.*,java.text.*" contentType="text/html"%>
<%# page errorPage="error.jsp" %>
<%
Openfire tc = new Openfire();
tc.getUsers("192.168.50.218","epvFjHq5RHA614C7");
out.println("Data Is As Below : " + tc.getUsers("192.168.50.218","epvFjHq5RHA614C7"));
%>
And I get Response from the JAVA Class method like this :
[{"username":"abcd","name":"","properties":null},{"username":"admin","email":"admin#example.com","name":"Administrator","properties":null},{"username":"bizdd456d454mnc","email":"bizMNC#bizrtc.com","name":"bidzMNC","properties":null},{"username":"bizddd454mnc","email":"bizMNC#bizrtc.com","name":"bidzMNC","properties":null},{"username":"bizmnc","email":"admin#example.com","name":"511515151515151","properties":{"property":[{"#key":"console.order","#value":"session-summary=1"},{"#key":"console.rows_per_page","#value":"user-summary=8"}]}},{"username":"dhaval","email":"dhaval#bizrtc.com","name":"dhaval","properties":null},{"username":"keyur","email":"keyur#bizrtc.com","name":"keyur","properties":null},{"username":"minz","email":"bizMNC#bizrtc.com","name":"bidzMNC","properties":null},{"username":"patel","email":"rau#example.com","name":"patelbhai","properties":{"property":[{"#key":"console.order","#value":"session-summary=1"},{"#key":"console.rows_per_page","#value":"user-summary=8"}]}},{"username":"rajan","email":"rajan#bizrtc.com","name":"rajan","properties":null},{"username":"+username+","email":"+email+","name":"+name+","properties":null}]
As I am very new to JAVA and JSP I don't know how to parse this data to HTML Table.
So Please help.
You can see here how to do it. You can populate it in Javasript or jQuery, but it is better to use JSTL and not just call java code inside JSPs.
I would suggest you use mustache als template engine.
It allows you to use a HTML fragment as template (store it as resource) where double curly brackets (hence the name Mustache) denote the insertion points.
The full documentation of the Mustache syntax is here and a Java example here. Let us know how it is going.
Excuse my lack of knowledge in many fundamental areas, but I am just learning how to create applets in java and how to allow interaction between the applet and the web page (javascript).
At the moment I have an applet with an init() and method1(). method1() just returns a string.
The applet is loaded on a web page and in javascript I literally reference the function:
<html>
<head>
<title>Testing Applet</title>
<script>
function hello() {
result = document.wplayer.method1();
alert(result);
}
</script>
</head>
<body>
<applet code = "player.Player" name = "wplayer" archive = "player.jar" width = "600" height = "400">
</applet>
<button onClick="hello();">Interact with app</button>
method1() just returns a string ("blah blah blah");
My question is, is this a safe way to do it and is it the most compatible?
Thanks!
Nick
is this a safe way to do it and is it the most compatible?
It's only as safe as the client is safe, so you should assume that the client may edit/forge/hack, etc.
If you meant safe in the other sense - not causing conflict - use an Object as your namespace in JavaScript and have everything kept within that Object. This way you are much less likely to have trouble with any conflicting variable names elsewhere on a page. You may also want to use unobtrusive JavaScript, to keep your script and HTML independent of each other.
Currently, your function hello is in the global namespace, and creates a global result, which could cause conflicts.
Assuming that the client has an up-to-date copy of Java and plugins enabled, you only really need to worry about the same compatibility issues as when writing any normal JavaScript for any browser.
I'm pretty new to Java and I apologize in advance if I'm wording this incorrectly. I've got a small code snippet that has multiple opening and closing delimiters because I've got some HTML mixed with JSP. Without the HTML this can be done in just a few lines of code but I need the HTML to render and it leads to almost double the lines of code. I'm wondering if there is a better way to do this as opposed to having so many opening and closing delimiters. I know I can use a templating library but I'm trying to stay away from that and would like if at all possible to do this inside a JSP (not a separate class). Thanks for the help!
<%
try {
List<Page> children = properties.getPath("getChild", "");
%>
<ul>
<%
for (Page children : e) {
if (children != null) {
%>
<li>Show a link</li>
<%
}//end if statement
}//end for loop
%>
<li>Another link goes here</li>
</ul>
<%
} catch (NullPointerException e){
%>
//show some content here
<% } %>
I think that this kind of problem can really be solved by using templating libraries or the included view convention for a framework.
These libraries were created to solve these kinds of problems and to organize the view as a whole. It will not only clear up the clutter in your view, it will also adhere to the MVC pattern.
In struts, for example, we will do something like this:
<s:textfield name="myParameter" />
and this:
<html:link page="/linkoutput.jsp" paramId="id" paramName="name"/>
For more reasons why you should be using templating or frameworks visit this question. As what Dave Newton said:
Attempting to do it all in jsp is precisely the wrong approach.
Hope this clears it up.
Use JSTL instead of all that Java code you have in your JSP. You can read about JSTL here - http://docs.oracle.com/javaee/5/tutorial/doc/bnakc.html
Never catch NPE just to catch NPE.
Consider using JSTL http://jstl.java.net/getStarted.html It provides plenty of tags for iteration and so on.
You'd be much better of using something like JSF. Just as JSP, this is also included in Java EE.
Is it possible to write a little Javaa program which parses a xml file from my web hosting site and updates this file? Or is there a better alternative to do so? I have to update the file every 10 min with about 10 lines of code each, so I don't want to write it out every time.
You can write little java program. BTW you can write a bigger one two :).
You can write program using any language you want. Including Java.
The program written in any language can parse XML.
Well, now we arrived to the problem. What do you mean when you say that you wish to parse XML from the web site? Does your web site provides URL that allows to download the XML? In this case you can download it (e.g. using HTTP GET method) and parse.
The next problem is how to update the XML on the site. You have to provide such functionality on site itself (e.g. implement service that is able to receive the XML and store it. For example via HTTP GET.
Once you are done you can write truly little java program that downloads the file using HTTP GET, parses it, creates new one and the sends it back to the site using HTTP POST.
I would investigate running this code on your server. What is the update? Does it use data not on your server? You can do this easily in Java but more detail is needed for a better answer.
OK, your idea is fine if your web hosting lets you do http PUT you can get the file using GET, modify it, e.g. using the DOM, and PUT it back. You might prefer to do more server side scripting and write the update at that end, it lets you use relational databases instead of flat files for example. In this case, writing a server side script to accept a POST as the other answer suggested is a good idea.
I've put a little example for you here: http://jcable.users.sourceforge.net/scores.php
There are three files on this website:
scores - a text file that gets updated.
scores.php - a script that shows the current score
add.php - a script that updates the current score.
scores.php looks like this:
<html>
<body>
The current score is <?php readfile("scores"); ?>
</body>
</html>
add.php looks like this:
<?php
if(isset($_POST["score"])) {
$fh = fopen("scores", 'w') or die("can't open file");
fwrite($fh, $_POST["score"]);
fclose($fh);
}
else
{
?>
<HTML>
<BODY>
<FORM action="add.php" method="POST">
New Score: <INPUT type="text" name="score"/>
</FORM>
</BODY>
</HTML>
<?php
}
?>
if you get add.php it will present you the form. But if your program calls it as a post it won't bother. Hope this gives you some ideas - its the simplest possible web app I can think of that has persistent server side data. You can add complexity - xml or json, etc., but the principles are there.
I am trying to use iText for pdf file generation and I have a question regarding the generation. I would like to serve the PDF to the browser so that the browser displays it, without actually creating a file.
What would be the best approach to achieve this?
One limitation is that I would need to use it from a JSP page - something that would circumvent the "getOutputStream has already been called once" error is what I am looking for.
I would like to serve the PDF to the browser so that the browser displays it, without actually creating a file.
Just pass responsegetOutputStream() instead of new FileOutputStream to PdfWriter.
PdfWriter pdfWriter = PdfWriter.getInstance(document, response.getOutputStream());
// ...
One limitation is that I would need to use it from a JSP page - something that would circumvent the "getOutputStream has already been called once" error is what I am looking for.
Just remove any whitespace outside <% %> in JSP, including newlines. They are implicitly sent to the response by the response writer.
I.e. do NOT
<% page import="foo" %>
<% page import="bar" %>
<%
for (int i = 0; i < 1000; i++) {
out.println("I should not use scriptlets.");
}
%>
(newline here)
but more so
<% page import="foo" %><% page import="bar" %><%
for (int i = 0; i < 1000; i++) {
out.println("I should use servlets.");
}
%>
Or better, don't put Java code in JSP files. JSP files are designed to present template text like HTML, not to do entirely different things. Do that in a normal Java class like a servlet.
Write it to the servlet output stream, remembering to set the encoding to the correct value
This http://onjava.com/onjava/2003/06/18/dynamic_files.html explains how to do it