JNDI 筆記(二) J2EE下使用JNDI

來源:互聯網
上載者:User

在J2EE環境下使用JNDI是非常簡單的事,因為所有的J2EE容器都要實現JNDI服務,所以,在J2EE環境下使用JNDI,與使用Hashtable也沒有什麼太大區別。只有一點限制,那就是綁定對象時,對象所屬的類必須實現java.io.Serializable介面,這一點也實在一點也不困難,幾乎所有用到的Java類都實現了這個介面,對於自訂的類,在介面實現列表裡把這個介面加進去也就是了。

下面,我將示範一下如何在J2EE環境下使用JNDI,為了保證代碼的通用性,我不使用struts之類的架構,而是直接使用標準JSP和Servlet實現。我將該項目的名稱定為jndi_test

要使用JNDI,需要先到SUN的網站上去下載jndi.jar。

 2.1 JSP
本項目包括5個JSP,功能說明如下:

index.jsp:首頁
bind.jsp:用於在JNDI中綁定對象
bind_result.jsp:綁定對象後的返回頁面
lookup.jsp:用於在JNDI中檢索對象
lookup_result.jsp:用於顯示檢索對象
本節中用到的JSP代碼如下,代碼都簡單地很,就不多做解釋了。

2.1.1 index.jsp


<%...@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>JNDI Test</title>
</head>
<body>
<a href="bind.jsp" target="_blank">bind.jsp</a>
<br />
<a href="lookup.jsp" target="_blank">lookup.jsp</a>
</body>
</html>

2.1.2 bind.jsp


<%...@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>JNDI Test - Bind</title>
</head>
<body>
<a href="bind.do">bind an object</a>
</body>
</html>

2.1.3 bind_result.jsp


<%...@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>JNDI Test - Bind result</title>
</head>
<body>
<p>Binded successfully!</p>
</body>
</html>

2.1.4 lookup.jsp


<%...@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>JNDI Test - lookup</title>
</head>
<body>
<a href="lookup.do">lookup the binded object</a>
</body>
</html>

2.1.5 lookup_result.jsp


<%...@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>JNDI Test - Lookup result</title>
</head>
<body>
<%...
    Object o = request.getAttribute("found_jndi_obj");
    out.println(o);
%>
</body>
</html>

2.2 Servlet
本例包括兩個Servlet,功能說明如下:

BindServlet:用於在JNDI服務中綁定一個對象
LookupServlet:用於在JNDI服務中取出一個對象
2.2.1 BindServlet.java


package lld.test.jndi;

import java.io.IOException;
import java.util.Date;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.*;

public class BindServlet extends HttpServlet
...{

    private static final long serialVersionUID = 5219969790998794367L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException
    ...{
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException
    ...{
        try
        ...{
            Context jndi_ctx = new InitialContext();
            String key = "jndi_object";
            jndi_ctx.rebind(key, new Date());
        }catch(Exception ex)
        ...{
            ex.printStackTrace();
        }
       
        ServletContext context = this.getServletContext();
        RequestDispatcher dispatcher = context.getRequestDispatcher("/bind_result.jsp");
        dispatcher.forward(req, resp);
    }
   
}

使用rebind而不是bind綁定對象是因為,使用bind時,如果已經有對象綁定到該索引值上,則會拋出異常。

因為只是範例程式碼,所以我只是綁定了一個最簡單的日期對象。

2.2.2 LookupServlet.java


package lld.test.jndi;

import java.io.IOException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LookupServlet extends HttpServlet
...{
    private static final long serialVersionUID = 6677219828267184673L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException
    ...{
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException
    ...{
        try
        ...{
            Context jndi_ctx = new InitialContext();
            String key = "jndi_object";
            Object o = jndi_ctx.lookup(key);
            req.setAttribute("found_jndi_obj", o);
        }catch(Exception ex)
        ...{
            ex.printStackTrace();
        }
       
        ServletContext context = this.getServletContext();
        RequestDispatcher dispatcher = context.getRequestDispatcher("/lookup_result.jsp");
        dispatcher.forward(req, resp);
    }
   
}

2.3 web.xml
在web.xml中,加入了servlet映射

 

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <display-name>jndi_test</display-name>
   
    <servlet>
        <servlet-name>BindServlet</servlet-name>
        <servlet-class>lld.test.jndi.BindServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>BindServlet</servlet-name>
        <url-pattern>/bind.do</url-pattern>
    </servlet-mapping>
   
    <servlet>
        <servlet-name>LookupServlet</servlet-name>
        <servlet-class>lld.test.jndi.LookupServlet</servlet-class>
    </servlet>
   
    <servlet-mapping>
        <servlet-name>LookupServlet</servlet-name>
        <url-pattern>/lookup.do</url-pattern>
    </servlet-mapping>
   
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>
OK,所有的代碼都在這裡了,部署到Tomcat下運行即可。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.