We want to split a working application in two different .war files in order to be able to update one app without affecting the other. Each webapp will have different a UI, different users and different deploy schedule.
The easiest path seems to be sharing the same session, so if app A set session.setAttribute("foo", "bar") app B will be able to see it.
Is there a way to share the HttpSession state for both apps in the same Tomcat instance?
Our app is running on a dedicated Tomcat 5.5, there are no other apps running on the same tomcat instance, so any security concerns regarding the session sharing are not a problem. We're running multiple Tomcat instances, but the balancer is using sticky sessions.
If it's not possible or this session sharing is a really bad idea please leave a comment.
You should not share HttpSession; but you can share other objects. For example, you can register an object via JNDI and access the same object in all your apps (databases use this to pool connections).
One thing to be aware of is that two web apps will use different classloaders. If you want to share objects, they need to use the same version of the class from the same classloader (or else you will get LinkageErrors). That means either putting them in a classloader shared by both web apps (system classpath for example) OR using serialization to effectively drain and reconstitute the object in the right classloader with the correct version of the class.
If you want to use Spring, there's a project called Spring Session:
https://github.com/spring-projects/spring-session
Quoting: "HttpSession - allows replacing the HttpSession in an application container (i.e. Tomcat) neutral way"
For Tomcat 8 I use the following configuration to share a session across 2 webapps:
conf/context.xml
<Context sessionCookiePath="/">
<Valve className="org.apache.catalina.valves.PersistentValve"/>
<Manager className="org.apache.catalina.session.PersistentManager">
<Store className="org.apache.catalina.session.FileStore" directory="${catalina.base}/temp/sessions"/>
</Manager>
...
</Context>
I deploy the same simple webapp twice log.war and log2.war:
/log
/log2
I can now log-in to /log and have the user displayed in /log2, this does not work with the tomcat default configuration.
The session value is set and read:
HttpSession session=request.getSession();
session.setAttribute("name",name);
HttpSession session=request.getSession(false);
String name=(String)session.getAttribute("name");
I used this project as example: https://www.javatpoint.com/servlet-http-session-login-and-logout-example
Most examples/solutions use a in-memory database which requires more setup work:
redis
hazelcast
If the two webapps are so closely coupled that they need to share objects, why are you splitting it in two? Even if you manage them somewhat independently any decent build management system should be able to create a single WAR file for deployment.
A solution like Aaron suggest with JNDI will work, but only if both webapps are running on the same server. If the units are tightly coupled and you are going to be running it on the same server anyway ... might as well have a single WAR.
If you really do want them to stand independently I'd seriously examine the data exchange between the two. Ideally you'd want them to only share relevant data with one another. This data could be passed back and forth via POST (or GET if more appropriate) parameters, you might even consider using cookies.
One way of doing this is described in this blog post: Session sharing in Apache Tomcat
Summary: Add emptySessionPath to the Connector configuration and crossContext to the Context
redison download
conf/context.xml
<Context sessionCookiePath="/">
...
<Manager className="org.redisson.tomcat.RedissonSessionManager"
configPath="${catalina.base}/conf/redisson.yaml"
readMode="REDIS" />
</Context>
conf/redisson.yaml
singleServerConfig:
address: "redis://<host>:6379"
sessionCookiePath="/" makes Tomcat use the same session id for different web apps.
RedissonSessionManager makes session to be persisted in 'shared space'
I was not able to achieve desired result with org.apache.catalina.session.FileStore PersistentManager in shared context.xml, I faced issues with session deserialization in background expiration monitor thread. It failed to deseriazile the session because it was using common classloader without webapp serializable models in classpath. Theoretically PersistentManager could be configured for each web app separately (to have proper classpath) in WEB-INF/context.xml but I failed to make it work.
org.apache.catalina.session.JDBCStore PersistentManage was promising because it expose last_access column for the session so it is not required to deserialize session_data, but it was saving app_name all the time causing same session id to be written as different rows for diffrent web apps. Thus session data was not stored in the shared place.
Spring Session has it`s own way to create session id. I was not able to find solution to force Spring Session to create same session id for different web apps.
Solution with core tomcat session id generation (with ability to generate the same for different web apps and RedissonSessionManager, which store data using session id as the only key and has it's own expiration mechanism) finally worked for me. The solution works perfectly with #SessionScope spring beans.
You can do by taking servlet context by your context root.
For retrieving variable.
request.getSession().getServletContext().getContext("/{applicationContextRoot}").getAttribute(variableName)
For setting variable:
request.getSession().getServletContext().getContext("/{applicationContextRoot}").setAttribute(variableName,variableValue)
Note: Both the applications should deployed in the same server.
Pls let me know if you find any problem
Tomcat 8 :
i had to do : <Context crossContext="true" sessionCookiePath="/"> in conf/context.xml
more details on config attributes here
and then to set the value(like #Qazi's answer):
ServletContext servletContext =request.getSession().getServletContext().getContext("contextPath")
servletContext.setAttribute(variableName,variableValue)
to get the value:
ServletContext servletContext =request.getSession().getServletContext().getContext("contextPath")
servletContext.getAttribute("user");
I developed session state server for tomcat using python.
Due to this I don't need to change the code already written for creating/accessing and destroying session. Also as there is separate server/service which is handling and storing session so not master cluster is needed. There is no session replication (as in tomcat clustering) in this case, rather this is session sharing between web farming.
You should not split your app that way in order by have high availability. You could deploy the whole app on many tomcat instances.
Related
My goal is to have 2 different tomcat servers that run the same web-application and be using the same DB,
I'm using spring + JPA with MySQL DB.
Is this a straight forward practice? can i just deploy and start-up both tomcats?
OR - is there any preliminary configuring to do? (i.e Do i have to configure JPA in both apps to be synchronized with each other? etc..)
EDIT - we are going to use HA-Proxy as a load balancer.
regards,
The simplest way is to configure your load balancer to point one user always to the same Tomcat instance. Otherwise, if your load balancer will point randomly for each request, you will have problems with sessions. By default one Tomcat won't be able to share session with another. In the other hand, you can configure your Tomcats to replicate sessions between nodes or use common session store. There are at least few ways to do that.
I'm reading up on JMX for the first time, and trying to see if its a feasible solution to a problem we're having on production.
We have an architecture that is constantly hitting a remote web service (managed by a different team on their own servers) and requesting data from it (we also cache from this service, but its a sticky problem where caching isn't extremely effective).
We'd like the ability to dynamically turn logging on/off at one specific point in the code, right before we hit the web service, where we can see the exact URLs/queries we're sending to the service. If we just blindly set a logging level and logged all web service requests, we'd have astronomically-large log files.
JMX seems to be the solution, where we control the logging in this section with a managed bean, and then can set that bean's state (setLoggingEnabled(boolean), etc.) remotely via some manager (probably just basic HTML adaptor).
My questions are all deployment-related:
If I write the MBean interface and impl, as well as the agent (which register MBeans and the HTML adaptor with the platform MBean server), do I compile, package & deploy those inside my main web application (WAR), or do they have to compile to their own, say, JAR and sit on the JVM beside my application?
We have a Dev, QA, Demo and Prod envrionment; is it possible to have 1 single HTML adaptor pointing to an MBean server which has different MBeans registered to it, 1 for each environment? It would be nice to have one URL to go to where you can manage beans in different environments
If the answer to my first question above is that the MBean interface, impl and agent all deploy inside your application, then is it possible to have your JMX-enabled application deployed on one server (say, Demo), but to monitor it from another server?
Thanks in advance!
How you package the MBeans is in great part a matter of portability. Will these specific services have any realistic usefulness outside the scope of this webapp ? If not, I would simply declare your webapp "JMX Manageable" and build it in. Otherwise, componentize the MBeans, put them in a jar, put the jar in the WEB-INF/lib and initialize them using a startup servlet configured in your web.xml.
For the single HTML adaptor, yes it is possible. Think of it as having Dev, QA, Demo and Prod MBeanServers, and then one Master MBeanServer. Your HTML Adaptor should render the master. Then you can use the OpenDMK cascading service to register cascades of Dev, QA, Demo and Prod in the Master. Now you will see all 5 MBeanServer's beans in the HTML adaptor display.
Does that answer your third question ?
JMX is a technology used for remote management of your application and for a situation for example when you want to change a configuration without a restart is the most proper use.
But in your case, I don't see why you would need JMX. For example if you use Log4j for your logging you could configure a file watchdog and just change logging to the lowest possible level. I.e. to debug. This does not require a restart and IMHO that should have been your initial design in the first place i.e. work arround loggers and levels. Right now, it is not clear what you mean and what happens with setLoggingEnable.
In any case, the managed bean is supposed to be deployed with your application and if you are using Spring you are in luck since it offers a really nice integration with JMX and you could deploy your spring beans as managed beans.
Finally when you connect to your process you will see the managed beans running for that JVM. So I am not sure what exactly you mean with point 2.
Anyway I hope this helps a little
Is there any way to share data between to JSP applications using Tomcat 5.5?
The applications are running in the same server.
The shared data should not persist in the system for many time and cannot be stored in cookies because it's bigger than 4Kb.
Thanks!
:)
Just put the data in a file on the disk file system or a database server which both have access to.
Update: as per the update and the comments, the functional requirement seems to boil down to let the webapps on the same server share the same HttpSession (including all of its attributes). In that case, you need to set the emptySessionPath attribute of the <Connector> element in Tomcat's /conf/server.xml to true.
<Connector emptySessionPath="true">
You could look at the crossContext attribute to allow you to share data via the context object. Previous Stackoverflow here:
What does the crossContext attribute do in Tomcat? Does it enable session sharing?
In case of SaaS applications, where the same server plays host to multiple applications. How are session attributes maintained? To elaborate the question:
AppA, and AppB are hosted on the same machine, I now create UserA for AppA and UserB for AppB. AppA and AppB belong to different organizations so they are not linked. Some details about the user are stored at http session level (until the session times out). So now if I log in to both AppA and AppB from the same browser using different tabs, I may end up seeing some of UserA/AppA details on the UserB/AppB screen or vice-versa. How can such a problem be solved?
One solution I can think is to create subdomains like appa.example.org and appb.example.org. Is there any other/better way?
Normally you will not see details from one app in another app.
When a session is created it is created inside the web application and identified by a key. This session-id is what is stored in a cookie or passed in some other way to identify which session object to refer to on the next request.
If you would present this session id to another webapp it won't find the attributes because they live in the other webapp.
Now, that is 'normally'. In practice this can be configured in all directions, like storing all atributes in the cookie (very useful in extreme failover scenarios), storing the session in a shared memcached layer or shared database table (then you would get the same object back in the other application of course), and so on, and so on.
The best solution I've come up with was inspired by this question. I've pointed multiple contexts to the same war file:
<Service ...>
<Engine ...>
<Host ... autoDeploy="false">
<Context docBase="myapp.war" path="/tenant1"/>
<Context docBase="myapp.war" path="/tenant2"/>
</Host>
</Engine>
</Service>
This is essentially the same as making copies of myapp.war called tenant1.war, tenant2.war, etc. Each tenant is technically running thier own webapp, even though they're all running the same code.
If you have users with credentials on two or more tenants, they can log on to both at the same time, and each webapp will get its own session, because the JSESSIONID cookies containing the session ID are each tied to a specific context path.
There are drawbacks to this approach. For one, all the classes in the war file get reloaded for each tenant, so I'll have to keep an eye on PermGen space. For another, I'll have to edit server.xml every time a new tenant comes along. Have you found a better solution?
We want to split a working application in two different .war files in order to be able to update one app without affecting the other. Each webapp will have different a UI, different users and different deploy schedule.
The easiest path seems to be sharing the same session, so if app A set session.setAttribute("foo", "bar") app B will be able to see it.
Is there a way to share the HttpSession state for both apps in the same Tomcat instance?
Our app is running on a dedicated Tomcat 5.5, there are no other apps running on the same tomcat instance, so any security concerns regarding the session sharing are not a problem. We're running multiple Tomcat instances, but the balancer is using sticky sessions.
If it's not possible or this session sharing is a really bad idea please leave a comment.
You should not share HttpSession; but you can share other objects. For example, you can register an object via JNDI and access the same object in all your apps (databases use this to pool connections).
One thing to be aware of is that two web apps will use different classloaders. If you want to share objects, they need to use the same version of the class from the same classloader (or else you will get LinkageErrors). That means either putting them in a classloader shared by both web apps (system classpath for example) OR using serialization to effectively drain and reconstitute the object in the right classloader with the correct version of the class.
If you want to use Spring, there's a project called Spring Session:
https://github.com/spring-projects/spring-session
Quoting: "HttpSession - allows replacing the HttpSession in an application container (i.e. Tomcat) neutral way"
For Tomcat 8 I use the following configuration to share a session across 2 webapps:
conf/context.xml
<Context sessionCookiePath="/">
<Valve className="org.apache.catalina.valves.PersistentValve"/>
<Manager className="org.apache.catalina.session.PersistentManager">
<Store className="org.apache.catalina.session.FileStore" directory="${catalina.base}/temp/sessions"/>
</Manager>
...
</Context>
I deploy the same simple webapp twice log.war and log2.war:
/log
/log2
I can now log-in to /log and have the user displayed in /log2, this does not work with the tomcat default configuration.
The session value is set and read:
HttpSession session=request.getSession();
session.setAttribute("name",name);
HttpSession session=request.getSession(false);
String name=(String)session.getAttribute("name");
I used this project as example: https://www.javatpoint.com/servlet-http-session-login-and-logout-example
Most examples/solutions use a in-memory database which requires more setup work:
redis
hazelcast
If the two webapps are so closely coupled that they need to share objects, why are you splitting it in two? Even if you manage them somewhat independently any decent build management system should be able to create a single WAR file for deployment.
A solution like Aaron suggest with JNDI will work, but only if both webapps are running on the same server. If the units are tightly coupled and you are going to be running it on the same server anyway ... might as well have a single WAR.
If you really do want them to stand independently I'd seriously examine the data exchange between the two. Ideally you'd want them to only share relevant data with one another. This data could be passed back and forth via POST (or GET if more appropriate) parameters, you might even consider using cookies.
One way of doing this is described in this blog post: Session sharing in Apache Tomcat
Summary: Add emptySessionPath to the Connector configuration and crossContext to the Context
redison download
conf/context.xml
<Context sessionCookiePath="/">
...
<Manager className="org.redisson.tomcat.RedissonSessionManager"
configPath="${catalina.base}/conf/redisson.yaml"
readMode="REDIS" />
</Context>
conf/redisson.yaml
singleServerConfig:
address: "redis://<host>:6379"
sessionCookiePath="/" makes Tomcat use the same session id for different web apps.
RedissonSessionManager makes session to be persisted in 'shared space'
I was not able to achieve desired result with org.apache.catalina.session.FileStore PersistentManager in shared context.xml, I faced issues with session deserialization in background expiration monitor thread. It failed to deseriazile the session because it was using common classloader without webapp serializable models in classpath. Theoretically PersistentManager could be configured for each web app separately (to have proper classpath) in WEB-INF/context.xml but I failed to make it work.
org.apache.catalina.session.JDBCStore PersistentManage was promising because it expose last_access column for the session so it is not required to deserialize session_data, but it was saving app_name all the time causing same session id to be written as different rows for diffrent web apps. Thus session data was not stored in the shared place.
Spring Session has it`s own way to create session id. I was not able to find solution to force Spring Session to create same session id for different web apps.
Solution with core tomcat session id generation (with ability to generate the same for different web apps and RedissonSessionManager, which store data using session id as the only key and has it's own expiration mechanism) finally worked for me. The solution works perfectly with #SessionScope spring beans.
You can do by taking servlet context by your context root.
For retrieving variable.
request.getSession().getServletContext().getContext("/{applicationContextRoot}").getAttribute(variableName)
For setting variable:
request.getSession().getServletContext().getContext("/{applicationContextRoot}").setAttribute(variableName,variableValue)
Note: Both the applications should deployed in the same server.
Pls let me know if you find any problem
Tomcat 8 :
i had to do : <Context crossContext="true" sessionCookiePath="/"> in conf/context.xml
more details on config attributes here
and then to set the value(like #Qazi's answer):
ServletContext servletContext =request.getSession().getServletContext().getContext("contextPath")
servletContext.setAttribute(variableName,variableValue)
to get the value:
ServletContext servletContext =request.getSession().getServletContext().getContext("contextPath")
servletContext.getAttribute("user");
I developed session state server for tomcat using python.
Due to this I don't need to change the code already written for creating/accessing and destroying session. Also as there is separate server/service which is handling and storing session so not master cluster is needed. There is no session replication (as in tomcat clustering) in this case, rather this is session sharing between web farming.
You should not split your app that way in order by have high availability. You could deploy the whole app on many tomcat instances.