欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Struts2访问servlet分享

程序员文章站 2023-11-16 22:41:40
一:访问或添加request/session/application属性 复制代码 代码如下:public string scope() throws excep...

一:访问或添加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;

       }

}