问题描述
我有一个 ldap 服务器,用于在 tomcat web 应用程序中对用户进行身份验证.我正在使用 jndirealm,它是在上下文文件中配置的,效果很好.
i have an ldap server that i'm using to authenticate users within a tomcat web application. i'm using the jndirealm and it's configured within a context file and this works great.
我还需要在 ldap 中搜索用户信息.我已经想出了如何使用jndi 方法"来做到这一点,并且通过使用哈希表创建我自己的 jndi 上下文,我让它在 tomcat 之外正常工作.但是,我不想在代码中配置 jndi 属性,而是想在 realm 配置旁边的上下文文件中创建一个 jndi rsource.
i'll also need to search the ldap for user information. i've figured out how to do this with the "jndi method" and i have it working fine outside of tomcat by creating my own jndi context using a hashtable. however, instead of configuring the jndi properties in code, i'd like to create a jndi rsource in my context file right next to the realm configuration.
我想我会做这样的事情:
i'm thinking i would do something like this:
但是要么 tomcat 告诉我无法创建资源,要么当我尝试使用以下内容对其进行初始化时:
but either tomcat tells me the resource can't be created or when i try to initialize it with something like this:
context initctx = new initialcontext(); dircontext ctx = (dircontext) initctx.lookup("java:comp/env/ldap");
tomcat 告诉我无法创建资源实例".我还在 web.xml 文件中添加了正确的资源引用,所以我认为这不是问题.
tomcat tells me the "cannot create resource instance". i've also added the correct resource-ref in my web.xml file, so i don't think that's the problem.
由于 ldap 与 jndi 方法一起使用,我假设它应该能够配置为资源,对吧?我错过了什么?
since ldap is being used with the jndi method i'm assuming it should be able to be configured as a resource, right? what am i missing?
推荐答案
这个答案有点晚了,但可能对其他用户有用.它基于 ejp 的回答.
this answer is a bit late, but probably it'll be useful for other users. it's based on ejp's answer.
以下百家乐凯发k8的解决方案已在 apache tomcat 7 上进行了测试.
如果需要,可以替换 ldapcontext 与 dircontext.
the following solution was tested on apache tomcat 7.
if you need, you can replace ldapcontext with dircontext.
创建一个实现 objectfactory 实例化一个 ldapcontext:
create a class which implements objectfactory to instantiate a ldapcontext:
public class ldapcontextfactory implements objectfactory {
public object getobjectinstance(object obj, name name, context namectx,
hashtable environment) throws exception {
hashtable
定义你的资源
将以下内容添加到您的 context.xml,引用工厂并定义值以创建 ldapcontext 实例:
define your resource
add the following to your context.xml, referencing the factory and defining the values to create a ldapcontext instance:
...
如果您需要为资源添加更多属性/值,请考虑更新您的 objectfactory 上面创建的用于读取这些新属性/值.
if you need to add more attributes/values to your resource, consider updating your objectfactory created above to read these new attributes/values.
在你需要的地方注入你的资源:
inject your resource wherever you need:
@resource(name = "ldap/ldapresource")
private ldapcontext bean;
或者查一下:
context initialcontext = new initialcontext();
ldapcontext ldapcontext = (ldapcontext)
initialcontext.lookup("java:comp/env/ldap/ldapresource");
查看更多
apache tomcat 的文档解释了如何添加自定义资源工厂.