Can a JSP template be used from within Java? - java

I'm pretty new to JSP. So far it seems that the flow of processing is very much Java runs first, then populates a JSP template.
I am wondering if there is a way from within Java to utilize a JSP template. What I mean is, imagine I had a simple "SimpleDiv.jsp" template on classpath like this:
<div id="${id}" class="${class}">
${content}
</div>
And then from within an arbitrary Java file (perhaps not even running on a servlet), I could do something like this:
private String getDivHtml( id, html ) {
Template simpleDiv = TemplateLoader.load("SimpleDiv.jsp");
simpleDiv.set("id", id);
simpleDiv.set("class", Whatever.CLASS_NAME);
simpleDiv.set("content", html);
return simpleDiv.toString();
}
This is a pretty simplistic example so don't get caught up on the details of that. Main question is -- can I pull in a JSP template in Java and cause it to generate HTML inline?

Freemarker and Velocity are very popular for generating content from templates, you might try one of them. Since JSPs are implemented as servlets (and the JSP spec defines them as webcomponents) they are tied to the servlet container.

There's no simple way to accomplish this using plain JSP. There are related Q/As in the site explaining how to do it:
What is the best way to create JSP layout template?
JSP tricks to make templating easier?
Another option using plain JSP would be using external frameworks to accomplish the task like Apache Tiles and SiteMesh (mentioned here: JSP template implementation (Composite View Pattern)).
If you can, upgrade to Facelets, the current view technology since Java EE 6. This technology already provides built-in template system as explained here and here.

Consider this subset of JSP which has no dependency on servlet:
http://jstp.sourceforge.net/manual.html

Jsp is a inner servelt, a java class, normally, it outputs HTML when it finishes executing.
Maybe you should just treat the jsp file as a pure string, the "simpeDiv.set" method just do replacing works: replace ${key} to ${value}

Related

Printing HTML using servlet vs using a jsp. What are their Advantages?

What are the advantages of printing a HTML page using a servlet instead of using a jsp
<pre>
out.println("<html><body>");
out.println("<h1>My HTML Body</h1>");
out.println("</html></body>");
</pre>
writing html with servlets is very cumbersome , that's why jsp was developed . internally though jsp are transformed into a servlet by the container so we don't have to write all those out.println(...some html); our self .
jsp also allows us to seperate out logic from our views.
When you have a lot of Java code, for example getting data from database, security, validation, etc, you may put this logic into servlet. For printing just HTML you may use JSP, or just static HTML page. It depends on your needs.

ESAPI implementation for spring form tags

How can we implement ESAPI output encoding in an application using java and spring-mvc.
Read many posts and saw this:
<%# page import="org.owasp.esapi.*" %>
<input type="hidden" name="hidden" value="<%out.print(ESAPI.encoder().encodeForHTML(content));%>"/>
But, in my application all the jsps use spring form tags like the following,
<td>Number:
<form:input path="someNo" size="20" maxlength="18" id="firstfield" onkeypress="return PressAButton('submithidden');"/></td>
How can I have ESAPI implementation for above code? is there any other way of implementing output encoding like creating a filter or something? Any suggestions are greatly appreciated!
After researching spring tags a bit, it appears that the data-binding happens in framework code thus preventing you from applying any escaping in the jsp.
One, semi-quick win could be defaulting all output to escape HTML. Add this entry in web.xml:
<context-param>
<param-name>defaultHtmlEscape</param-name>
<param-value>true</param-value>
</context-param>
The only problem here is that output-escaping is a BIG pain... the rules for html escaping are different when your value is going to be passed as data to an HTML attribute or a Javascript function. And there could be some parts of your application where you DO NOT want to html escape, but you should be able to override those with the form tag attribute htmlEscape="false" when you need to.
What you need is to be able to hook the part of Spring tags where it is binding the HTML to the form, but you need to be able to do it so you can escape based on where its being placed. Escaping rules are different for an HTMLAttribute as opposed to plain HTML and if the value is going to be passed as data to a javascript function. So Spring's solution only defends one category of attack.
These are the only ways out I see, all of them will require work:
Use JSTL tags instead of Spring tags so you can write your variables with ${thisSyntax} and wrap them in esapi tags like this:
<c:out value="<esapi:encodeForHTML>${variable}</esapi:encodeForHTML>"/>
Follow a solution like what #A. Paul put forward, where you do your context escaping back on the controller side. I'm aware you feel that this isn't an option, but the next solution I'm putting forward is untested.
Implement your own tag library that subclasses [org.springframework.web.servlet.tags.form.InputTag][1], specifically the method writeValue. While esapi prevents alot, I would recommend looking at owasp's new Encoder project to show you exactly how tricky output encoding is. Ideally your tag library will allow you to utilize either esapi's Encoder or this new API.
Just a thought not sure if this is what you are looking for.
Can you use the below code in Java and change the data in the bean itself and then send in the user interface.
if ( ESAPI.securityConfiguration().getLogEncodingRequired() ) {
data = ESAPI.encoder().encodeForHTML(message);
}
You can check the below url.
http://www.jtmelton.com/tag/esapi/

