ActionContext
是 Struts2 框架中的一個(gè)核心組件,它封裝了與當(dāng)前請(qǐng)求相關(guān)的所有信息。在處理跨域請(qǐng)求時(shí),可以使用 ActionContext
來(lái)設(shè)置和獲取請(qǐng)求的頭部信息、參數(shù)等。
以下是一個(gè)簡(jiǎn)單的示例,說(shuō)明如何使用 ActionContext
處理跨域請(qǐng)求:
首先,確保你的項(xiàng)目中已經(jīng)引入了 Struts2 相關(guān)的依賴。
在你的 Struts2 動(dòng)作類中,獲取 ActionContext
實(shí)例:
import com.opensymphony.xwork2.ActionContext;
public class MyAction {
public String execute() {
// 獲取 ActionContext 實(shí)例
ActionContext actionContext = ActionContext.getContext();
// ...
}
}
Access-Control-Allow-Origin
:import javax.servlet.http.HttpServletResponse;
public class MyAction {
public String execute() {
// 獲取 ActionContext 實(shí)例
ActionContext actionContext = ActionContext.getContext();
// 獲取 HttpServletResponse 對(duì)象
HttpServletResponse response = (HttpServletResponse) actionContext.get("request").getResponse();
// 設(shè)置跨域請(qǐng)求的頭部信息
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
// ...
}
}
public class MyAction {
public String execute() {
// ...
}
public String options() {
// 獲取 ActionContext 實(shí)例
ActionContext actionContext = ActionContext.getContext();
// 獲取 HttpServletResponse 對(duì)象
HttpServletResponse response = (HttpServletResponse) actionContext.get("request").getResponse();
// 設(shè)置跨域請(qǐng)求的頭部信息
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
// 返回成功響應(yīng)
return "success";
}
}
options
方法:<struts>
<package name="default" extends="struts-default">
<action name="myAction" class="com.example.MyAction">
<interceptor-ref name="defaultStack"></interceptor-ref>
<result name="success">/success.jsp</result>
<result name="input">/input.jsp</result>
<param name="method">options</param>
</action>
</package>
</struts>
現(xiàn)在,當(dāng)客戶端發(fā)起跨域請(qǐng)求時(shí),服務(wù)器會(huì)正確處理并返回相應(yīng)的響應(yīng)。