Struts2访问servlet分享

编程学习 2021-07-05 11:23www.dzhlxh.cn编程入门
Struts2访问servlet分享

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

       }

}

Copyright © 2016-2025 www.dzhlxh.cn 金源码 版权所有 Power by

网站模板下载|网络推广|微博营销|seo优化|视频营销|网络营销|微信营销|网站建设|织梦模板|小程序模板