jndi简单运用之weblogic

Main.java

package weblogic;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
public class Main {
	public static void main(String[] args) throws Exception {
		bind("object","This is a object.");
		
		System.out.println(getResource("object"));
	}
	// get the resource of the specified name
	private static Object getResource(String jndiName) throws Exception{
		Properties jndiConfig=getJndiConfig();
		Context context = new InitialContext(jndiConfig);
		Object resource=context.lookup(jndiName);
		context.close();
		return resource;
	}
	// bind a object to the specified name
	private static void bind(String jndiName,Object object) throws Exception{
		Properties jndiConfig=getJndiConfig();
		Context context = new InitialContext(jndiConfig);
		context.bind(jndiName, object);
		context.close();
	}
	// get the configuration properties
	private static Properties getJndiConfig(){
		String initialContextFactory="weblogic.jndi.WLInitialContextFactory";
		String providerUrl="t3://localhost:8888";
		String securityPrincipal="weblogic";
		String securityCredentials="password";
		Properties jndiConfig=new Properties();
		jndiConfig.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);
		jndiConfig.put(Context.PROVIDER_URL, providerUrl);
//		jndiConfig.put(Context.SECURITY_PRINCIPAL, securityPrincipal);
//		jndiConfig.put(Context.SECURITY_CREDENTIALS, securityCredentials);
		return jndiConfig;
	}
}

 getJndiConfig()方法中提供了初始化Context的property配置。

属性名 属性说明
Context.INITIAL_CONTEXT_FACTORY 指定InitialContext的实现类名称。这里使用weblogic作为服务器。所以相应的值为weblogic.jndi.WLInitialContextFactory。
Context.PROVIDER_URL 连接jndi服务器的url。这里weblogic运行在本机,并且端口号为8888。所以值设置为t3://localhost:8888。
Context.SECURITY_PRINCIPAL 通过jndi访问指定resource的凭证名称。简单理解为访问这个resource时的用户名。如果这个resource没有设定访问策略,则可以不设。
Context.SECURITY_CREDENTIALS 通过jndi访问指定resource时与凭证相对应的密码。简单理解为访问这个resource时与用户名相对应的密码。如果这个resource没有设定访问策略,则可以不设。

 

getJndiConfig()有以下2行注释

//jndiConfig.put(Context.SECURITY_PRINCIPAL, securityPrincipal);

//jndiConfig.put(Context.SECURITY_CREDENTIALS, securityCredentials);

这是因为没有对新注册的resource{object=This is a object}设置访问策略。

通过以下步骤可以在weblogic10.3中对某一个resource设置访问策略。

1) 登录weblogic



 2) 切换到指定server



 3)打开jndi配置页面

 4)择选新注册的resource,切换到sercurity页。

1
5) 选择Policies页,单击Add Conditions



 6)Predicate List 选择User,单击Next



 7)User Argument Name 填写Weblogic(这是我登录weblogic的一个用户名),点击Add按钮,点击Finish


 
8)最终点击Save,会出现保存成功信息



  

 

通过以上步骤为名称为object的resource设定了访问策略。如果通过api访问这个resoucre,

必须提供Context.SECURITY_PRINCIPAL,Context.SECURITY_CREDENTIALS。

及以上示例只需要重新启用注释的那2行代码。

猜你喜欢

转载自antlove.iteye.com/blog/1829363