struts2如何获取Request-Session-ServletContext-Response

1. 访问和添加request/session/application属性
如果只是往request/session/application中设置属性,可以用下面的方式

Java代码 复制代码收藏代码struts2如何获取Request-Session-ServletContext-Response - KingViker - KingViker的博客
ActionContextctx=ActionContext.getContext();
ctx.getApplication().put("app","应用范围");//往ServletContext里放入app
ctx.getSession().put("ses","session范围");//往session里放入ses
ctx.put("req","request范围");//往request里放入req
ctx.put("names",Arrays.asList("老张","老黎","老方"));

  ActionContext ctx = ActionContext.getContext();    ctx.getApplication().put("app", "应用范围");//往ServletContext里放入app    ctx.getSession().put("ses", "session范围");//往session里放入ses    ctx.put("req", "request范围");//往request里放入req    ctx.put("names", Arrays.asList("老张", "老黎", "老方"));     

jsp页面上获取方式

Java代码 复制代码收藏代码struts2如何获取Request-Session-ServletContext-Response - KingViker - KingViker的博客
${applicationScope.app}<br>
${sessionScope.ses}<br>
${requestScope.req}<br>

 ${applicationScope.app}<br>      ${sessionScope.ses}<br>      ${requestScope.req}<br>

2. struts2中如何获取httpServletRequest/HttpSession/ServletContext/HttpServletResponse对象
方法一,通过ServletActionContext类获取:(推介使用)

Java代码 复制代码收藏代码struts2如何获取Request-Session-ServletContext-Response - KingViker - KingViker的博客
publicStringrsa()throwsException{
HttpServletRequestrequest=ServletActionContext.getRequest();
ServletContextservletContext=ServletActionContext.getServletContext();
request.setAttribute("req","请求范围属性");
request.getSession().setAttribute("ses","会话范围属性");
servletContext.setAttribute("app","应用范围属性");
HttpServletResponseresponse=ServletActionContext.getResponse();
return"message";
}

  public String rsa() throws Exception{    HttpServletRequest request = ServletActionContext.getRequest();    ServletContext servletContext = ServletActionContext.getServletContext();    request.setAttribute("req", "请求范围属性");    request.getSession().setAttribute("ses", "会话范围属性");    servletContext.setAttribute("app", "应用范围属性");    HttpServletResponse response = ServletActionContext.getResponse();    return "message";   }

方法二,实现指定接口,由struts框架注入:
Java代码 复制代码收藏代码struts2如何获取Request-Session-ServletContext-Response - KingViker - KingViker的博客
importcom.opensymphony.xwork2.ActionContext;
publicclassHelloWorldAction2implementsServletContextAware,ServletRequestAware,ServletResponseAware{
privateHttpServletRequestrequest;
privateHttpServletResponseresponse;
privateServletContextservletContext;
publicvoidsetServletContext(ServletContextcontext){
//context对象不是应用程序传进去的,而是由struts框架自动注入的
this.servletContext=context;
}
publicvoidsetServletRequest(HttpServletRequestrequest){
this.request=request;
}
publicvoidsetServletResponse(HttpServletResponseresponse){
this.response=response;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值