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