Display Current Date on JSF Page

Is it possible to display the current date (today's) in JSF without using a backing bean?

I have the following code snippet , but it didn't work out.

<div class="leftSide">Today's date #{currentDate}</div>

or

<f:facet name="header">  
<h:outputText value="Today's date" />  
</f:facet>
<h:outputText value="#currentDate">
    <f:convertDateTime pattern="MM/dd/yyyy" type="date" />
</h:outputText>

You could register an instance of java.util.Date as a request scoped bean in faces-config.xml .

<managed-bean>
    <managed-bean-name>currentDate</managed-bean-name>
    <managed-bean-class>java.util.Date</managed-bean-class>
    <managed-bean-scope>request</managed-bean-scope>
</managed-bean>

This way it's available as #{currentDate} without the need for a custom backing bean class.


Update : the JSF utility library OmniFaces has such a bean already registered as #{now} . So if you happen to use OmniFaces already, you can just make use of it directly.

<h:outputText value="#{now}">
    <f:convertDateTime pattern="MM/dd/yyyy" type="date" />
</h:outputText>

In JSF you could use the implicit EL object session that provides access to the current HttpSession. The HttpSession#getLastAccessedTime time ...

... returns the last time the client sent a request associated with this session, as the number of milliseconds since midnight January 1, 1970 GMT, and marked by the time the container received the request.

So you could use the following code snippet in your facelet:

<h:outputText value="#{session.lastAccessedTime}">
      <f:convertDateTime pattern="MM/dd/yyyy" type="date" />
</h:outputText>

This will be server time and may differ from client time with respect to different time zones.

But you could also use a javascript solution, as discussed here:

How do I get the current date in JavaScript?


Or you could do it using Omnifaces. I'm surprised BalusC hasn't told you about this solution (I think he's a great Omnifaces contributor). Maybe it's because using Omnifaces just to display a simple date in a page might be an overkill to some.

Anyway, if your project already uses Omnifaces, there are 2 managed beans exposed by default and one in particular that you may find handy. As per the tag documentation specifies, once Omnifaces is added to your project, you can use the #{now} managed bean.

For instance, to set a Primefaces calendar's max date, I just wrote the following :

    <p:calendar id="myCalendar" pattern="dd/MM/yyyy" 
                value="#{mybean.myDate}" maxdate="#{now}"/>

I guess the #{now} managed bean can be used in many more situations, and probably yours as well.

If your project does not use Omnifaces yet, I suggest you look at their spec and see how helpful it could be for you. For instance, I'm using their validateOrder tag to make sure two dates are properly ordered.

链接地址: http://www.djcxy.com/p/77534.html

上一篇: 我应该使用工厂还是服务来获取AngularJS中的数据?

下一篇: 在JSF页面上显示当前日期