ActionContext如何處理跨域請(qǐng)求

小樊
81
2024-10-10 06:16:47

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)求:

  1. 首先,確保你的項(xiàng)目中已經(jīng)引入了 Struts2 相關(guān)的依賴。

  2. 在你的 Struts2 動(dòng)作類中,獲取 ActionContext 實(shí)例:

import com.opensymphony.xwork2.ActionContext;

public class MyAction {
    public String execute() {
        // 獲取 ActionContext 實(shí)例
        ActionContext actionContext = ActionContext.getContext();

        // ...
    }
}
  1. 設(shè)置跨域請(qǐng)求的頭部信息。例如,設(shè)置 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");

        // ...
    }
}
  1. 如果需要處理預(yù)檢請(qǐng)求(OPTIONS 請(qǐng)求),可以在動(dòng)作類中添加一個(gè)處理預(yù)檢請(qǐng)求的方法:
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";
    }
}
  1. 配置 Struts2 動(dòng)作映射,將預(yù)檢請(qǐng)求映射到 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)。

0