Professional Documents
Culture Documents
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 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:
Parameters
The nice format is very interesting. The following table shows, how it will format the
date output:
Writing Example
2
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
package net.roseindia;
import com.opensymphony.xwork2.ActionSupport;
import java.util.Date;
/**
* <p> Validate a user login. </p>
*/
public class DateBean extends ActionSupport {
setTodayDate(new Date());
return SUCCESS;
/**
* <p>Field to store Today's Date.</p>
* <p/>
*/
private Date todayDate;
/**
* <p>Provide Today's Date.</p>
*
* @return Returns the Todays date.
*/
public Date getTodayDate() {
return todayDate;
}
/**
* <p>Store new Date</p>
*
* @param value The username to set.
*/
public void setTodayDate(Date value) {
todayDate = value;
}
Add the following entry in the struts.xml file in order to create action mapping:
3
</head>
<body>
<tr>
<td>Date in (yyyy-MM-dd) Format:</td>
<td>
<b><s:date name="todayDate" format="yyyy-MM-dd" /></b>
</td>
</tr>
<tr>
<td>Date in (MM/dd/yyyy hh:mm AM/PM) Format:</td>
<td>
<b><s:date name="todayDate" format="MM/dd/yyyy 'at' hh:mm a" /></b>
</td>
</tr>
<tr>
<td>Date in (dd-MMM-yyyy hh:mm AM/PM) Format:</td>
<td>
<b><s:date name="todayDate" format="dd-MMM-yyyy 'at' hh:mm a" /></b>
</td>
</tr>
<tr>
<td>Date in (dd/MM/yyyy hh:mm) Format:</td>
<td>
<b><s:date name="todayDate" format="dd/MM/yyyy hh:mm" /></b>
4
</td>
</tr>
<tr>
<td>Nice Format:</td>
<td>
<b><s:date name="todayDate" format="yyyy-MM-dd" nice="true"/></b>
</td>
</tr>
</s:form>
</body>
</html>
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 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.
5
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.
Action class to get today's date is DateBean. Here is the code of DateBean.java
package net.roseindia;
import com.opensymphony.xwork2.ActionSupport;
import java.util.Date;
/**
* <p> Validate a user login. </p>
*/
public class DateBean extends ActionSupport {
setTodayDate(new Date());
return SUCCESS;
/**
* <p>Field to store Today's Date.</p>
* <p/>
*/
private Date todayDate;
/**
* <p>Provide Today's Date.</p>
*
* @return Returns the Todays date.
*/
public Date getTodayDate() {
return todayDate;
}
/**
* <p>Store new Date</p>
*
* @param value The username to set.
*/
public void setTodayDate(Date value) {
todayDate = value;
}
6
Add the following entry in the struts.xml file in order to create action mapping:
</head>
<body>
</s:form>
</body>
</html>
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:
7
<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>
The code:
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.
The values in these variables will be used for displaying on the jsp page. Here is the code
of action class (OrderBean.java):
package net.roseindia;
import com.opensymphony.xwork2.ActionSupport;
import java.util.Date;
/**
* <p> Validate a user login. </p>
*/
public class OrderBean extends ActionSupport {
setOrderDate(new Date());
setProductName("ICE Cream");
setProductCost(102.08);
return SUCCESS;
/**
* <p>Field to store Today's Date.</p>
* <p/>
*/
private Date orderDate;
/**
* <p>Provide Today's Date.</p>
*
* @return Returns the Todays date.
*/
public Date getOrderDate() {
return orderDate;
}
/**
* <p>Store new Date</p>
*
* @param value The Order date to set.
*/
public void setOrderDate(Date value) {
10
orderDate = value;
}
The execute method of action class populates Product Name, Product cost and Order
date.
setOrderDate(new Date());
setProductName("ICE Cream");
setProductCost(102.08);
return SUCCESS;
In the following jsp page (struts2format.jsp) you can view the actual usage of the tag.
</head>
<body>
<tr>
<td align="right">Product Name:</td>
<td>
<b><s:text name="product.name">
<s:param name="value" value="productName"/>
</s:text>
</b>
</td>
</tr>
<tr>
<td align="right">Product cost:</td>
<td>
<s:text name="product.cost" >
<s:param name="value" value="productCost"/>
</s:text>
</td>
</tr>
<tr>
<td align="right">Order Date:</td>
<td>
<b><s:text name="product.orderDate">
<s:param name="value" value="orderDate"/>
</s:text>
</b>
</td>
</tr>
</s:form>
</body>
</html>
Please note that the formatting for product.name, product.cost and product.orderDate
are defined in the package.properties message resource file.
So, you can easily define or change the formatting of output just modifying the properties
file.
Modification in struts.xml
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 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.
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).
• [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:
Parameters
You can use the following parameters to control the file upload functionality.
Action Class
In the action class we will define four properties to facilitate the file upload.
package net.roseindia;
import java.util.Date;
import java.io.File;
import com.opensymphony.xwork2.ActionSupport;
public class StrutsFileUpload extends ActionSupport {
14
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.
try {
FileUtils.copyFile(upload, theFile);
} catch (Exception e) {
15
addActionError(e.getMessage());
return INPUT;
Here is the code of jsp file (upload.jsp) that displays the file upload form to the user.
</head>
<body>
<s:actionerror />
<s:fielderror />
<s:form action="doUpload" method="POST" enctype="multipart/form-data">
<tr>
<td colspan="2"><h1>File Upload Example</h1></td>
</tr>
In the above code the form encrypt type is "multipart/form-data" and <s:file ../> tag
renders the html file tag.
<%@ page
language="java"
contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
16
<html>
<head>
<title>Showcase</title>
<link href="<s:url value="/css/main.css"/>" rel="stylesheet" type="text/css"/>
</head>
<body>
<table class="wwFormTable">
<tr>
<tr>
<td class="tdLabel"><label for="doUpload_upload" class="label">Content
Type:</label></td>
<td><s:property value="uploadContentType" /></td>
</tr>
<tr>
<td class="tdLabel"><label for="doUpload_upload" class="label">File
Name:</label></td>
<td ><s:property value="uploadFileName" /></td>
</tr>
<tr>
<td class="tdLabel"><label for="doUpload_upload" class="label">File:</label></td>
<td><s:property value="upload" /></td>
</tr>
<tr>
<td class="tdLabel"><label for="doUpload_upload" class="label">File
Caption:</label></td>
<td><s:property value="caption" /></td>
</tr>
</table>
</body>
</html>
<action name="showUpload">
<result>/pages/upload.jsp</result>
</action>
The "showUpload" action displays the upload form and "doUpload" action actually
uploads the file.
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.
18
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:
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 :
<action name="StaticParameter"
class="net.roseindia.StaticParameter">
<param name="pramater1">Value 1</param>
<param name="pramater2">Value 2</param>
<param name="pramater3">Value 3</param>
<result>/pages/staticparameter/showparamerts.jsp</result>
</action>
StaticParameter.java
package net.roseindia;
19
import com.opensymphony.xwork2.ActionSupport;
import java.util.Date;
showparameters.jsp
</tr>
<tr>
<td width="25%">pramater1</td>
<td width="25%"><s:property value="pramater1" /></td>
</tr>
<tr>
<td width="25%">pramater2</td>
<td width="25%"><s:property value="pramater2" /></td>
</tr>
<tr>
<td width="25%">pramater3</td>
<td width="25%"><s:property value="pramater3" /></td>
</tr>
</table>
</body>
</html>
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
21
session, you need an action class implementing the SessionAware interface and extending
ActionSupport class.
Description:
struts.xml
<action name="GetSession"
class="net.roseindia.GetSession">
<result>/pages/staticparameter/GetSession.jsp</result>
</action>
Now, create a JavaBean (GetSesstion.java). This is a simple POJO (Plain Old Java
Object). Here, we implement SessionAware interface.
The setSession() method sets the session in a Map object. It is called at the running time.
GetSession.java
package net.roseindia;
import org.apache.struts2.interceptor.SessionAware;
import com.opensymphony.xwork2.ActionSupport;
import java.util.*;
}
22
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.
GetSession.jsp
</body>
</html>
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.
Accessing the request and response object, you need a struts.xml file.
struts.xml
<action name="AccessRequest"
class="net.roseindia.AccessRequest">
<result>/pages/staticparameter/AccessRequest.jsp</result>
</action>
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.
AccessRequest.java
package net.roseindia;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
Finally, create a jsp page for accessing the request and response object.
AccessRequest.jsp
<html>
<head>
<title>Access Request and Response Example! </title>
</head>
<body>
<h1><span style="background-color: #FFFFcc">Access Request
and Response Example!</span></h1>
<b>Request: </b><%=request%><br>
<b>Response: </b><%=response%><br>
<b>Date: </b><%=new Date()%>
</body>
</html>