程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> JSP編程 >> 關於JSP >> Struts2訪問servlet分享

Struts2訪問servlet分享

編輯:關於JSP

一:訪問或添加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>

 

二:獲取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;

       }

}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved