【學習筆記15】訪問或添加幾個屬性

1、訪問或添加request/session/application屬性:
Action:
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
   //System.out.println("servletContext.getAttribute : " + (String) (ctx.getApplication().get("app")));
   return "scope";
}
JSP:
${applicationScope.app}<br>
${sessionScope.ses}<br>
${requestScope.req}<br>

2、獲取HttpServletRequest / HttpSession / ServletContext / HttpServletResponse對象:
方法1,經過ServletActionContext類直接獲取:
public String rsa() throws Exception{
  HttpServletRequest request = ServletActionContext.getRequest();
  ServletContext servletContext = ServletActionContext.getServletContext();
  HttpServletResponse response = ServletActionContext.getResponse();
  HttpSession session = request.getSession();
  return "scope";
}
方法2,實現指定接口, 由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;
  }
}


(本學習筆記是根據傳智播客的視頻教程整理而來) html

相關文章
相關標籤/搜索