How to access the response object in struts2 action class?
In Struts2, you can obtain the response object by implementing the ServletResponseAware interface in the Servlet API. The specific steps are as follows:
- Create an Action class and implement the ServletResponseAware interface.
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.interceptor.ServletResponseAware;
public class MyAction implements ServletResponseAware {
private HttpServletResponse response;
@Override
public void setServletResponse(HttpServletResponse response) {
this.response = response;
}
// 在需要使用response对象的方法中,可以直接使用this.response来获取response对象
public String execute() {
// 使用response对象的方法
response.setContentType("text/html");
// ...
return "success";
}
}
- Configure the struts.xml configuration file for Struts2 to make the Action class accessible as an Action.
<struts>
<package name="default" namespace="/" extends="struts-default">
<action name="myAction" class="com.example.MyAction">
<result>/success.jsp</result>
</action>
</package>
</struts>
- Call Action in JSP page.
<%@ taglib prefix="s" uri="/struts-tags" %>
<s:form action="myAction">
<s:submit value="Submit" />
</s:form>
In the above example, when the user clicks the Submit button, it will trigger the execute() method corresponding to myAction, allowing the response object to be retrieved and further actions to be taken.