Struts 2 datetimepicker example

In Struts 2, the dojo ajax tag “<sx:datetimepicker>” will render a text box and append a calender icon behind, click on the calender icon will prompt a date time picker component.

To create a date time pick component, just ensure :
1. Download the struts2-dojo-plugin.jar library.
2. Include the “struts-dojo-tags” tag and output its header.


<%@ taglib prefix="sx" uri="/struts-dojo-tags" %>
<html>
<head>
<sx:head />
</head>

For example,


<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ taglib prefix="sx" uri="/struts-dojo-tags" %>
<html>
<head>
<sx:head />
</head>
<body>
<sx:datetimepicker name="date2" label="Format (dd-MMM-yyyy)" 
displayFormat="dd-MMM-yyyy" value="%{'2010-01-01'}"/>
...

Resulting the following HTML, few dojo and JavaScript libraries to create a date time pick component.


<html> 
<head> 
<script language="JavaScript" type="text/javascript"> 
    // Dojo configuration
    djConfig = {
        isDebug: false,
        bindEncoding: "UTF-8"
          ,baseRelativePath: "/Struts2Example/struts/dojo/"
          ,baseScriptUri: "/Struts2Example/struts/dojo/"
         ,parseWidgets : false
    };
</script> 
<script language="JavaScript" type="text/javascript"
        src="/Struts2Example/struts/dojo/struts_dojo.js"></script> 

<script language="JavaScript" type="text/javascript"
        src="/Struts2Example/struts/ajax/dojoRequire.js"></script> 

<link rel="stylesheet" href="/Struts2Example/struts/xhtml/styles.css" type="text/css"/> 

<script language="JavaScript" src="/Struts2Example/struts/utils.js" 
type="text/javascript"></script> 

<script language="JavaScript" src="/Struts2Example/struts/xhtml/validation.js" 
type="text/javascript"></script> 

<script language="JavaScript" src="/Struts2Example/struts/css_xhtml/validation.js" 
type="text/javascript"></script> 
</head> 
...
<td class="tdLabel">
<label for="widget_1291193434" class="label">Format (dd-MMM-yyyy):
</label></td> 
<td>
<div dojoType="struts:StrutsDatePicker"    id="widget_1291193434"    
value="2010-01-01"    name="date2"    inputName="dojo.date2"    
displayFormat="dd-MMM-yyyy"  saveFormat="rfc"></div> 
</td> 
</tr> 
<script language="JavaScript" type="text/javascript">
djConfig.searchIds.push("widget_1291193434");</script> 

Struts 2 <s:datetimepicker> example

A complete full example of the <s:datetimepicker> tag to generate a datetimepicker component, and show the use of OGNL and Java property to set the default date to the “datetimepicker” component.

1. pom.xml

Download the Struts 2 dojo dependency libraries.

pom.xml


//...
   <!-- Struts 2 -->
   <dependency>
      <groupId>org.apache.struts</groupId>
      <artifactId>struts2-core</artifactId>
      <version>2.1.8</version>
    </dependency>
	
    <!-- Struts 2 Dojo Ajax Tags -->
    <dependency>
      <groupId>org.apache.struts</groupId>
      <artifactId>struts2-dojo-plugin</artifactId>
      <version>2.1.8</version>
    </dependency>
//...

2. Action class

Action class to store the selected date.

DateTimePickerAction.java


package com.mkyong.common.action;

import java.util.Date;
import com.opensymphony.xwork2.ActionSupport;

public class DateTimePickerAction extends ActionSupport{

	private Date date1;
	private Date date2;
	private Date date3;
	
	//return today date
	public Date getTodayDate(){
		
		return new Date();
	}

	//getter and setter methods
	public String execute() throws Exception{
		
		return SUCCESS;
	}

	public String display() {
		return NONE;
	}
	
}

3. Result Page

Render the date time picker component via “<s:datetimepicker>” tag, set the default date via Java property and OGNL.

The ‘displayFormat‘ attribute is supported in many date patterns, read this article – Date Format Patterns.
Ensure you put the “struts-dojo-tags” tag and render it’s header <sx:head />


<%@ taglib prefix="sx" uri="/struts-dojo-tags" %>
<html>
<head>
<sx:head />
</head>

datetimepicker.jsp


<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ taglib prefix="sx" uri="/struts-dojo-tags" %>
<html>
<head>
<sx:head />
</head>

<body>
<h1>Struts 2 datetimepicker example</h1>

<s:form action="resultAction" namespace="/" method="POST" >

<sx:datetimepicker name="date1" label="Format (dd-MMM-yyyy)" 
displayFormat="dd-MMM-yyyy" value="todayDate" />

<sx:datetimepicker name="date2" label="Format (dd-MMM-yyyy)" 
displayFormat="dd-MMM-yyyy" value="%{'2010-01-01'}"/>

<sx:datetimepicker name="date3" label="Format (dd-MMM-yyyy)" 
displayFormat="dd-MMM-yyyy" value="%{'today'}"/>

<s:submit value="submit" name="submit" />
	
</s:form>

</body>
</html>

result.jsp


<%@ taglib prefix="s" uri="/struts-tags" %>
<html>

<body>
<h1>Struts 2 datetimepicker example</h1>

<h2>
   Date1 : <s:property value="date1"/> 
</h2> 

<h2>
   Date 2 : <s:property value="date2"/> 
</h2> 

<h2>
   Date 3 : <s:property value="date3"/> 
</h2> 

</body>
</html>

3. struts.xml

Link it all ~


<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
 
<struts>

 <constant name="struts.devMode" value="true" />
	
<package name="default" namespace="/" extends="struts-default">
		
  <action name="dateTimePickerAction" 
	class="com.mkyong.common.action.DateTimePickerAction" 
        method="display">
	<result name="none">pages/datetimepicker.jsp</result>
  </action>
		
  <action name="resultAction" 
        class="com.mkyong.common.action.DateTimePickerAction" >
	<result name="success">pages/result.jsp</result>
  </action>
</package>
	
</struts>

4. Demo

http://localhost:8080/Struts2Example/dateTimePickerAction.action

Struts 2 datetimepicker example
Struts 2 datetimepicker example

Reference

  1. Struts 2 datetimepicker documentation
  2. Struts 2 ajax and javascript recipes
  3. Date Format Pattern

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
24 Comment threads
6 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
27 Comment authors
praveenvenkateshSuweiulimanjushree Recent comment authors
newest oldest most voted
praveen
Guest
praveen

Hello mkyong sir, Is it possible to get time also along with date?? thanks in advance

venkatesh
Guest
venkatesh

how to use date picker for date and time as well

Suwei
Guest
Suwei

You speak Chinese?I can not read EnglishO(?_?)O~

manjushree
Guest
manjushree

hi,
Is there any option to change the template of the calender?

bala
Guest
bala

Hi,

I have implemented the above code but date picker is not displaying only label is displaying in IE 10. Can you please suggest ?

varun
Guest
varun

I have implemented Struts dojo calender in my application.But,It is not working in IE10.
Please suggest me this issue.

Prateek
Guest
Prateek

I want to set enddate to be 3 months from today. So how to do it?

Gurumurthy
Guest
Gurumurthy

Hi All,

I have implemented Struts dojo calender in my application.But,It is not working in IE10.
Please suggest me abou this issue.
thanks advance to all.

Regards,
Guru

bala
Guest
bala

Hi,

Did u resolved the issue in IE 10, i am also facing the same.Please help

Pankaj
Guest
Pankaj

how to use both date and time in dojo both at a time.

saurabh agrawal
Guest
saurabh agrawal

how to disable the yesterday date i want to show only today date is enable plz help

thank advanced

isharag
Guest
isharag

above date time picker work fine for me…but there is one issue.i need date picker as required field.so how can i do the

Rajdeep Sabui
Guest
Rajdeep Sabui

How did it worked?? Mine is generating an error
Error reading included file template/~~~ajax/controlheader-core.ftl – Class: freemarker.core.Include

uli
Guest
uli

