struts之Action中獲取request、response物件的方法

NO IMAGE


struts之Action中獲取request、response物件的方法

1、訪問或新增request/session/application屬性

public String scope() throws Exception{

    ActionContext ctx = ActionContext.getContext();

    ctx.getApplication().put(“app”, “應用範圍”);//往ServletContext裡放入app

    ctx.getSession().put(“ses”, “session範圍”);//往session裡放入ses

    ctx.put(“req”, “request範圍”);//往request裡放入req

    return “scope”;

}

JSP:

<body>

    ${applicationScope.app} <br>

    ${sessionScope.ses}<br>

    ${requestScope.req}<br>

</body>

                   

2、獲取HttpServletRequest/HttpSession/ServletContext/HttpServletResponse物件

方法一、通過ServletActionContext類直接獲取:

public String rsa() throws Exception{

    HttpServletRequest request = ServletActionContext.getRequest();

    ServletContext servletContext = ServletActionContext.getServletContext();

    request.getSession();

    HttpServletResponse response = ServletActionContext.getResponse();

     return “scope”;

}

方法二、實現指定介面,由struts框架執行時注入:

public class HelloWorldAction implements ServletRequestAware, ServletResponseAware, ServletContextAware{

    private HttpServletRequest request;

    private ServletContext servletContext;

    private HttpServletResponse response;

    public void setServletRequest(HttpServletRequest req) {

        this.request=req;

    }

    public void setServletResponse(HttpServletResponse res) {

        this.response=res;

    }

    public void setServletContext(ServletContext ser) {

        this.servletContext=ser;

    }

}

           

程式碼

按 Ctrl C 複製程式碼

按 Ctrl C 複製程式碼