Java variable in jsp tag?

I am 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 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 would like to be able to reuse headerDateFormat in javascript through Rhino - I think it will work with it, but not in JSP tags.

+6
java jsp
source share
2 answers

If you want to use

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

(which is actually correct )

then you should put it as an attribute in one of the areas of the page, request, session or application with this name as the key. Assuming you want to put it in the request area of ​​the 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 be installed in the page area by default.

See also:

  • Our JSP Wiki Page - A Short Introduction to JSP
+8
source share

Try something similar with the optional 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> 
+3
source share

All Articles