简体   繁体   中英

java variable in a jsp tag?

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.

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:

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM