Struts 2 Date Format In this tutorial you will learn about Date Format function in Struts 2. We have provided fully tested example code to illustrate the concepts. You can copy the code and use it for your fast development. Struts Date tag Struts date tag is used to output the date into required format. It can be used to format the date into several different formats. Syntax of the date tag is: <s:date name="todayDate" format="yyyy-MM-dd" /> Parameters Following table shows the parameters of date tag. Name Requir ed Default Evaluate d Type Description format false false String The date format pattern id false true String It will be used id tag in the HTML name true true String The date value which is to be formatted nice false false true Boolean Whether to print out the date nicely The nice format is very interesting. The following table shows, how it will format the date output: i18n key default struts.date.forma t.past {0} ago struts.date.forma t.future in {0} 1
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Struts 2 Date Format
In this tutorial you will learn about Date Format function in Struts 2. We have provided fully tested example code to illustrate the concepts. You can copy the code and use it for your fast development.
Struts Date tag
Struts date tag is used to output the date into required format. It can be used to format the date into several different formats. Syntax of the date tag is:
<s:date name="todayDate" format="yyyy-MM-dd" />
Parameters
Following table shows the parameters of date tag.
Name Required Default Evaluated Type Description
format false false String The date format pattern
id false true String It will be used id tag in the HTML
name true true StringThe date value which is to be formatted
nice false false true BooleanWhether to print out the date nicely
The nice format is very interesting. The following table shows, how it will format the date output:
struts.date.format.hours{0,choice,1#one hour|1<{0} hours}{1,choice,0#|1#, one minute|1<, {1} minutes}
struts.date.format.days{0,choice,1#one day|1<{0} days}{1,choice,0#|1#, one hour|1<, {1} hours}
struts.date.format.years{0,choice,1#one year|1<{0} years}{1,choice,0#|1#, one day|1<, {1} days}
Writing Example
1
In this example we will use DateBean action class to get the current date of the system. This current date will be used in our example. Here is the code of DateBean.java
In this section you learnt how to use Struts 2 Date format tag.
Struts 2 datetimepicker
In this section we will show you how to develop datetimepicker in struts 2. Struts 2 uses the dojo toolkit for creating date picker. In Struts 2 its very easy to create date time picker.
The <s:datetimepicker .../> tag
The Struts 2 <s:datetimepicker ...> actually renders date/time picker in the dropdown container. When user clicks on the calendar icon the date/time picker is displayed on the form.
4
Struts 2 date picker is actually Dojo widget, that makes it easy to select a date. It also provides easy way to select any date/month/year very fast. The date time picker will make your web application very user friendly.
Writing time picker code
Action class to get today's date is DateBean. Here is the code of DateBean.java
Struts 2 date picker is dojo widget so, it is necessary to generate the client side JavaScript code. The <s:head theme="ajax" /> generates the client side dojo specific java script. Here is the code generated by this tag:
6
<link rel="stylesheet" href="/struts2tutorial/struts/xhtml/styles.css" type="text/css"/><script language="JavaScript" type="text/javascript"> // Dojo configuration djConfig = { baseRelativePath: "/struts2tutorial/struts/dojo", isDebug: false, bindEncoding: "UTF-8", debugAtAllCosts: true // not needed, but allows the Venkman debugger to work with the includes };</script><script language="JavaScript" type="text/javascript" src="/struts2tutorial/struts/dojo/dojo.js"></script><script language="JavaScript" type="text/javascript" src="/struts2tutorial/struts/simple/dojoRequire.js"></script><script language="JavaScript" type="text/javascript" src="/struts2tutorial/struts/ajax/dojoRequire.js"></script><script language="JavaScript" type="text/javascript" src="/struts2tutorial/struts/CommonFunctions.js"></script>
Following table summarizes the format by datepicker component:
Format Description
dd This format is used to display day in two digits format
d Try to display day in one digit format, if cannot use 2 digit format
MM The format displays month in two digits format
M It try to display month in one digits format, if cannot use 2 digit format
yyyy Display year in four digits format
yy Display the last two digits of the year
y Display the last digits of the year
Here is the output of the program
7
In this section we have studied how to use Struts 2 datepicker control.
Struts 2 Format
In this section you will learn how to format Date and numbers in Struts 2 Framework. Our Struts 2 Format Examples are very easy to grasp and you will learn these concepts in very small time.
If you start developing any real world web application, at some point of time you will delve into the problem of displaying the date and number in some specific format. You can easily write your code and then format the output as string in your action class. But there is some drawback it like:
Your code are not aware of i18n. It will be very difficult to adapt to different locals.
Your action class are also clutter with unnecessary code.
Struts 2 in-built formatting functionality can save you from above problem. You can use s:text tag built-in formatting functionality to format your date and numbers.
Steps to Develop Example code
Write Action class
In the action class we are creating three fields:
8
private String productName;private Double productCost;private Date orderDate;
The values in these variables will be used for displaying on the jsp page. Here is the code of action class (OrderBean.java):
Please note that the formatting for product.name, product.cost and product.orderDate are defined in the package.properties message resource file.
Defining the formatting in properties file
In Struts 2 the formatting is defined in the message resource file (package.properties). The package.properties file is saved in the directory (package) where your action class resides. Here is the content of package.properties file:
To test the program, compile and package the code and then start tomcat. Type http://localhost:8080/struts2tutorial/roseindia/Struts2Format.action in the browser to view the result. Your browser should show the following output:
In this section you learnt how to use Struts 2 Format functionality.
Struts 2 File Upload
In this section you will learn how to write program in Struts 2 to upload the file on the server. In this example we are also providing the code to save the uploaded file in any directory on the server machine.
The Struts 2 FileUpload component can be used to upload the multipart file in your Struts 2 application. In this section you will learn about the code to upload file on the server.
How File Upload Works in Struts 2?
Struts 2 utilizes the service of File Upload Interceptor to add the support for uploading files in the Struts applications. The Struts 2 File Upload Interceptor is based on MultiPartRequestWrapper, which is automatically applied to the request if it contains the file element. Then it adds the following parameters to the request (assuming the uploaded file name is MyFile).
[MyFile] : File - the actual File [MyFile]ContentType : String - the content type of the file
12
[File Name]FileName : String - the actual name of the file uploaded (not the HTML name)
In the action class you can get the file, the uploaded file name and content type by just creating getter and setters. For example, setMyfile(File file), setMyFileContentType(String contentType), getMyFile(), etc..
The file upload interceptor also does the validation and adds errors, these error messages are stored in the struts-messsages.properties file. The values of the messages can be overridden by providing the text for the following keys:
struts.messages.error.uploading - error when uploading of file fails struts.messages.error.file.too.large - error occurs when file size is large struts.messages.error.content.type.not.allowed - when the content type is not
allowed
Parameters
You can use the following parameters to control the file upload functionality.
maximumSize This parameter is optional. The default value of this is 2MB. allowedTypes This parameter is also optional. It allows you to specify the
allowed content type.
Writing Example code to upload file
Now we will write the code to upload the file on server.
Action Class
In the action class we will define four properties to facilitate the file upload.
private File upload; // The actual file
private String uploadContentType;// The content type of the file
private String uploadFileName;// The uploaded file name and path
private String fileCaption;// The caption of the file entered by user.
Here is the full code of action class StrutsFileUpload.java
package net.roseindia;import java.util.Date;import java.io.File;import com.opensymphony.xwork2.ActionSupport;public class StrutsFileUpload extends ActionSupport {
13
private File upload;//The actual file private String uploadContentType; //The content type of the file private String uploadFileName; //The uploaded file name private String fileCaption;//The caption of the file entered by user public String execute() throws Exception {
return SUCCESS;
} public String getFileCaption() { return fileCaption; } public void setFileCaption(String fileCaption) { this.fileCaption = fileCaption; } public File getUpload() { return upload; } public void setUpload(File upload) { this.upload = upload; } public String getUploadContentType() { return uploadContentType; } public void setUploadContentType(String uploadContentType) { this.uploadContentType = uploadContentType; } public String getUploadFileName() { return uploadFileName; } public void setUploadFileName(String uploadFileName) { this.uploadFileName = uploadFileName; }
}
Here we have not shown the code to save the uploaded file. But it can be done easily using the following code in execute(..) method of action class. Here is code snippet.
//Following code can be used to save the uploaded file
try {
String fullFileName = "c:/upload/myfile.txt";
File theFile = new File(fullFileName);
FileUtils.copyFile(upload, theFile);
} catch (Exception e) {
14
addActionError(e.getMessage());
return INPUT;
}
Writing JSP page
Here is the code of jsp file (upload.jsp) that displays the file upload form to the user.
The "showUpload" action displays the upload form and "doUpload" action actually uploads the file.
Running the example
To test the application compile code and then run the tomcat. Type http://localhost:8080/struts2tutorial/roseindia/showUpload.action in your browser. You browser should show the following form:
Now browse the file, enter caption and then click on the "Submit" button. Application will upload your file and then following success screen will be displayed.
There is one important point to be noted about File Upload Interceptor. The File Upload Interceptor actually deletes the the upload, once the action is executed. Here is the screen shot of tomcat that shows the file delete message:
In this section you learnt the concept of file upload in struts 2.
Struts 2 Resources
a) Static Parameter
In this section, we will develop a simple application to access the static parameters. We will use a JavaBean to set and get the static parameters. Each static parameter has a value.
Description :
Develop a JavaBean with three properties (Static Parameters) of string type ( parameter1,parameter2, parameter3 ). Define three JavaBean properties and add their corresponding values in the action mapping (in the application's struts.xml ). Set the name(s) and value(s) as shown below:
Create a simple JavaBean StaticParameter.java in the "struts2tutorial\WEB-INF\src\java\net\roseindia" directory. Here the "StaticParameter" class extends the ActionSupport class. It sets and gets the three static parameters by using the setParameter1(), setParameter2(), setParameter3() and getParameter1(), getParameter2(), getParameter3() methods.
Now compile the JavaBean (StaticParameter.java) through the 'ant' command.
Open web browser and give request as http://localhost:8080/struts2tutorial/roseindia/StaticParameter.action. It displays a table that contains three static parameters in key-value format.
Output of this application:
B) Accessing Session Object
20
In this section, we will develop a simple application to access the framework resources like the session object, session context and the last accessed session time. To access the session, you need an action class implementing the SessionAware interface and extending ActionSupport class.
org.apache.struts2.interceptor.SessionAware Interface: Actions that need access to the user's HTTP session should implement this interface. This interface is only relevant if the Action is used in a servlet environment. Note that using this interface makes the Action tied to a servlet environment, so it should be avoided if possible since things like unit testing will become more difficult.
Description:
add the following action snippet to the following struts.xml file.
public void setSession(Map session){ session = this.getSession(); }
public Map getSession(){
21
return session; }
}
Now, we create a jsp page for viewing the session object, session context and session time. The session object provides information about the session, getSessionContext() method provides the information about the session context and getLastAccessedTime() provides date and time when the last session is accessed.
Finally, open the web-browser and type the http://localhost:8080/struts2tutorial/roseindia/GetSession.action in the address bar. It displays the information about framework session, session context and last accessed session time.
Output of this application:
22
C) Access Request and Response
In this section, you will learn to develop an application that accesses the request and response object in struts 2 application. To access the request object , use the ActionContext or implement the ServletRequestAware interface and to access the response object, use the ActionContext or implement the ServletResponseAware interface.
Here, in this application, we are going to implement the ServletRequestAware and ServletResponseAware interfaces in our action class.
Accessing the request and response object, you need a struts.xml file.
Here we use the setServletRequest() (for setting the request object) and getServletRequest() (for getting the request object) methods of ServletRequestAware interface. Similarly, we use the setServletResponse() (for setting the response) and getServletResponse() (for getting the response) methods of ServletResponseAware interace.
Open the web-browser and type the "http://localhost:8080/struts2tutorial/roseindia/AccessRequest.action" in the address bar and press the "enter key" it displays the access request and response object as well as accessed date and time.