天天看点

WAS6.1JNDI数据源配置测试代码一、例子原文参考二、修改版本一三、修改版本二四、可能遇到的问题

WAS课实验选学参考例子(需要配合前面配置好的jdbc/Test数据源使用)

前面数据源的配置文档下载:http://www.docin.com/p-1093004452.html

文章用到的jar包下载:http://download.csdn.net/detail/gsls200808/8513087

一、例子原文参考

(选学参考代码)

package com.myexample.util;

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class BaseUtil {
	public static Connection getConn() {
		Connection con = null;

		Context ctx;
		try {
			ctx = new InitialContext();

			DataSource ds;

			ds = (DataSource) ctx.lookup("java:comp/env/jdbc/Test");

			if (ds == null) {
				System.out.println("数据源不正确");
			} else {

				try {
					con = ds.getConnection();
				} catch (SQLException e) {
					e.printStackTrace();
				}

			}
		} catch (NamingException e) {
			e.printStackTrace();
		}

		return con;

	}
}
           

WEB-INF/web.xml

<resource-ref>
		<res-ref-name>jdbc/Test</res-ref-name>
		<res-type>javax.sql.DataSource</res-type>
		<res-auth>Container</res-auth>
	</resource-ref>
           

相应的资源配置 xml 文件(不同的应用服务器设置不同,这里是以早期版本的 tomcat 服务器为例的)

<reference-descriptor>
		<resource-description>
			<res-ref-name>jdbc/Test</res-ref-name>
			<jndi-name>jdbc/Test</jndi-name>
		</resource-description>
	</reference-descriptor>
           

也可以直接在程序中使用lookup(“jdbc/Test”),但这样程序的移植以后,如果JNDI命名冲突,将需要直接更改代码;上面的第一个方法可以通过直接更改相应的资源配置xml来解决命名冲突的问题.

上面选学的这个实验老师没在Websphere6.1上做成功。经过一番查找后发现StackOverFlow上很多Websphere的资源配置文件是写在WEB-INF/ibm-web-bnd.xml下面的,内容也不一样。

二、修改版本一

下面的例子在Websphere6.1测试通过,但仍有瑕疵。

WEB-INF/web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app 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">
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
	<!-- Data Source Reference -->
	<resource-ref>
		<res-ref-name>jdbc/Test</res-ref-name>
		<res-type>javax.sql.DataSource</res-type>
		<res-auth>Container</res-auth>
		<res-sharing-scope>Shareable</res-sharing-scope>
	</resource-ref>
</web-app>
           

WEB-INF/ibm-web-bnd.xml

<?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">
	<virtual-host name="default_host" />
	<!-- Binding for Data Source,  -->
	<resource-ref name="jdbc/Test" binding-name="jdbc/Test"></resource-ref>

</web-bnd>
           

index.jsp

<%@page import="java.sql.Connection"%>
<%@page import="javax.sql.DataSource"%>
<%@page import="javax.naming.InitialContext"%>
<%@page import="javax.naming.Context"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>

<!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=UTF-8">
<title>JNDI测试</title>
</head>
<body>
	<br /> ======================
	<br />
	<%
		Connection conn = null;
		Context initCtx = null;
		initCtx = new InitialContext();
		DataSource ds = (DataSource) initCtx
				.lookup("java:comp/env/jdbc/Test");
		if (ds != null) {
			out.print("数据源获取成功!<br />");
			conn = ds.getConnection();
		} else {
			out.print("数据源获取失败<br />");
		}
		if (conn != null) {
			out.print("数据库连接获取成功<br />");
		} else {
			out.print("数据库连接获取失败<br />");
		}
	%>
</body>
</html>
           

部署之后会有五项,多出的是一个映射选项,选无并把前面的TestApp选上就可以了。

三、修改版本二

2015年3月9日更新:上面的代码其实是有瑕疵的:获得的连接可能是不能用的,还有一个问题配置jndi数据源的文件在WAS6.1应该是ibm-web-bnd.xmi,其他版本可能有变化。