Error rendering label in 2.3.16.3. Works if you skip label or use older or newer version.
See: https://issues.apache.org/jira/browse/WW-4254

ArunBalachandren
Guest
ArunBalachandren

Hi mkyong,
I am lacking in JNDI connectivity using struts2.
Is there any tutorials or source code regarding that..

Thanks in advance,

Jean Bruno
Guest
Jean Bruno

Hey man.
I hope you’re fine.

Have you ever tried the date “2012/10/21” to datetimepicker component?

This component has problem with the date from 20th day.

Do you have some thing to help me with it?

Thank you mkyoung.

hermann
Guest
hermann

I just noticed that with the action extension set to null :

<constant name="struts.action.extension" value=""/>

the the datetimepicker field is not displayed. how can we fix that ?

Richard
Guest
Richard

Hi mkyong,

Your site is so great. It’s a good place to lean Java for me.

I downloaded your example and run it, found the datetimepicker doesn’t support locale zh_cn good. Any solutions?

Thanks!

vaibhav
Guest
vaibhav

Format (dd-MMM-yyyy):
i want to display calander on jsp but do not show ……….

Aniket
Guest
Aniket

Hi,
Above tutorial is very good.
But my problem is i want to pick the date in between the range which i already mentioned.
please give me solution.
Thanks in Advance

Aniket
Guest
Aniket

Hi,
This is good tutorial.
But in my case i need to give range of date, it should be between my previous date & current date.
plz give me solution
Thanks in advance

Gerenne
Guest
Gerenne

Hi,

First, thanks for your post is very usefull.

When I load my app, this work correctly, but then I reload my form with ajax, and I lose my datetimepicker component…

Any idea?

Thanks Irene.

gootys
Guest
gootys

Hi Mykong ,

When I try to implement the above example , get the below error

SEVERE: Servlet.service() for servlet [jsp] in context with path [/Gshax] threw exception [javax.servlet.ServletException: java.lang.NoClassDefFoundError: com/opensymphony/xwork2/util/logging/LoggerFactory] with root cause
java.lang.ClassNotFoundException: com.opensymphony.xwork2.util.logging.LoggerFactory
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1678)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1523)
at org.apache.struts2.dojo.components.DateTimePicker.(DateTimePicker.java:184)
at org.apache.struts2.dojo.views.jsp.ui.DateTimePickerTag.getBean(DateTimePickerTag.java:59)
at org.apache.struts2.views.jsp.ComponentTagSupport.doStartTag(ComponentTagSupport.java:49)
at org.apache.jsp.Hfdadd_jsp._jspx_meth_sx_005fdatetimepicker_005f0(Hfdadd_jsp.java:297)
at org.apache.jsp.Hfdadd_jsp._jspx_meth_s_005fform_005f0(Hfdadd_jsp.java:149)
at org.apache.jsp.Hfdadd_jsp._jspService(Hfdadd_jsp.java:96)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:433)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:389)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:333)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:416)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:405)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:964)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:515)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)

gootys
Guest
gootys

Also,
Can you pls let me know where to put pom.xml in eclipse.
I mean, I was following your other example I am stuck with this one.
Can’t I make this example work without pom.xml ?

canhpv
Guest
canhpv

This is good example.
But when i setup this example i meet one error: i input value into date1 field by keyboard, i do not use calendar. But i move focus other element, that value is lost. Thus i can not input value by hands.

Please help me!

Farah
Guest
Farah

Oh yea! I have the same problem.. Except this everything work fine.

Jayesh
Guest
Jayesh

Hi,

Thanks your articles are nice and helped me lot on many instances. I was trying to use the DOJO validations and it works fine when I use normal text type elements of the html.

However I need to use this with the struts text boxes can you tell me how should I go for this. An approach will really help me.

Regards,
Jayesh

Simal Patel
Guest
Simal Patel

gr8 work.
Thanks for this nice example.

Abhishek
Guest
Abhishek

I am using struts 2 with hibernate.
I have a two date time picker fields in my JSP.one for joining date and other for relieving date and a checkbox “I currently work here”.when the user checks the checkbox i want to disable the Relieving date time picker field.

Please help.