标签:
JNDI,Java Naming Directory Interface,J2EE的标准之一,所有的J2EE容器都必须提供一个JNDI的服务。它是SUN公司提供的一种标准的Java命名系统接口,JNDI提供统一的客户端API,通过不同的访问提供者接口JNDI服务供应接口(SPI)的实现,由管理者将JNDI API映射为特定的命名服务和目录系统,使得Java应用程序可以和这些命名服务和目录服务之间进行交互。目录服务是命名服务的一种自然扩展。两者之间的关键差别是目录服务中对象不但可以有名称还可以有属性(例如,用户有email地址),而命名服务中对象没有属性。
package com.zhouxiang; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; public class JndiTest { //将当前对象绑定到<span style="font-family: Arial; font-size: 14px; line-height: 26px;">目录容器环境中</span> public void registerInJndi() { try { Context context = new InitialContext(); context.bind("java:global/JndiEjb", this); } catch (NamingException e) { } } //通过jndi查找并返回<span style="font-family: 'Microsoft YaHei UI', 'Microsoft YaHei', SimSun, 'Segoe UI', Tahoma, Helvetica, sans-serif, 'Microsoft YaHei', Georgia, Helvetica, Arial, sans-serif, 宋体, PMingLiU, serif;">当前对象</span> public void retrieveFromJndi() { try { Context context = new InitialContext(); Object lookup = context.lookup("java:global/JndiEjb"); if(lookup != null && lookup instanceof JndiTest) { JndiTest jndiEjb = (JndiTest)lookup; jndiEjb.helloWorld(); } } catch (NamingException e) { } } public void helloWorld() { System.out.println("hello world"); } }
package com.zhouxiang; import java.io.IOException; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class CDITest */ public class ServletTest extends HttpServlet { private static final long serialVersionUID = 1L; private JndiTest test1=new JndiTest(); /** * @see HttpServlet#HttpServlet() */ public CDITest() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doPost(request,response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub test1.registerInJndi(); test1.retrieveFromJndi(); } }
标签:
原文地址:http://blog.csdn.net/leimengyuanlian/article/details/43955655