下面给出更改的几项内容:

删除ibm-web-bnd.xml,新建WEB-INF/ibm-web-bnd.xmi,内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<webappbnd:WebAppBinding xmi:version="2.0"
	xmlns:xmi="http://www.omg.org/XMI" xmlns:webappbnd="webappbnd.xmi"
	xmi:id="WebAppBinding_1237946146690" virtualHostName="default_host">
	<webapp href="WEB-INF/web.xml#WebApp_1237946146690" target="_blank" rel="external nofollow"  />
	<resRefBindings xmi:id="ResourceRefBinding_1238122581487"
		jndiName="jdbc/Test">
		<bindingResourceRef
			href="WEB-INF/web.xml#ResourceRef_1238122581487" target="_blank" rel="external nofollow"  />
	</resRefBindings>
</webappbnd:WebAppBinding>
           

更改web.xml如下

<span style="font-size:12px;"><?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_1237946146690" 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">
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
	<!-- Data Source Reference jdbc/Test-->
	<resource-ref id="ResourceRef_1238122581487">
		<description>datasource</description>
		<res-ref-name>jdbc/Test</res-ref-name>
		<res-type>javax.sql.DataSource</res-type>
		<res-auth>Container</res-auth>
		<res-sharing-scope>Shareable</res-sharing-scope>
	</resource-ref>
</web-app></span>
           

新建dbtest.jsp

