How to Use JNDI in websphere (get connect string database websphere)
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
/**
* @version 1.0
* @author
*/
public class JuliDataServlet extends HttpServlet implements Servlet
{
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
doPost( req, resp);
}
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
Connection conn=null;
PrintWriter out=resp.getWriter();
try{
//JNDI
Context aContext = new InitialContext();
DataSource aDataSource = (DataSource)aContext.lookup("java:comp/env/ExtDS");
conn = aDataSource.getConnection();
//JNDI end
//raw JDBC for the same SAMPLEsample DB2 database
//Class.forName("COM.ibm.db2.jdbc.app.DB2Driver"); //need db2java.zip in the path
//conn = DriverManager.getConnection("jdbc:db2:sample"); //DB2
//raw JDBC end
String firstname="";
String sql = "select firstnme, lastname from employee";
Statement stm = conn.createStatement();
ResultSet rst = stm.executeQuery(sql);
for (int i=0; (i<10 && rst.next()); i++) //only print 10 names
{
firstname = rst.getString("firstnme");
out.println("Hello "+ firstname+"," );
}
if(conn != null)
{
conn.close();
System.out.println("Successfully closed");
}
}
catch (Exception e)
{
System.out.println(e);
}
}
}
==============================
ExtDS : Alias JNDI in websphere
=================================
Config file : ibm-web-bnd.html
<?xml version="1.0" encoding="UTF-8"?> <web-bnd xmlns="http://websphere.ibm.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://websphere.ibm.com/xml/ns/javaee
http://websphere.ibm.com/xml/ns/javaee/ibm-web-bnd_1_0.xsd" version="1.0"> <resource-ref> <res-ref-name>ExtDS</res-ref-name> <jndi-name>ExtDS</jndi-name> </resource-ref> </web-bnd>
==================================
Config file : web.xml
<resource-ref> <description> Datasource connection to db</description> <res-ref-name>ExtDS</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref>
Không có nhận xét nào:
Đăng nhận xét