Struts2访问servlet API的方法

1、通过ActionContext类访问
ActionContext是执行时的上下文。上下文可以看作是一个容器,它存放的是Action在执行时需要用到的对象。Action运行期间所用到的数据都保存在ActionContext中。这种方式不能直接过去Servlet API实例,对于Servlet API,可以通过以下方式访问:

ActionContext context = ActionContext.getContext();
context.put("name","faker");    //在request中存放
context.getSession().put("name","faker");   //在session中存放
context.getApplication().put("name","faker");   //在application中存放

2、通过特定的XXXAware接口访问
这种方式能够直接访问servlet API实例
有三种接口:

  • ServletContextAware:实现该接口的Action可直接访问web应用的ServletContext实例
  • ServletRequestAware:实现该接口的Action可直接访问用户请求的ServletRequestContext实例
  • ServletResponseAware:实现该接口的Action可直接访问服务器响应的ServletResponseContext实例
//先实现接口
private HttpServletRequest request;
在方法中request.setAttribute("name","string");

3、通过ServletActionContext类直接访问
ServletActionContext中的方法都是静态的方法,如下:

  • static PageContext getPageContext() //用于访问web应用的PageContext对象,对应JSP的内置对象page
  • static HttpServletRequest getRequest() //用于访问web应用的HttpServletRequest对象
  • static HttpServletResponse getResponse() //用于访问web应用的HttpServletResponse对象
  • static ServletContext getServletCOntext() //用于访问web应用的ServletContext对象
ServletActionContext.getRequest().setAttribute("message","Message");
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值