<%@page import="java.sql.SQLException"%>
<%@page import="javax.naming.NamingException"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.Connection"%>
<%@page import="javax.sql.DataSource"%>
<%@page import="javax.naming.Context"%>
<%@page import="javax.naming.InitialContext"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<%
		try {
			//初始化StringBuffer对象
			StringBuffer buffer = new StringBuffer();

			//JNDI获取数据源
			Context initcontext = new InitialContext();
			Context context = (Context) initcontext.lookup("java:comp/env");
			DataSource datasource = (DataSource) context
					.lookup("jdbc/Test");
			Connection cn = datasource.getConnection();

			//数据库操作
			Statement st = cn.createStatement();
			String sql = "select * from Categories";
			//String key = "";
			//if (key != null)
			//sql = sql + " where CategoryName like '%" + key + "%'";
			ResultSet rs = st.executeQuery(sql);

			//将结果写入StringBuffer对象
			buffer.append("<Table Border><TR>");
			buffer.append("<TH width=100>" + "类别ID");
			buffer.append("<TH width=100>" + "分类名称");
			buffer.append("<TH width=50>" + "类别描述");
			buffer.append("</TR>");
			while (rs.next()) {
				buffer.append("<TR>");
				buffer.append("<TD>" + rs.getInt(1) + "</TD>");
				buffer.append("<TD>" + rs.getString(2) + "</TD>");
				buffer.append("<TD>" + rs.getString(3) + "</TD>");
				buffer.append("</TR>");
			}
			buffer.append("</Table>");

			//输出
			out.write(buffer.toString());
			rs.close();
			st.close();
			cn.close();
		} catch (NamingException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	%>
</body>
</html>
           

至此代码没什么问题了,但是在WAS上运行却获取不到内容,查看日志文件SystemErr.log(目录在C:\Program Files\IBM\WebSphere\AppServer\profiles\Profile1\logs\server1),出现如下错误:

[15-3-9 18:15:43:651 CST] 0000002b SystemErr     R java.sql.SQLException: [IBM][SQLServer JDBC Driver]This driver is locked for use with embedded applications.
[15-3-9 18:15:43:651 CST] 0000002b SystemErr     R     at com.ibm.websphere.jdbc.base.BaseExceptions.createException(Unknown Source)
[15-3-9 18:15:43:651 CST] 0000002b SystemErr     R     at com.ibm.websphere.jdbc.base.BaseExceptions.getException(Unknown Source)
[15-3-9 18:15:43:651 CST] 0000002b SystemErr     R     at com.ibm.websphere.jdbc.base.BaseConnection.createStatement(Unknown Source)
[15-3-9 18:15:43:651 CST] 0000002b SystemErr     R     at com.ibm.websphere.jdbcx.base.BasePooledConnection.createStatement(Unknown Source)
[15-3-9 18:15:43:651 CST] 0000002b SystemErr     R     at com.ibm.websphere.jdbcx.base.BaseConnectionWrapper.createStatement(Unknown Source)
[15-3-9 18:15:43:651 CST] 0000002b SystemErr     R     at com.ibm.ws.rsadapter.jdbc.WSJdbcConnection.createStatement(WSJdbcConnection.java:1194)
[15-3-9 18:15:43:651 CST] 0000002b SystemErr     R     at com.ibm.ws.rsadapter.jdbc.WSJdbcConnection.createStatement(WSJdbcConnection.java:1172)
[15-3-9 18:15:43:651 CST] 0000002b SystemErr     R     at com.ibm._jsp._dbtest._jspService(_dbtest.java:95)
[15-3-9 18:15:43:651 CST] 0000002b SystemErr     R     at com.ibm.ws.jsp.runtime.HttpJspBase.service(HttpJspBase.java:85)
[15-3-9 18:15:43:651 CST] 0000002b SystemErr     R     at javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
[15-3-9 18:15:43:651 CST] 0000002b SystemErr     R     at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:966)
[15-3-9 18:15:43:651 CST] 0000002b SystemErr     R     at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:478)
[15-3-9 18:15:43:651 CST] 0000002b SystemErr     R     at com.ibm.ws.wswebcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:463)
[15-3-9 18:15:43:651 CST] 0000002b SystemErr     R     at com.ibm.wsspi.webcontainer.servlet.GenericServletWrapper.handleRequest(GenericServletWrapper.java:115)
[15-3-9 18:15:43:651 CST] 0000002b SystemErr     R     at com.ibm.ws.jsp.webcontainerext.AbstractJSPExtensionServletWrapper.handleRequest(AbstractJSPExtensionServletWrapper.java:168)
[15-3-9 18:15:43:651 CST] 0000002b SystemErr     R     at com.ibm.ws.jsp.webcontainerext.AbstractJSPExtensionProcessor.handleRequest(AbstractJSPExtensionProcessor.java:270)
[15-3-9 18:15:43:651 CST] 0000002b SystemErr     R     at com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:3107)
[15-3-9 18:15:43:651 CST] 0000002b SystemErr     R     at com.ibm.ws.webcontainer.webapp.WebGroup.handleRequest(WebGroup.java:238)
[15-3-9 18:15:43:651 CST] 0000002b SystemErr     R     at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:811)
[15-3-9 18:15:43:651 CST] 0000002b SystemErr     R     at com.ibm.ws.wswebcontainer.WebContainer.handleRequest(WebContainer.java:1425)
[15-3-9 18:15:43:651 CST] 0000002b SystemErr     R     at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:92)
[15-3-9 18:15:43:651 CST] 0000002b SystemErr     R     at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:465)
[15-3-9 18:15:43:651 CST] 0000002b SystemErr     R     at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewInformation(HttpInboundLink.java:394)
[15-3-9 18:15:43:651 CST] 0000002b SystemErr     R     at com.ibm.ws.http.channel.inbound.impl.HttpICLReadCallback.complete(HttpICLReadCallback.java:102)
[15-3-9 18:15:43:651 CST] 0000002b SystemErr     R     at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:152)
[15-3-9 18:15:43:651 CST] 0000002b SystemErr     R     at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:213)
[15-3-9 18:15:43:651 CST] 0000002b SystemErr     R     at com.ibm.io.async.AbstractAsyncFuture.fireCompletionActions(AbstractAsyncFuture.java:195)
[15-3-9 18:15:43:651 CST] 0000002b SystemErr     R     at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:136)
[15-3-9 18:15:43:651 CST] 0000002b SystemErr     R     at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:193)
[15-3-9 18:15:43:651 CST] 0000002b SystemErr     R     at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:766)
[15-3-9 18:15:43:651 CST] 0000002b SystemErr     R     at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:847)
[15-3-9 18:15:43:651 CST] 0000002b SystemErr     R     at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1498)
           

