简体   繁体   中英

How to configure programatically the session tracking modes for Tomcat

I'm using an embedded tomcat server version 7. I want to programmatically configure the server with the session tracking mode (in fact I search a way to get rid of jsessionid ie neither in the cookies nor in the url). But there is no a method in org.apache.catalina.Context to simply configure this property like in a web.xml descriptor file (I cannot use such file). So what is the best way to do it?

I tried the above code

Context ctxt = tomcat.addWebapp(.......);
ctxt.getServletContext().setSessionTrackingModes(
        my_modes);

But this method failed with the error

java.lang.IllegalStateException: The session tracking modes for context / cannot be set whilst the context is running
at org.apache.catalina.core.ApplicationContext.setSessionTrackingModes(ApplicationContext.java:1235)
at org.apache.catalina.core.ApplicationContextFacade.setSessionTrackingModes(ApplicationContextFacade.java:611)

I tried to use https://tomcat.apache.org/tomcat-7.0-doc/api/org/apache/catalina/Context.html#addApplicationListener(java.lang.String) . The listener on contextInitialized set the tracking mode

servletContextEvent.getServletContext().setSessionTrackingModes(
        EnumSet.copyOf(sessionTrackingModes));

But I don't know how to configure tomcat with an instance of this listener because with the last method Context.addApplicationListener the method takes the className of the listener and when running the server fails to instantiate my listener because the absence of an empty constructor (my listener constructor takes the list of sessionTrackingMode.. cannot be configurable)

[read-1] ERROR Aug 18 19:10:03 - Error configuring application listener of class xx.xx.xx.SessionTrackingListener
java.lang.InstantiationException: xx.xx.xx.SessionTrackingListener
at java.lang.Class.newInstance(Class.java:427)
at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:125)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4715)
..............
Caused by: java.lang.NoSuchMethodException: xx.xx.xx.xx.SessionTrackingListener.<init>()
at java.lang.Class.getConstructor0(Class.java:3082)
at java.lang.Class.newInstance(Class.java:412)

So do you suggest a better way to do it

Use a SessionTrackingListener. The problem with the one you are using is that it doesn't have a default constructor. It should work if you add a default constructor to it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM