Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java variable in a jsp tag?

Tags:

java

jsp

I'm trying to do something like this:

<%
    String headerDateFormat = "EEE, d MMM yyyy h:mm:ss aa"; 
%>

<fmt:formatDate pattern="<% out.print( headerDateFormat ); %>" value="${now}" />

I've also tried:

<fmt:formatDate pattern="${headerDateFormat}" value="${now}" />

And:

<fmt:formatDate pattern="headerDateFormat" value="${now}" />

I'm obviously very new to JSP - is this possible? Ideally I'd like to be able to reuse the headerDateFormat in javascript via Rhino - I think as is it will work with it, but not in the JSP tags.

like image 244
javamonkey79 Avatar asked Feb 25 '11 19:02

javamonkey79


2 Answers

If you want to use

<fmt:formatDate pattern="${headerDateFormat}" value="${now}" />

(which is actually the right way)

then you should be putting it as an attribute in one of the page, request, session or application scopes with that name as key. Assuming that you want to put it in the request scope in a servlet:

String headerDateFormat = "EEE, d MMM yyyy h:mm:ss aa";
request.setAttribute("headerDateFormat", headerDateFormat);

You can also use JSTL <c:set> for this.

<c:set var="headerDateFormat" value="EEE, d MMM yyyy h:mm:ss aa" />

it will by default be set in the page scope.

See also:

  • Our JSP wiki page - a little introduction to JSP
like image 119
BalusC Avatar answered Oct 23 '22 20:10

BalusC


Try something like this using an additional JSTL tag in your JSP:

<%-- note the single quotes around the value attribute --%>
<c:set var="headerDateFormat" value="'EEE, d MMM yyyy h:mm:ss aa'"/>
<fmt:formatDate pattern="${headerDateFormat}" value="${now}" />

Also in your JSP, add a JavaScript block to access the JSP variable:

<script>
  var format = '<c:out value="${headerDateFormat}"/>';
  // use format as needed in JavaScript
</script>
like image 36
Brent Worden Avatar answered Oct 23 '22 19:10

Brent Worden