问题出在base.jar(目录在C:\Program Files\IBM\WebSphere\AppServer\lib)驱动不能用,被锁住了,需要licence才能解锁。下面是某位大神的解锁方法

把base.jar复制到E盘根目录下

然后执行以下java代码(需要导入javassist这个jar包,笔者是从struts2开发包例程解压拷过来的javassist-3.11.0.GA.jar):

package com.example;

import java.io.IOException;

import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.NotFoundException;
import javassist.expr.ExprEditor;
import javassist.expr.MethodCall;

public class test {

	public static void main(String[] args) {
		ClassPool pool = ClassPool.getDefault();

		try {
			pool.insertClassPath("E:\\base.jar");
			CtClass cc = pool.get("com.ibm.websphere.jdbc.base.BaseConnection");
			CtMethod m = cc.getDeclaredMethod("open");
			m.instrument(new ExprEditor() {

				@Override
				public void edit(MethodCall m) throws CannotCompileException {
					if (m.getClassName().equals(
							"com.ibm.websphere.jdbc.base.BaseLicenseUtility")
							&& m.getMethodName().equals("isLocked")) {
						m.replace("$_=false;");
						System.out.println("find\n");
					}
					;
				}

			});
			cc.writeFile("E:\\aaa");
		} catch (NotFoundException e) {
			e.printStackTrace();
		} catch (CannotCompileException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println("end\n");

	}
}
           

程序运行之后会在E盘aaa目录输出带包的class文件。

然后对base.jar解压,替换class,然后重新打包成jar(建议用winrar打包成zip然后改后缀名),最后替换掉原始的base.jar就可以了。

已经打包好的base.jar包下载:http://download.csdn.net/detail/gsls200808/8513087

到这里才算真正结束!!!

================================分割线===============================================

四、可能遇到的问题

下面谈谈笔者遇到的问题:

1.交叉引用(SystemOut.log)

[15-3-9 14:54:52:635 CST] 00000038 ArchiveDeploy W   ADMA0091E: 为模块 firstapp.war 在 URI WEB-INF/ibm-web-bnd.xmi 中定义的资源 WEB-INF/ibm-web-bnd.xmi 是无效的。此资源具有无法解析的交叉引用 org.eclipse.jst.j2ee.webapplication.internal.impl.WebAppImpl@13be13be (eProxyURI: WEB-INF/web.xml#WebApp_1237946146690)。
[15-3-9 14:54:57:088 CST] 00000038 ArchiveDeploy W   ADMA0091E: 为模块 firstapp.war 在 URI WEB-INF/ibm-web-bnd.xmi 中定义的资源 WEB-INF/ibm-web-bnd.xmi 是无效的。此资源具有无法解析的交叉引用 org.eclipse.jst.j2ee.webapplication.internal.impl.WebAppI[email protected] (eProxyURI: WEB-INF/web.xml#WebApp_1237946146690)。
           

出现这个错误的原因是web.xml中没有配置<webapp>的id属性,配置好后正常

2.空指针异常(SystemErr.log)

[15-3-9 18:13:36:620 CST] 0000002c SystemErr     R java.lang.NullPointerException
           

配置文件xml或xmi没写好

3.总结一句,控制台测试成功但代码运行不正常不一定是代码结构问题,还有可能是licence的问题

update2018-3-8:补充一下javassist改的内容,改了BaseConnection的open方法,将BaseLicenseUtility.isLocked(this)这一句替换成了false,这么说可能不直观,看一个jd-gui反编译后的对比图

WAS6.1JNDI数据源配置测试代码一、例子原文参考二、修改版本一三、修改版本二四、可能遇到的问题

update2018-3-8:base.jar替换的代码https://gitee.com/gsls200808/CrackBaseJar

继续阅读