I am putting together an application and would like to apply "Custom" EL Expressions to sections on the page when it is rendered. This will help me control what parts are displayed on the page given the status of the page. The problem is that the EL Expressions are not being evaluated and treated only as String values. For example
<c:if test="${form.conditionEL}" >
<input type="submit" value="Close">
</c:if>
The value of the ${field.conditionEL} might evaluate to something like "submission.status eq 'COMPLETE'".
So, is there a way to get that string value to be interpreted within the JSP page ?
Thanks for any help in making this happen. Let me know if I missed providing any pertinent information to help resolve.
Environment: Java 8, Tomcat 9, JSP 3.0, Spring
Regards,
Mike
I would simply add the submission status to the page context which let's you simply do:
<c:if test="${submissionStatus eq 'COMPLETE'}" >
<input type="submit" value="Close">
</c:if>
Check whether EL expressions are ignored in your page tag. I've also faced the same issue and this resolved mine.
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" isELIgnored="false" %>
Let me explain my requirement. Currently we are using Scala template which has some html code and Scala attributes.
Example test.scala.html
#(hostName: String, token: String, protocol: String, supportEmail: String)
#import helper._
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<table>
<tr>
<td> </td>
<td style="color: #626262;">
<p style="font-size:14px;">
<br/>
Our app will let you access your company intranet.<br/><br/>
Your activation code is <b>#token</b><br/><br/>
If you have any questions, please contact our support team anytime.
<br/><br/>
Best regards,<br/>
The Support Team
</p>
</td>
</tr>
</table>
</body>
If you see the above code #token and #supportEmail is dynamic we are passing to Scala.
Till now looks good. The requirement changes, the customer now wants us to read the content from the database. They want to save the actual html content (table ... end of table).
So I took the code and stored it in a database column. I am able to pass this content to my view function by using #Html.
Now my new Scala view function looks like the following:
#(hostName: String, token:String, protocol: String, supportEmail: String, content: String)
#import helper._
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
#Html(content)
Bu I am not able pass #token and #supportEmail dynamically. It is treated as a plain string. After rendering it looks like the following :
Our app will let you access your company intranet, files and SaaS services from your device.
Your activation code is #token
If you have any questions, please contact our support team #supportEmail anytime.
Best regards,
The support Team
Can anyone explain me whats wrong with #Html, can I parse the dynamic content or not. If not is there any alternative.
The #Html function allows you to insert a fragment of HTML from a variable without escaping special characters like < or >. However, it works only with static HTML and unfortunately doesn't parse additional Scala code inside it.
In your case, the easiest way to achieve your requirements is to prepare the content in your controller before passing it to the view. Code in controller's method would look more or less like this:
public Result showContent() {
//fetching all your data here
content = content.replace("#token", token);
content = content.replace("#supportEmail", supportEmail);
return ok(views.html.test.render(hostName, protocol, content));
}
Basically, you aren't forced to use Twirl placeholders inside the table content. The decision how to mark replaceable parameters in the content is up to you. Just make sure that replace calls matches you patterns.
I assumed that token and supportEmail aren't used in other places of the view, hence I removed them from the header of the view.
#(hostName: String, protocol: String, content: String)
Simple solutions are usually the best solutions :)
i am learning JSTL and from tutorials point in this link
when i tried to execute that example in the page which is
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title><c:url> Tag Example</title>
</head>
<body>
TEST
</body>
</html>
i am getting following error.
but i could not understand why and what is the solution for that?
The validator is probably confused by the nested double quotes:
TEST
You can make the code cleaner by doing:
<c:url value="/jsp/index.htm" var="myUrl" />
TEST
which assigns the value of the processed URL to a var named 'myUrl' and then uses JSP Expression language to output the URL.
Change this line:
<title><c:url> Tag Example</title>
By:
<title><c:url> Tag Example</title>
Otherwise, the JSP engine will interpret this (<c:url>) as the beginning of a tag to be processed.
You need to escape your nested quotes as
TEST
Otherwise the HTML parser perceives "<c:url value=" as the href value and complains about the space in between. Alternatively, you can make use of single and double quotes as
<a href='<c:url value="/jsp/index.htm"/>'>TEST</a>
Or,
TEST
I've been told that the use of scriptlets (<%= ... %>) in my JSP pages isn't such a great idea.
Can someone with a bit more java/jsp experience please give me some pointers as to how to change this code so its more 'best practice', whatever that may be?
This JSP is actually my sitemesh main decorator page. Basically my web design has a tab strip and a submenu, and i wish to somehow highlight the current tab and show the correct submenu by looking at the current request URI.
<%# taglib uri="http://www.opensymphony.com/sitemesh/decorator" prefix="decorator" %>
<html>
<head>
<title>My Events - <decorator:title /></title>
<link href="<%= request.getContextPath() %>/assets/styles.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="tabs">
<a
<%= request.getRequestURI().contains("/events/") ? "class='selected'" : "" %>
href='<%= request.getContextPath() %>/events/Listing.action'>Events</a>
<a
<%= request.getRequestURI().contains("/people/") ? "class='selected'" : "" %>
href='<%= request.getContextPath() %>/people/Listing.action'>People</a>
</div>
<div class="submenu">
<% if(request.getRequestURI().contains("/events/")) { %>
List of Events
|New Event
<% } %>
<% if(request.getRequestURI().contains("/people/")) { %>
List of People
|New Person
<% } %>
</div>
<div class="body">
<decorator:body />
</div>
</body>
</html>
Thanks all
I think it helps more if you see with your own eyes that it can actually be done entirely without scriptlets.
Here's a 1 on 1 rewrite with help of among others JSTL (just drop jstl-1.2.jar in /WEB-INF/lib) core and functions taglib:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<html>
<head>
<title>My Events - <decorator:title /></title>
<link href="${pageContext.request.contextPath}/assets/styles.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="tabs">
<a
${fn:contains(pageContext.request.requestURI, '/events/') ? 'class="selected"' : ''}
href="${pageContext.request.contextPath}/events/Listing.action">Events</a>
<a
${fn:contains(pageContext.request.requestURI, '/people/') ? 'class="selected"' : ''}
href="${pageContext.request.contextPath}/people/Listing.action">People</a>
</div>
<div class="submenu">
<c:if test="${fn:contains(pageContext.request.requestURI, '/events/')}">
List of Events
|New Event
</c:if>
<c:if test="${fn:contains(pageContext.request.requestURI, '/people/')}">
List of People
|New Person
</c:if>
</div>
Here's a more optimized rewrite, note that I used c:set to "cache" expression results for reuse and that I use HTML <base> tag to avoid putting the context path in every link (just make all relative URL's in your webpage relative to it --without the leading slash!):
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<c:set var="isEvents" value="${fn:contains(pageContext.request.requestURI, '/events/')}" />
<c:set var="isPeople" value="${fn:contains(pageContext.request.requestURI, '/people/')}" />
<html>
<head>
<title>My Events - <decorator:title /></title>
<base href="${pageContext.request.contextPath}">
<link href="assets/styles.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="tabs">
<a ${isEvents ? 'class="selected"' : ''} href="events/Listing.action">Events</a>
<a ${isPeople ? 'class="selected"' : ''} href="people/Listing.action">People</a>
</div>
<div class="submenu">
<c:if test="${isEvents}">
List of Events|New Event
</c:if>
<c:if test="${isPeople}">
List of People|New Person
</c:if>
</div>
It can actually be optimized more if you collect all those "hardcoded" values like events and people and link texts in a Map in the application scope and use under each the JSTL <c:forEach> to display the tabs.
As to your actual question, you can disable scriptlets (and get runtime errors about using it) by adding the following entry in webapp's web.xml. It may help to spot overseen scriptlets.
<jsp-config>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<scripting-invalid>true</scripting-invalid>
</jsp-property-group>
</jsp-config>
To learn more about EL, check the Java EE tutorial part II chapter 5. Implicit EL objects, such as ${pageContext} are described here. To learn more about JSTL, check the Java EE tutorial part II chapter 7. Note that JSTL and EL are two separate things. JSTL is a standard taglib and EL just enables to access backend data programmatically. Although it is normally used in taglibs like JSTL, it can also be used standalone in template text.
As an aside, is <%= request.getContextPath() %> an acceptable use of scriptlets that isn't frowned on so much?
This may be an unpopular opinion, but if all you do are simple conditionals and text insertions, I cannot find much fault in the use of scriptlets. (Note the if)
I'd probably use JSTL and the expression language, but mostly because it can be less typing, and IDE support may be better (but a good JSP IDE can also find missing closing brackets and stuff like that).
But fundamentally (as in "keep logic out of templates") I fail to see any difference between
<% if(request.getRequestURI().contains("/events/")) { %>
and
${fn:contains(pageContext.request.requestURI, '/events/')
Scriptlets aren't the worst thing in the world. An important consideration is to think about who is going to be maintaining the code. If its web designers who don't have much Java experience, you are probably better off going with tag libraries. However, if Java developers are doing the maintainance, it may be easier on them to go with scriptlets.
If you end up using a tag library and JSTL, you are expecting the maintainer to also learn the tag library and know JSTL. Some developers will be fine with this as it is a skill they want or already have, but for some developers who only have to deal with JSPs every few months or so, it can be lot less painful to work with clearly written scriptlets written in nice, familiar Java.
This isn't a direct answer to your question (and there are already several good ones, so I won't try to add to it), but you did mention:
Can someone with a bit more java/jsp
experience please give me some
pointers as to how to change this code
so its more 'best practice', whatever
that may be?
In my opinion, best practice, with regards to JSP, is that it should be used strictly as a templating engine, and no more (i.e., no business logic in there). Using JSTL, as many pointed out, definitely helps you get there, but even with JSTL, it's easy to do to much in a JSP.
I personally like to follow the rules laid out in Enforcing Strict Model-View Separation in Templating Engines by the Terence Parr when developing in JSP. The paper mentions the purpose of templating engines (separating model and view), and characteristics of a good templating engine. It takes a good look at JSP and points out ways it's not a good templating engine. Not surprisingly, JSP is basically too powerful and allows developers to do too much. I strongly recommend reading this paper, and it'll help you restrict yourself to the "good" parts of JSP.
If you read only one section in that paper, read chapter 7, which includes the following rules:
the view cannot modify the model either by directly altering model
data objects or by invoking methods on
the model that cause side-effects.
That is, a template can access data
from the model and invoke methods, but
such references must be side-effect
free. This rule arises partially
because data references must be
order-insensitive. See Section 7.1.
the view cannot perform computations upon dependent data
values because the computations may
change in the future and they should
be neatly encapsulated in the model in
any case. For example, the view cannot
compute book sale prices as
“$price*.90”. To be independent of the
model, the view cannot make
assumptions about the meaning of data.
the view cannot compare dependent data values, but can test the
properties of data such as
presence/absence or length of a
multi-valued data value. Tests like
$bloodPressure<120 must be moved to
the model as doctors like to keep
reduc- ing the max systolic pressure
on us. Expressions in the view must be
replaced with a test for presence of a
value simulat- ing a boolean such as
$bloodPressureOk!=null Template output
can be conditional on model data and
com- putations, the conditional just
has to be computed in the model. Even
simple tests that make negative values
red should be computed in the model;
the right level of abstraction is usu-
ally something higher level such as
“department x is losing money.”
the view cannot make data type assumptions. Some type assumptions are
obvious when the view assumes a data
value is a date, for example, but more
subtle type assumptions ap- pear: If a
template assumes $userID is an
integer, the pro- grammer cannot
change this value to be a non-numeric
in the model without breaking the
template. This rule forbids array
indexing such as colorCode[$topic] and
$name[$ID] The view further cannot
call methods with arguments be- cause
(statically or dynamically) there is
an assumed argu- ment type, unless one
could guarantee the model method
merely treated them as objects.
Besides graphics designers are not
programmers; expecting them to invoke
methods and know what to pass is
unrealistic.
data from the model must not contain display or layout information.
The model cannot pass any display
informa- tion to the view disguised as
data values. This includes not passing
the name of a template to apply to
other data values.
Incidentally, Terence has created his own templating engine called String Template which supposedly does a really good job of enforcing these rules. I have no personal experience with it, but would love to check it out on my next project.
You may want to start by using tag libraries. You can use the standard tag library JSTL to do most of the common things that you need scriplets for. There are many other richer tag libraries that are used like in the struts2 framework or from apache.
e.g.
<c:if test="${your condition}">
Your Content
</c:if>
would replace your if statements.
The preferred alternative to scriptlets is the JSTL expression language; here's a good overview. You'll need to add the taglib like so:
<%# taglib uri='http://java.sun.com/jsp/jstl/core' prefix='c' %>
As an example, JSTL provides a bunch of implicit objects that give you the stuff you need; the one you want is pageContext.request.
So you can replace <%request.getRequestURI%> with ${pageContext.request.requestURI}.
You can do conditionals using <c:if> tags.
You'll need to use some web framework. Or at least some convenient taglib. Or a templating enginge like FreeMarker.
Ad frameworks:
If you like JSP way of coding, then I'd suggest Struts 2.
<s:if test="%{false}">
<div>Will Not Be Executed</div>
</s:if>
<s:elseif test="%{true}">
<div>Will Be Executed</div>
</s:elseif>
<s:else>
<div>Will Not Be Executed</div>
</s:else>
Then there's component-oriented JSF.
If you like OOP and coding everything in Java, try Apache Wicket (my favorite) or Google Web Toolkit.
When trying to use a custom JSP tag library, I have a variable defined in JSP that I would like to be evaluated before being passed to the tag library. However, I cannot seem to get it to work. Here's a simplified version of my JSP:
<% int index = 8; %>
<foo:myTag myAttribute="something_<%= index %>"/>
The doStartTag() method of my TagHandler uses the pageContext's output stream to write based on the inputted attribute:
public int doStartTag() {
...
out.println("Foo: " + this.myAttribute);
}
However, the output I see in my final markup is:
Foo: something_<%= index %>
instead of what I want:
Foo: something_8
My tag library definition for the attribute is:
<attribute>
<name>myAttribute</name>
<required>true</required>
</attribute>
I have tried to configure the attribute with rtexprvalue both true and false, but neither worked. Is there a way I can configure the attribute so that it's evaluated before being sent to the Handler? Or am I going about this totally wrong?
I'm relatively new to JSP tags, so I'm open to alternatives for solving this problem. Also, I realize that using scriptlets in JSP is frowned upon, but I'm working with some legacy code here so I'm kind of stuck with it for now.
Edit:
I have also tried:
<foo:myTag myAttribute="something_${index}"/>
which does not work either - it just outputs something_${index}.
I don't believe that you can use a <%= ... %> within an attribute in a custom tag, unless your <%= ... %> is the entire contents of the attribute value. Does the following work for you?
<% int index = 8; %>
<% String attribValue = "something_" + index; %>
<foo:myTag myAttribute="<%= attribValue %>"/>
EDIT: I believe the <% ... %> within the custom tag attribute can only contain a variable name. not any Java expression.
To keep your JSP code clean and neat, avoid scripting when possible. I think this is the preferred way to do it:
<foo:myTag >
<jsp:attribute name="myAttribute">
something_${index}
</jsp:attribute>
</foo:myTag >
if your tag also contains a body, you'll have to change it from
<foo:myTag myAttribute="<%= attribValue %>">
body
</foo:myTag >
to
<foo:myTag >
<jsp:attribute name="myAttribute">
something_${index}
</jsp:attribute>
<jsp:body>
body
</jsp:body>
</foo:myTag >
<foo:myTag myAttribute="something_${index}"/>