In the Execute method of the Struts1.x action class, there are four parameters, of which two are response and request. In Struts2, there are no arguments, so you can't simply get HttpServletResponse or HttpServletRequest objects from the Execute method.
However, there are still many ways to get these objects in the Struts2 action class. Here's a list of four ways to get these objects.
"Method 1" using the Struts2 Aware interceptor
This method requires the action class to implement the appropriate interceptor interface. If we want to get the HttpServletResponse object, we need to implement the Org.apache.struts2.interceptor.ServletResponseAware interface, the code is as follows:
Package action;
Import Com.opensymphony.xwork2.ActionSupport;
Import javax.servlet.http.*;
Import org.apache.struts2.interceptor.*;
public class Myaction extends Actionsupport implements Servletresponseaware
{
private Javax.servlet.http.HttpServletResponse response;
Gets the HttpServletResponse object public
void Setservletresponse (httpservletresponse response)
{
This.response = response;
}
Public String Execute () throws Exception
{
response.getwriter (). Write ("Implement Servletresponseaware Interface");
}
In the above code, Myaction implements a Servletresponseaware interface and implements the Setservletresponse method. If an action class implements the Servletresponseaware interface, Struts2 invokes the Setservletresponse method before calling the Execute method and passes the response parameter to the method. If you want to get objects such as HttpServletRequest, httpsession, and cookies, the action class can implement interfaces such as Servletrequestaware, Sessionaware, and Cookiesaware, respectively. These interfaces are in the Org.apache.struts2.interceptor package.
If you want to get the request parameters, the action class can implement Org.apache.struts2.interceptor. Parameteraware interface, but you can also implement Com.opensymphony.xwork2.interceptor if you only want to determine whether a parameter exists. Parameternameaware interface. This interface has a Acceptableparametername method, which is called once when the STRUTS2 obtains a request parameter. The reader can record all of the request parameters in this method for later use. This method is defined as follows:
boolean acceptableParameterName(String parameterName);