Including a page using spring

I'm using spring to display a jsp page. That's fine. Now I'd like to include another page in it. I know I can use the <jsp:include> tag in my page however I'd like to use a controller to pass some logic to the page which is to be included. Is it possible please?
Thanks,
Krt_Malta
You might want to checkout a template engine like Freemarker or Velocity. Here's a description of how Spring integrates with view technologies.
Your controller can add objects to the Model and Spring will add them to the HTTPRequest as attributes, is that what you mean? Including a jsp fragment doesn't affect that, your jsp fragment can access the request attributes. Otherwise it's unclear to me what you mean by "passing some logic to the page".
Look into JSTL (Jsp Standard Tag Library).
You can implement conditional logic in your JSP using the JSTL <c:if> or <c:choose> tags. Then, instead of splitting up the logic into multiple files and using <jsp:include> to include the logic you want, you can build all the logic into your page and the controller can set request (or other scope) attributes to turn on the logic you desire.
For example:
<c:if test="${Order66}"
&ltc:forEach items="${JediMembership}" var="jedi">
kill ${jedi}
&lt/c:forEach>
</c:if>
<c:if test="${Order67}"
two large pizza, extra cheese.
</c:if>
The controller then set "Order66" and / or "Order67" in the request (or any other scope).

How to JSP display multiple page with one layout (Example index.jsp?page=about display about.jsp)

I new in JSP, i have a problem with JSP
in php i use
$page=$_GET["page"]
for display multiple page for one layout it mean i have index , it display layout and when i click on menu go to about us the index url = index.jsp?page=about
in PHP when i declare $page above and next step i do
Switch($page){
case 1:about
include 'aboutus.php'
case 2:news
include 'news.php'
}
How can i do it ?
How jsp can do the same way php to display multiple page in 1 layout
Use jsp:include.
<jsp:include page="/WEB-INF/${param.page}.jsp" />
And pass ?page=news or ?page=about, etc as parameter. The ${param.page} prints the outcome of request.getParameter("page"). You can prevent direct access to JSP files (by entering URL in browser address bar) by placing JSP files in /WEB-INF folder.
See also:
Basic JSP/Servlet tutorials
Hidden features of JSP/Servlet
How to avoid Java code in JSP
nowadays you use "templates" of Java Server Faces (JSF) for this approach. When you use JSP, you actually don't use the same concept as in PHP. You'd better use the MVC concept. But to answer your question, you could probably achieve this with the include tag http://java.sun.com/products/jsp/tags/11/syntaxref1112.html and control it with JSTL:
http://www.java2s.com/Code/Java/JSTL/JSTLiftag.htm

Is it possible to extract SCRIPT tags using SiteMesh?

I have custom JSP tags that generate some HTML content, along with some javascript functions that get called by this HTML code. In the current implementation, the SCRIPT tags are created just above the HTML code.
To avoid modifying the existing code base, I want to pull up these scripts inside the HEAD section of the page using SiteMesh or some other decorator tool.
I know SiteMesh can extract content from <content tag="..."> elements, but I was wondering if it was possible also with other tags, such as SCRIPT.
Is this possible with SiteMesh, or know of any tools that could allow me to do that?
Thank you!
SiteMesh's HTMLPageParser is extensible, so you can add your own custom rule to extract <script> elements by extending HTMLPageParser and configuring SiteMesh to use your class instead of HTMLPageParser, something like this:
import com.opensymphony.module.sitemesh.parser.HTMLPageParser;
public CustomPageParser extends HTMLPageParser {
protected void addUserDefinedRules(State html, PageBuilder page) {
super.addUserDefinedRules(html, page);
html.addRule(new ScriptExtractingRule(page));
}
}
I imagine your ScriptExtractingRule would be modeled after the standard SiteMesh ContentBlockExtractingRule, storing the content in the page context so your decorator can access the blocks as if they were <content> blocks.

Categories

Resources