Top Banner
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
32

Struts 2 Date Format

Apr 11, 2015

Download

Documents

jagadeeshchinni

Struts 2 Date Format
Welcome message from author
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
Page 1: Struts 2 Date Format

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:

i18n key default

struts.date.format.past {0} ago

struts.date.format.future in {0}

struts.date.format.seconds an instant

struts.date.format.minutes {0,choice,1#one minute|1<{0} minutes}

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

Page 2: Struts 2 Date Format

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 {

  

    public String execute() throws Exception {

      setTodayDate(new Date());      return SUCCESS;

  }

    // ---- Username property ----

    /**     * <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:

2

Page 3: Struts 2 Date Format

<action name="FormatDate" class="net.roseindia.DateBean"><result>/pages/dateformat.jsp</result></action>

Following jsp file(dateformat.jsp) shows the usage of date tag:

<%@ taglib prefix="s" uri="/struts-tags" %><html><head><title>Struts 2 Format Date Example!</title>

<link href="<s:url value="/css/main.css"/>" rel="stylesheet"type="text/css"/>

</head><body>

<s:form action="FormatDate" method="POST">

<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>

3

Page 4: Struts 2 Date Format

</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>

Output of the program:

 

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

Page 5: Struts 2 Date Format

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

package net.roseindia;import com.opensymphony.xwork2.ActionSupport;import java.util.Date;

/** * <p> Validate a user login. </p> */public  class DateBean  extends ActionSupport {

  

    public String execute() throws Exception {

      setTodayDate(new Date());      return SUCCESS;

  }

    // ---- Username property ----

    /**     * <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;    }

5

Page 6: Struts 2 Date Format

}

Add the following entry in the struts.xml file in order to create action mapping:

<action name="DateTimePicker" class="net.roseindia.DateBean"><result>/pages/datepicker.jsp</result></action>

Following jsp file(datepicker.jsp) shows the usage of datepicker tag: 

<%@ taglib prefix="s" uri="/struts-tags" %><html><head><title>Struts 2 Format Date Example!</title>

<link href="<s:url value="/css/main.css"/>" rel="stylesheet"type="text/css"/>

<s:head theme="ajax" />

</head><body>

<s:form action="DateTimePicker" method="POST">

<s:datetimepicker name="todayDate" label="Format (yyyy-MM-dd)" displayFormat="yyyy-MM-dd"/>

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

</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:

6

Page 7: Struts 2 Date Format

<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:

<s:datetimepicker name="todayDate" label="Format (yyyy-MM-dd)" displayFormat="yyyy-MM-dd"/>

generates the date/time picker on the form.

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

Page 8: Struts 2 Date Format

 

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

Page 9: Struts 2 Date Format

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):

package net.roseindia;import com.opensymphony.xwork2.ActionSupport;import java.util.Date;

/** * <p> Validate a user login. </p> */public  class OrderBean  extends ActionSupport {

  private String productName;  private Double productCost;

    public String execute() throws Exception {

      setOrderDate(new Date());      setProductName("ICE Cream");      setProductCost(102.08);      return SUCCESS;

  }

    // ---- Order Date property ----

    /**     * <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) {

9

Page 10: Struts 2 Date Format

        orderDate = value;    }

  public Double getProductCost() {    return productCost;  }

  public void setProductCost(Double productCost) {    this.productCost = productCost;  }

  public String getProductName() {    return productName;  }

  public void setProductName(String productName) {    this.productName = productName;  }

}

The execute method of action class populates Product Name, Product cost and Order date. 

    public String execute() throws Exception {

      setOrderDate(new Date());      setProductName("ICE Cream");      setProductCost(102.08);      return SUCCESS;

     }

Writing JSP page

In the following jsp page (struts2format.jsp) you can view the actual usage of the tag.

<%@ taglib prefix="s" uri="/struts-tags" %><html><head><title>Struts 2 Format Example!</title>

<link href="<s:url value="/css/main.css"/>" rel="stylesheet"type="text/css"/>

</head><body>

<s:form action="Struts2Format" method="POST">

10

Page 11: Struts 2 Date Format

<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.

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:

11

Page 12: Struts 2 Date Format

product.cost= USD {0,number,##0.00}product.orderDate = {0,date,dd-MMM-yyyy}product.name = {0}

So, you can easily define or change the formatting of output just modifying the properties file.

Modification in struts.xml

Add the following line in struts.xml file:

<action name="Struts2Format" class="net.roseindia.OrderBean"><result>/pages/struts2format.jsp</result></action>

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

Page 13: Struts 2 Date Format

[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

Page 14: Struts 2 Date Format

      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

Page 15: Struts 2 Date Format

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.

<%@ taglib prefix="s" uri="/struts-tags" %><html><head><title>File Upload Example</title><link href="<s:url value="/css/main.css"/>" rel="stylesheet" type="text/css"/>

</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>

<s:file name="upload" label="File"/><s:textfield name="caption" label="Caption"/><s:submit /></s:form></body></html>

In the above code the form encrypt type is "multipart/form-data" and <s:file ../> tag renders the html file tag.

File upload success page

Here is the code of file upload(upload-success.jsp) success page.

<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><%@ taglib prefix="s" uri="/struts-tags" %>

15

Page 16: Struts 2 Date Format

<html><head><title>Showcase</title><link href="<s:url value="/css/main.css"/>" rel="stylesheet" type="text/css"/></head>

<body><table class="wwFormTable"><tr>

<td colspan="2"><h1>File Upload Example</h1></td></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>

Adding mapping in struts.xml file

16

Page 17: Struts 2 Date Format

Add the following mapping in the struts.xml file.

<!-- File Upload -->

<action name="showUpload"><result>/pages/upload.jsp</result></action>

<action name="doUpload" class="net.roseindia.StrutsFileUpload"><result name="input">/pages/upload.jsp</result><result>/pages/upload-success.jsp</result></action>

<!-- End File Upload -->

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.

 

17

Page 18: Struts 2 Date Format

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:

INFO: Removing file upload C:\apache-tomcat-6.0.10Struts2\apache-tomcat-6.0.10\work\Catalina\localhost\struts2tutorial\upload__13f532f7_1132e1d4754__8000_00000000.tmp

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:

code snippet from struts.xml 

<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>

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. 

18

Page 19: Struts 2 Date Format

StaticParameter.java

package net.roseindia;import com.opensymphony.xwork2.ActionSupport;import java.util.Date;

public  class StaticParameter  extends ActionSupport {

  private String pramater1;  private String pramater2;  private String pramater3;      public String execute() throws Exception {      return SUCCESS;  }

  public String getPramater1() {    return pramater1;  }

  public void setPramater1(String pramater1) {    this.pramater1 = pramater1;  }

  public String getPramater2() {    return pramater2;  }

  public void setPramater2(String pramater2) {    this.pramater2 = pramater2;  }

  public String getPramater3() {    return pramater3;  }

  public void setPramater3(String pramater3) {    this.pramater3 = pramater3;  }

}

Create a jsp page (showparameters.jsp) to view the static parameters.  

showparameters.jsp

<%@ taglib prefix="s" uri="/struts-tags" %><html>    <head>        <title>Static Parameter Example!</title>    </head>    <body>    <h1>Static Parameter</h1>

19

Page 20: Struts 2 Date Format

    <table border="1" width="25%" bgcolor="#ffffcc">       <tr>      <td width="25%"><b>Key</b></td>      <td width="25%"><b>Value</b></td>      </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>

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

Page 21: Struts 2 Date Format

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. 

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.*;

public class GetSession extends ActionSupport implements SessionAware{

  private Map session;  public String execute() throws Exception{    return SUCCESS;  }

  public void setSession(Map session){    session = this.getSession();  }

  public Map getSession(){

21

Page 22: Struts 2 Date Format

    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.   

GetSession.jsp

<%@ taglib prefix="s" uri="/struts-tags" %><%@page language="java" import="java.util.*" %><html>  <head>    <title>Get Session Example!</title>  </head>  <body>    <h1><span style="background-color: #FFFFcc"> Session Example! </span></h1>    <b>Session:</b><%=session%><br>    <b>Session Context: </b><%=session.getSessionContext() %><br>    <b>Session Time: </b><%=new Date(session.getLastAccessedTime())%>      </body>

</html>

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

Page 23: Struts 2 Date Format

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. 

struts.xml

<action name="AccessRequest" class="net.roseindia.AccessRequest">     <result>/pages/staticparameter/AccessRequest.jsp</result></action>

Now, create a simple action "AccessRequest.java "

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.

23

Page 24: Struts 2 Date Format

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;

public class AccessRequest extends ActionSupport implements                   ServletRequestAware,ServletResponseAware{    private HttpServletRequest request;  private HttpServletResponse response;    public String execute() throws Exception{    return SUCCESS;  }  public void setServletRequest(HttpServletRequest request){    this.request = request;  }

  public HttpServletRequest getServletRequest(){    return request;  }

  public void setServletResponse(HttpServletResponse response){    this.response = response;  }

  public HttpServletResponse getServletResponse(){    return response;  }

}

Finally, create a jsp page for accessing the request and response object. 

AccessRequest.jsp

<%@ taglib prefix="s" uri="/struts-tags" %><%@page language="java" import="java.util.*" %>

<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>

24

Page 25: Struts 2 Date Format

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.

Output of this application:

25