[英]How can I share a variable or object between two or more Servlets?
我想知道是否有某种方式可以在两个或多个Servlet之间共享变量或对象,我的意思是某种“标准”方式。 我认为这不是一个好习惯,但是是构建原型的更简单方法。
我不知道这是否取决于所使用的技术,但我将使用Tomcat 5.5
我想共享一个简单类的对象的Vector(仅公共属性,字符串,int等)。 我的意图是在数据库中拥有一个静态数据,显然,当Tomcat停止时,它将丢失。 (仅用于测试)
我认为您在这里寻找的是请求,会话或应用程序数据。
在servlet中,您可以将对象作为属性添加到请求对象,会话对象或servlet上下文对象中:
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
String shared = "shared";
request.setAttribute("sharedId", shared); // add to request
request.getSession().setAttribute("sharedId", shared); // add to session
this.getServletConfig().getServletContext().setAttribute("sharedId", shared); // add to application context
request.getRequestDispatcher("/URLofOtherServlet").forward(request, response);
}
如果将其放在请求对象中,它将对转发到的Servlet可用,直到请求完成:
request.getAttribute("sharedId");
如果将其放在会话中,则以后的所有servlet都可以使用它,但是该值将绑定到用户:
request.getSession().getAttribute("sharedId");
直到会话根据用户的不活动状态而到期。
已由您重置:
request.getSession().invalidate();
或者一个servlet从范围中删除它:
request.getSession().removeAttribute("sharedId");
如果将其放在servlet上下文中,则在应用程序运行时将可用:
this.getServletConfig().getServletContext().getAttribute("sharedId");
直到将其删除:
this.getServletConfig().getServletContext().removeAttribute("sharedId");
将其放在3个不同范围之一中。
请求-持续请求的生命
session-持续用户会话的生命
应用程序-持续到应用程序关闭为止
您可以通过传递给从HttpServlet类扩展的方法的HttpServletRequest变量访问所有这些作用域。
取决于数据的预期用途范围。
如果仅按用户使用数据,例如用户登录信息,页面点击计数等,请使用会话对象(httpServletRequest.getSession()。get / setAttribute(String [,Object]))
如果多个用户的数据相同(总网页访问量,辅助线程等),请使用ServletContext属性。 servlet.getServletCongfig()。getServletContext()。get / setAttribute(String [,Object]))。 这仅在相同的war文件/网络应用程序中有效。 请注意,该数据也不会在重新启动后持续存在。
另一种选择是在上下文之间共享数据...
<Context path="/myApp1" docBase="myApp1" crossContext="true"/>
<Context path="/myApp2" docBase="myApp2" crossContext="true"/>
在myApp1上:
ServletContext sc = getServletContext();
sc.setAttribute("attribute", "value");
在myApp2上:
ServletContext sc = getServletContext("/myApp1");
String anwser = (String)sc.getAttribute("attribute");
您不能只是将对象放在HttpSession中,然后在每个servlet中通过其属性名称来引用它吗?
例如:
getSession().setAttribute("thing", object);
...然后在另一个servlet中:
Object obj = getSession.getAttribute("thing");
这就是我如何用Jetty做到这一点。
https://stackoverflow.com/a/46968645/1287091
使用服务器上下文,在该上下文中,在嵌入式Jetty服务器启动期间写入单例,并在服务器的整个生命周期内在所有Web应用程序之间共享。 假设上下文只有一个编写者,也可以用于在Web应用之间共享对象/数据-否则,您需要注意并发性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.