Formatting HTML in a JSP - java

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.

Related

Can I create methods in JSPs?

Can I write methods in JSPs? (Java Server Pages)
I tried writing a method within the body of the JSP, but my IDE doesn't seem to like it.
JSP can only show information to user, if you want to do some elaboration you have to re-call a servlet that to that for you.
Analize and try using this:
Everything in your jsp.
But i recommend you that if your a gonna use methods, use classes instead. They are safer and loads quite faster when calling them.
<%
//Your main logic
out.print(myMethod());
%>
<html>
your client side content
</html>
<%!
public String myMethod(){
return "Method called successfully";
}
%>

Generate Static HTML Pages using Java

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.

script inside scriptlet - bad practice how to avoid

i am working on a legacy project where i have seen below piece of code.
I know it is a bad practice to use script inside scriptlet.
Regarding this , i have few confusion in mind.
what i believe is scriptlet is executed before page loads, so if below if condition is true then ShowBookReference() function call is a part of an Html page, but my question is when page is rendered should this function call happens or not ?
<% if (refLinkTerm != null) { %>
<script Language="javascript">
ShowBookReference('<%=sub2ndNavMenu%>', '<%=refLinkTerm%>', <%=String.valueOf(searchType)%>, <%=String.valueOf(codeType)%>)
</script>
<%}%>
How to avoid this kind of practice ?
Please share your thoughts.
Use an MVC framework such as Spring MVC. In these frameworks, you fill in a Java object (or map of objects) with the values for the page to display, and then the page just fills in placeholders with those values.
In terms of JSP, Its usual to use scriptlets to assign value to JS.
But as you've mentioned that it runs before the page load, so it's good to run the function on window.onload.
<script type="text/javascript">
window.onload = function() {
ShowBookReference('<%=sub2ndNavMenu%>', '<%=refLinkTerm%>', <%=String.valueOf(searchType)%>, <%=String.valueOf(codeType)%>)
}
</script>
In case you're referring some DOM elements inside ShowBookReference function, it may not be available so run it on page load.
Else you can use UI frameworks like JSF which provides you tags to bind java values to UI easily.

Including a static content using RequestDispatcher from JSP is not working on GAE Java SDK

I have a web-app running on the App Engine Java SDK 1.7.2. The app has no filter and no servlets besides the defaults for serving static content and JSP.
In a JSP file, I have a single line with something like:
<% request.getRequestDispatcher( "a.html" ).include( request, response ); %>
This is throwing a java.lang.IllegalStateException: "getOutputStream has already been called".
If I change the "a.html" for a dynamic content like "a.jsp", everything works fine. The documentation says a RequestDispatcher should work for dynamic and static content.
OBS: I am still learning Servlets and everything related, but I know there are other ways to achieve what I am doing here - this is just an example, not a real world scenario. I just would like to know if this is the expected behaviour and why. Or is it just a bug?
After googling, I learned that this bug has been around for a long time. Look at
http://www.coderanch.com/t/165116/java-Web-Component-SCWCD/certification/RequestDispatcher-include-throws-IllegalStateException
Strange as it might seem, the following works.
<%#page buffer="none"%>
<%
request.getRequestDispatcher("a.html").include(request,response);
%>
Why on earth you are putting scriplets in JSP, it is a horrible way of making your JSP's maintenance nightmare. Anyways looks like your request is already being sent before you are calling this method.

How To Stop Tomcat/Java Wrapping My Output

I've got a JSP page that I want to return a fragment of HTML. The trouble is that whenever I request the JSP, something is attempting to make the HTML more valid by wrapping <html> tags around it. I don't want it to do this though as it will be used in a variety of other places.
For an example, the following JSP:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<script src="${applicationConfig.javascriptUrl}update.js" language="javascript" type="text/javascript"></script>
<p>Wibble</p>
Will result in the following HTML:
<html xmlns="http://www.w3.org/1999/xhtml"><head></head><script src="http://fisher.mycompany.com:8080/my-app/includes/js/update.js" language="javascript" type="text/javascript"></script>
<p>Wibble</p></html>
I really don't want those <html> & <head> tags there and would like to get rid of them but have no idea where this is happening to turn it off. Does anyone have any clues?
* Edit *
To give a little more information on what I am trying to achieve. This JSP will check a variety of things and form a piece of HTML. This HTML can then be included into other applications via a web service call.
Servlets can return any content type including javascript and images, not just HTML. Tomcat should not wrap jsps in extraneous tags. I put the snippet you suggested in a jsp, minus the taglib which I don't have set up, and got back exactly the HTML that I put in.
Can you tell us more about your environment? Are you using tomcat? Are you using some kind of framework?
Servlets are HTML factories. They expect to send a valid HTML page down to a browser to be rendered. You can't "get rid of it" without breaking the whole model.
Your original concept of sending a snippet that's "used in a variety of other places" is flawed. You sound like to want to set some data that might be used in other places - that's valid - but I don't see how wrapping it in markup matters.
Only the JSP should be using the marked up data. JSPs are all about display. I'd rethink what you're doing and attack how you want to share the data, not the markup.
One approach it might work,
Create HTML files as you required valid HTML,
and use servlet to returns response, servlet should read HMTL File and return
its contents as String, like XML respones from servlet
hopes thats helps

Categories