Although STRUTS2 provides the Actioncontex class to access the Servlet API, it is not possible to obtain a Servlet API instance directly, in order to make
STRUTS2 has direct access to an instance of the Servlet API, and STRUTS2 also provides an interface:
Servletcontextaware implements the action for this interface, and can directly access the ServletContext in the Web App
Servletrequestaware implements the action of this interface, which can directly access the user's requested HttpServletRequest
Servletresponseaware implements the action for this interface, and can directly access the HttpServletResponse that responds to user requests
Implementing these interfaces requires only one more method. Implementing the Servletrequestaware interface requires implementing the public Setsetbletrequestaware (HttpServletRequest request). This method has a parameter httpservletrequest, which represents the user's request. Setsetbletrequestaware accesses the Servlet object in action by accessing the request object for the Web app and setting the object to the member property of the action, HttpServletRequest.
Examples are as follows:
Package com;
Import Javax.servlet.http.HttpServletRequest;
Import Org.apache.struts2.interceptor.ServletRequestAware;
Import Com.opensymphony.xwork2.ActionSupport;
public class Loginaction extends Actionsupport implements servletrequestaware{
private HttpServletRequest request;
@Override
Public String Execute () throws Exception {
Request.setattribute ("Success", "Walking in the Sun");
return SUCCESS;
}
@Override
public void Setservletrequest (HttpServletRequest request) {
This.request=request;
}
}
success.jsp output
<%@ page language= "java" import= "java.util.*" pageencoding= "Iso-8859-1"%>
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >
<body>
${requestscope.success}
</body>
Implementing the Xxxaware interface to directly access the servlet API