...
When you create a custom subclass of RealmBase
or GenericPrincipal
and attempt to use those classes in your webapp code, you'll probably have problems with ClassCastException
. This is because the instance returned by request.getUserPrincipal()
is of a class loaded by the server's ClassLoaderclassloader, and you are trying to access it through you webapp's ClassLoaderclassloader. While the classes maybe otherwise exactly the same, different (sibling) ClassLoaders classloaders makes them different classes.
This assumes you created a MyPrincipal
class, and put in Tomcat's server/classes (or lib) directory, as well as in your webapp's webinf/classes (or lib) directory. Normally, you would put custom Realm realm and Principal principal classes in the server directory because they depend on other classes there.
Here's what you would like to do, but it throws ClassCastException
:
No Format |
---|
MyPrincipal p = request.getUserPrincipal();
String emailAddress = p.getEmailAddress();
|
Here are 4 ways you might get around the ClassLoader classloader boundary:
1) Reflection
No Format |
---|
Principal p = request.getUserPrincipal();
String emailAddress = p.getClass().getMethod("getEmailAddress", null).invoke(p, null);
|
2) Move classes to a common ClassLoaderclassloader
You could put your custom classes in a ClassLoader classloader that is common to both the server and your webapp - e.g., either the "common" or bootstrap ClassLoadersclassloaders. To do this, however, you would also need to move the classes that your custom classes depend on up to the common ClassLoaderclassloader, and that seems like a bad idea, because there a many of them and they a core server classes.
...
Rather than move the implementing custom classes up, you could define Interfaces interfaces for your customs classes, and put the interfaces in the common directory. You're code would look like this:
...
Wiki Markup |
---|
You might want to try serializing the response of 'request.getUserPrincipal()' and deserialize it to an instance of \[webapp\]MyPrincipal. |
...