java039的简单介绍

博主:adminadmin 2023-03-20 04:02:09 454

今天给各位分享java039的知识,其中也会对进行解释,如果能碰巧解决你现在面临的问题,别忘了关注本站,现在开始吧!

本文目录一览:

java 中怎么用正则表达式删除"[ " 或 " ]" 一些特殊字符 先谢了

例子如下:

String pattern = "([-+*/^()\\]\\[])";

String test = "1237019830+32[89-234]234";

System.out.println("------test1=["+test+"]");

test = test.replaceAll(pattern, "");

System.out.println("------test2=["+test+"]");

这个应该能够满足你的要求,已测试。

运行结果为:

------test1=[1237019830+32[89-234]234]

------test2=[12370198303289234234]

java中打印1到100之间的整数,且个位为4的不打印?

for (int i = 1; i = 100; i++) {

if (i % 10 != 4) {

System.out.println(i);

}

}

[高分]java方面的问题:请教高手db.properties连接池的用法

连接池用法JDBC

Java Servlet作为首选的服务器端数据处理技术,正在迅速取代CGI脚本。Servlet超越CGI的优势之一在于,不仅多个请求可以共享公用资源,而且还可以在不同用户请求之间保留持续数据。本文介绍一种充分发挥该特色的实用技术,即数据库连接池。

一、实现连接池的意义

动态Web站点往往用数据库存储的信息生成Web页面,每一个页面请求导致一次数据库访问。连接数据库不仅要开销一定的通讯和内存资源,还必须完成用户验证、安全上下文配置这类任务,因而往往成为最为耗时的操作。当然,实际的连接时间开销千变万化,但1到2秒延迟并非不常见。如果某个基于数据库的Web应用只需建立一次初始连接,不同页面请求能够共享同一连接,就能获得显著的性能改善。

Servlet是一个Java类。Servlet引擎(它可能是Web服务软件的一部分,也可能是一个独立的附加模块)在系统启动或Servlet第一次被请求时将该类装入Java虚拟机并创建它的一个实例。不同用户请求由同一Servlet实例的多个独立线程处理。那些要求在不同请求之间持续有效的数据既可以用Servlet的实例变量来保存,也可以保存在独立的辅助对象中。

用JDBC访问数据库首先要创建与数据库之间的连接,获得一个连接对象(Connection),由连接对象提供执行SQL语句的方法。本文介绍的数据库连接池包括一个管理类DBConnectionManager,负责提供与多个连接池对象(DBConnectionPool类)之间的接口。每一个连接池对象管理一组JDBC连接对象,每一个连接对象可以被任意数量的Servlet共享。

类DBConnectionPool提供以下功能:

1) 从连接池获取(或创建)可用连接。

2) 把连接返回给连接池。

3) 在系统关闭时释放所有资源,关闭所有连接。

此外, DBConnectionPool类还能够处理无效连接(原来登记为可用的连接,由于某种原因不再可用,如超时,通讯问题),并能够限制连接池中的连接总数不超过某个预定值。

管理类DBConnectionManager用于管理多个连接池对象,它提供以下功能:

1) 装载和注册JDBC驱动程序。

2) 根据在属性文件中定义的属性创建连接池对象。

3) 实现连接池名字与其实例之间的映射。

4) 跟踪客户程序对连接池的引用,保证在最后一个客户程序结束时安全地关闭所有连接池。

本文余下部分将详细说明这两个类,最后给出一个示例演示Servlet使用连接池的一般过程。

二、具体实现

DBConnectionManager.java程序清单如下:

001 import java.io.*;

002 import java.sql.*;

003 import java.util.*;

004 import java.util.Date;

005

006 /**

007 * 管理类DBConnectionManager支持对一个或多个由属性文件定义的数据库连接

008 * 池的访问.客户程序可以调用getInstance()方法访问本类的唯一实例.

009 */

010 public class DBConnectionManager {

011 static private DBConnectionManager instance; // 唯一实例

012 static private int clients;

013

014 private Vector drivers = new Vector();

015 private PrintWriter log;

016 private Hashtable pools = new Hashtable();

017

018 /**

019 * 返回唯一实例.如果是第一次调用此方法,则创建实例

020 *

021 * @return DBConnectionManager 唯一实例

022 */

023 static synchronized public DBConnectionManager getInstance() {

024 if (instance == null) {

025 instance = new DBConnectionManager();

026 }

027 clients++;

028 return instance;

029 }

030

031 /**

032 * 建构函数私有以防止其它对象创建本类实例

033 */

034 private DBConnectionManager() {

035 init();

036 }

037

038 /**

039 * 将连接对象返回给由名字指定的连接池

040 *

041 * @param name 在属性文件中定义的连接池名字

042 * @param con 连接对象

043 */

044 public void freeConnection(String name, Connection con) {

045 DBConnectionPool pool = (DBConnectionPool) pools.get(name);

046 if (pool != null) {

047 pool.freeConnection(con);

048 }

049 }

050

051 /**

052 * 获得一个可用的(空闲的)连接.如果没有可用连接,且已有连接数小于最大连接数

053 * 限制,则创建并返回新连接

054 *

055 * @param name 在属性文件中定义的连接池名字

056 * @return Connection 可用连接或null

057 */

058 public Connection getConnection(String name) {

059 DBConnectionPool pool = (DBConnectionPool) pools.get(name);

060 if (pool != null) {

061 return pool.getConnection();

062 }

063 return null;

064 }

065

066 /**

067 * 获得一个可用连接.若没有可用连接,且已有连接数小于最大连接数限制,

068 * 则创建并返回新连接.否则,在指定的时间内等待其它线程释放连接.

069 *

070 * @param name 连接池名字

071 * @param time 以毫秒计的等待时间

072 * @return Connection 可用连接或null

073 */

074 public Connection getConnection(String name, long time) {

075 DBConnectionPool pool = (DBConnectionPool) pools.get(name);

076 if (pool != null) {

077 return pool.getConnection(time);

078 }

079 return null;

080 }

081

082 /**

083 * 关闭所有连接,撤销驱动程序的注册

084 */

085 public synchronized void release() {

086 // 等待直到最后一个客户程序调用

087 if (--clients != 0) {

088 return;

089 }

090

091 Enumeration allPools = pools.elements();

092 while (allPools.hasMoreElements()) {

093 DBConnectionPool pool = (DBConnectionPool) allPools.nextElement();

094 pool.release();

095 }

096 Enumeration allDrivers = drivers.elements();

097 while (allDrivers.hasMoreElements()) {

098 Driver driver = (Driver) allDrivers.nextElement();

099 try {

100 DriverManager.deregisterDriver(driver);

101 log("撤销JDBC驱动程序 " + driver.getClass().getName()+"的注册");

102 }

103 catch (SQLException e) {

104 log(e, "无法撤销下列JDBC驱动程序的注册: " + driver.getClass().getName());

105 }

106 }

107 }

108

109 /**

110 * 根据指定属性创建连接池实例.

111 *

112 * @param props 连接池属性

113 */

114 private void createPools(Properties props) {

115 Enumeration propNames = props.propertyNames();

116 while (propNames.hasMoreElements()) {

117 String name = (String) propNames.nextElement();

118 if (name.endsWith(".url")) {

119 String poolName = name.substring(0, name.lastIndexOf("."));

120 String url = props.getProperty(poolName + ".url");

121 if (url == null) {

122 log("没有为连接池" + poolName + "指定URL");

123 continue;

124 }

125 String user = props.getProperty(poolName + ".user");

126 String password = props.getProperty(poolName + ".password");

127 String maxconn = props.getProperty(poolName + ".maxconn", "0");

128 int max;

129 try {

130 max = Integer.valueOf(maxconn).intValue();

131 }

132 catch (NumberFormatException e) {

133 log("错误的最大连接数限制: " + maxconn + " .连接池: " + poolName);

134 max = 0;

135 }

136 DBConnectionPool pool =

137 new DBConnectionPool(poolName, url, user, password, max);

138 pools.put(poolName, pool);

139 log("成功创建连接池" + poolName);

140 }

141 }

142 }

143

144 /**

145 * 读取属性完成初始化

146 */

147 private void init() {

148 InputStream is = getClass().getResourceAsStream("/db.properties");

149 Properties dbProps = new Properties();

150 try {

151 dbProps.load(is);

152 }

153 catch (Exception e) {

154 System.err.println("不能读取属性文件. " +

155 "请确保db.properties在CLASSPATH指定的路径中");

156 return;

157 }

158 String logFile = dbProps.getProperty("logfile", "DBConnectionManager.log");

159 try {

160 log = new PrintWriter(new FileWriter(logFile, true), true);

161 }

162 catch (IOException e) {

163 System.err.println("无法打开日志文件: " + logFile);

164 log = new PrintWriter(System.err);

165 }

166 loadDrivers(dbProps);

167 createPools(dbProps);

168 }

169

170 /**

171 * 装载和注册所有JDBC驱动程序

172 *

173 * @param props 属性

174 */

175 private void loadDrivers(Properties props) {

176 String driverClasses = props.getProperty("drivers");

177 StringTokenizer st = new StringTokenizer(driverClasses);

178 while (st.hasMoreElements()) {

179 String driverClassName = st.nextToken().trim();

180 try {

181 Driver driver = (Driver)

182 Class.forName(driverClassName).newInstance();

183 DriverManager.registerDriver(driver);

184 drivers.addElement(driver);

185 log("成功注册JDBC驱动程序" + driverClassName);

186 }

187 catch (Exception e) {

188 log("无法注册JDBC驱动程序: " +

189 driverClassName + ", 错误: " + e);

190 }

191 }

192 }

193

194 /**

195 * 将文本信息写入日志文件

196 */

197 private void log(String msg) {

198 log.println(new Date() + ": " + msg);

199 }

200

201 /**

202 * 将文本信息与异常写入日志文件

203 */

204 private void log(Throwable e, String msg) {

205 log.println(new Date() + ": " + msg);

206 e.printStackTrace(log);

207 }

208

209 /**

210 * 此内部类定义了一个连接池.它能够根据要求创建新连接,直到预定的最

211 * 大连接数为止.在返回连接给客户程序之前,它能够验证连接的有效性.

212 */

213 class DBConnectionPool {

214 private int checkedOut;

215 private Vector freeConnections = new Vector();

216 private int maxConn;

217 private String name;

218 private String password;

219 private String URL;

220 private String user;

221

222 /**

223 * 创建新的连接池

224 *

225 * @param name 连接池名字

226 * @param URL 数据库的JDBC URL

227 * @param user 数据库帐号,或 null

228 * @param password 密码,或 null

229 * @param maxConn 此连接池允许建立的最大连接数

230 */

231 public DBConnectionPool(String name, String URL, String user, String password,

232 int maxConn) {

233 this.name = name;

234 this.URL = URL;

235 this.user = user;

236 this.password = password;

237 this.maxConn = maxConn;

238 }

239

240 /**

241 * 将不再使用的连接返回给连接池

242 *

243 * @param con 客户程序释放的连接

244 */

245 public synchronized void freeConnection(Connection con) {

246 // 将指定连接加入到向量末尾

247 freeConnections.addElement(con);

248 checkedOut--;

249 notifyAll();

250 }

251

252 /**

253 * 从连接池获得一个可用连接.如没有空闲的连接且当前连接数小于最大连接

254 * 数限制,则创建新连接.如原来登记为可用的连接不再有效,则从向量删除之,

255 * 然后递归调用自己以尝试新的可用连接.

256 */

257 public synchronized Connection getConnection() {

258 Connection con = null;

259 if (freeConnections.size() 0) {

260 // 获取向量中第一个可用连接

261 con = (Connection) freeConnections.firstElement();

262 freeConnections.removeElementAt(0);

263 try {

264 if (con.isClosed()) {

265 log("从连接池" + name+"删除一个无效连接");

266 // 递归调用自己,尝试再次获取可用连接

267 con = getConnection();

268 }

269 }

270 catch (SQLException e) {

271 log("从连接池" + name+"删除一个无效连接");

272 // 递归调用自己,尝试再次获取可用连接

273 con = getConnection();

274 }

275 }

276 else if (maxConn == 0 || checkedOut maxConn) {

277 con = newConnection();

278 }

279 if (con != null) {

280 checkedOut++;

281 }

282 return con;

283 }

284

285 /**

286 * 从连接池获取可用连接.可以指定客户程序能够等待的最长时间

287 * 参见前一个getConnection()方法.

288 *

289 * @param timeout 以毫秒计的等待时间限制

290 */

291 public synchronized Connection getConnection(long timeout) {

292 long startTime = new Date().getTime();

293 Connection con;

294 while ((con = getConnection()) == null) {

295 try {

296 wait(timeout);

297 }

298 catch (InterruptedException e) {}

299 if ((new Date().getTime() - startTime) = timeout) {

300 // wait()返回的原因是超时

301 return null;

302 }

303 }

304 return con;

305 }

306

307 /**

308 * 关闭所有连接

309 */

310 public synchronized void release() {

311 Enumeration allConnections = freeConnections.elements();

312 while (allConnections.hasMoreElements()) {

313 Connection con = (Connection) allConnections.nextElement();

314 try {

315 con.close();

316 log("关闭连接池" + name+"中的一个连接");

317 }

318 catch (SQLException e) {

319 log(e, "无法关闭连接池" + name+"中的连接");

320 }

321 }

322 freeConnections.removeAllElements();

323 }

324

325 /**

326 * 创建新的连接

327 */

328 private Connection newConnection() {

329 Connection con = null;

330 try {

331 if (user == null) {

332 con = DriverManager.getConnection(URL);

333 }

334 else {

335 con = DriverManager.getConnection(URL, user, password);

336 }

337 log("连接池" + name+"创建一个新的连接");

338 }

339 catch (SQLException e) {

340 log(e, "无法创建下列URL的连接: " + URL);

341 return null;

342 }

343 return con;

344 }

345 }

346 }

三、类DBConnectionPool说明

该类在209至345行实现,它表示指向某个数据库的连接池。数据库由JDBC URL标识。一个JDBC URL由三部分组成:协议标识(总是jdbc),驱动程序标识(如 odbc、idb、oracle等),数据库标识(其格式依赖于驱动程序)。例如,jdbcdbc:demo,即是一个指向demo数据库的JDBC URL,而且访问该数据库要使用JDBC-ODBC驱动程序。每个连接池都有一个供客户程序使用的名字以及可选的用户帐号、密码、最大连接数限制。如果Web应用程序所支持的某些数据库操作可以被所有用户执行,而其它一些操作应由特别许可的用户执行,则可以为两类操作分别定义连接池,两个连接池使用相同的JDBC URL,但使用不同的帐号和密码。

类DBConnectionPool的建构函数需要上述所有数据作为其参数。如222至238行所示,这些数据被保存为它的实例变量:

如252至283行、285至305行所示, 客户程序可以使用DBConnectionPool类提供的两个方法获取可用连接。两者的共同之处在于:如连接池中存在可用连接,则直接返回,否则创建新的连接并返回。如果没有可用连接且已有连接总数等于最大限制数,第一个方法将直接返回null,而第二个方法将等待直到有可用连接为止。

所有的可用连接对象均登记在名为freeConnections的向量(Vector)中。如果向量中有多于一个的连接,getConnection()总是选取第一个。同时,由于新的可用连接总是从尾部加入向量,从而使得数据库连接由于长时间闲置而被关闭的风险减低到最小程度。

第一个getConnection()在返回可用连接给客户程序之前,调用了isClosed()方法验证连接仍旧有效。如果该连接被关闭或触发异常,getConnection()递归地调用自己以尝试获取另外的可用连接。如果在向量freeConnections中不存在任何可用连接,getConnection()方法检查是否已经指定最大连接数限制。如已经指定,则检查当前连接数是否已经到达极限。此处maxConn为0表示没有限制。如果没有指定最大连接数限制或当前连接数小于该值,该方法尝试创建新的连接。如创建成功,则增加已使用连接的计数并返回,否则返回空值。

如325至345行所示,创建新连接由newConnection()方法实现。创建过程与是否已经指定数据库帐号、密码有关。

JDBC的DriverManager类提供多个getConnection()方法,这些方法要用到JDBC URL与其它一些参数,如用户帐号和密码等。DriverManager将使用指定的JDBC URL确定适合于目标数据库的驱动程序及建立连接。

在285至305行实现的第二个getConnection()方法需要一个以毫秒为单位的时间参数,该参数表示客户程序能够等待的最长时间。建立连接的具体操作仍旧由第一个getConnection()方法实现。

该方法执行时先将startTime初始化为当前时间。在while循环中尝试获得一个连接。如果失败,则以给定的时间值为参数调用wait()。wait()的返回可能是由于其它线程调用notify()或notifyAll(),也可能是由于预定时间已到。为找出wait()返回的真正原因,程序用当前时间减开始时间(startTime),如差值大于预定时间则返回空值,否则再次调用getConnection()。

把空闲的连接登记到连接池由240至250行的freeConnection()方法实现,它的参数为返回给连接池的连接对象。该对象被加入到freeConnections向量的末尾,然后减少已使用连接计数。调用notifyAll()是为了通知其它正在等待可用连接的线程。

许多Servlet引擎为实现安全关闭提供多种方法。数据库连接池需要知道该事件以保证所有连接能够正常关闭。DBConnectionManager类负协调整个关闭过程,但关闭连接池中所有连接的任务则由DBConnectionPool类负责。在307至323行实现的release()方法供DBConnectionManager调用。该方法遍历freeConnections向量并关闭所有连接,然后从向量中删除这些连接。

四、类DBConnectionManager 说明

该类只能创建一个实例,其它对象能够调用其静态方法(也称为类方法)获得该唯一实例的引用。如031至036行所示,DBConnectionManager类的建构函数是私有的,这是为了避免其它对象创建该类的实例。

DBConnectionManager类的客户程序可以调用getInstance()方法获得对该类唯一实例的引用。如018至029行所示,类的唯一实例在getInstance()方法第一次被调用期间创建,此后其引用就一直保存在静态变量instance中。每次调用getInstance()都增加一个DBConnectionManager的客户程序计数。即,该计数代表引用DBConnectionManager唯一实例的客户程序总数,它将被用于控制连接池的关闭操作。

该类实例的初始化工作由146至168行之间的私有方法init()完成。其中 getResourceAsStream()方法用于定位并打开外部文件。外部文件的定位方法依赖于类装载器的实现。标准的本地类装载器查找操作总是开始于类文件所在路径,也能够搜索CLASSPATH中声明的路径。db.properties是一个属性文件,它包含定义连接池的键-值对。可供定义的公用属性如下:

drivers 以空格分隔的JDBC驱动程序类列表

logfile 日志文件的绝对路径

其它的属性和特定连接池相关,其属性名字前应加上连接池名字:

poolname.url 数据库的 JDBC URL

poolname.maxconn 允许建立的最大连接数,0表示没有限制

poolname.user 用于该连接池的数据库帐号

poolname.password 相应的密码

其中url属性是必需的,而其它属性则是可选的。数据库帐号和密码必须合法。用于Windows平台的db.properties文件示例如下:

drivers=sun.jdbc.odbc.JdbcOdbcDriver jdbc.idbDriver

logfile=D:\user\src\java\DBConnectionManager\log.txt

idb.url=jdbc:idb:c:\local\javawebserver1.1\db\db.prp

idb.maxconn=2

access.url=jdbcdbc:demo

access.user=demo

access.password=demopw

注意在Windows路径中的反斜杠必须输入2个,这是由于属性文件中的反斜杠同时也是一个转义字符。

init()方法在创建属性对象并读取db.properties文件之后,就开始检查logfile属性。如果属性文件中没有指定日志文件,则默认为当前目录下的DBConnectionManager.log文件。如日志文件无法使用,则向System.err输出日志记录。

装载和注册所有在drivers属性中指定的JDBC驱动程序由170至192行之间的loadDrivers()方法实现。该方法先用StringTokenizer将drivers属性值分割为对应于驱动程序名称的字符串,然后依次装载这些类并创建其实例,最后在 DriverManager中注册该实例并把它加入到一个私有的向量drivers。向量drivers将用于关闭服务时从DriverManager取消所有JDBC 驱动程序的注册。

init()方法的最后一个任务是调用私有方法createPools()创建连接池对象。如109至142行所示,createPools()方法先创建所有属性名字的枚举对象(即Enumeration对象,该对象可以想象为一个元素系列,逐次调用其nextElement()方法将顺序返回各元素),然后在其中搜索名字以“.url”结尾的属性。对于每一个符合条件的属性,先提取其连接池名字部分,进而读取所有属于该连接池的属性,最后创建连接池对象并把它保存在实例变量pools中。散列表(Hashtable类 )pools实现连接池名字到连接池对象之间的映射,此处以连接池名字为键,连接池对象为值。

为便于客户程序从指定连接池获得可用连接或将连接返回给连接池,类DBConnectionManager提供了方法getConnection()和freeConnection()。所有这些方法都要求在参数中指定连接池名字,具体的连接获取或返回操作则调用对应的连接池对象完成。它们的实现分别在051至064行、066至080行、038至049行。

如082至107行所示,为实现连接池的安全关闭,DBConnectionManager提供了方法release()。在上面我们已经提到,所有DBConnectionManager的客户程序都应该调用静态方法getInstance()以获得该管理器的引用,此调用将增加客户程序计数。客户程序在关闭时调用release()可以递减该计数。当最后一个客户程序调用release(),递减后的引用计数为0,就可以调用各个连接池的release()方法关闭所有连接了。管理类release()方法最后的任务是撤销所有JDBC驱动程序的注册。

五、Servlet使用连接池示例

Servlet API所定义的Servlet生命周期类如:

1) 创建并初始化Servlet(init()方法)。

2) 响应客户程序的服务请求(service()方法)。

3) Servlet终止运行,释放所有资源(destroy()方法)。

本例演示连接池应用,上述关键步骤中的相关操作为:

1) 在init(),用实例变量connMgr 保存调用DBConnectionManager.getInstance()所返回的引用。

2) 在service(),调用getConnection(),执行数据库操作,用freeConnection()将连接返回给连接池。

3) 在destroy(),调用release()关闭所有连接,释放所有资源。

示例程序清单如下:

import java.io.*;

import java.sql.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class TestServlet extends HttpServlet {

private DBConnectionManager connMgr;

public void init(ServletConfig conf) throws ServletException {

super.init(conf);

connMgr = DBConnectionManager.getInstance();

}

public void service(HttpServletRequest req, HttpServletResponse res)

throws IOException {

res.setContentType("text/html");

PrintWriter out = res.getWriter();

Connection con = connMgr.getConnection("idb");

if (con == null) {

out.println("不能获取数据库连接.");

return;

}

ResultSet rs = null;

ResultSetMetaData md = null;

Statement stmt = null;

try {

stmt = con.createStatement();

rs = stmt.executeQuery("SELECT * FROM EMPLOYEE");

md = rs.getMetaData();

out.println("H1职工数据/H1");

while (rs.next()) {

out.println("BR");

for (int i = 1; i md.getColumnCount(); i++) {

out.print(rs.getString(i) + ", ");

}

}

stmt.close();

rs.close();

}

catch (SQLException e) {

e.printStackTrace(out);

}

connMgr.freeConnection("i

java网上预约功能怎么实现啊。。

物车的逻辑业务的实现(MyCartBO.java),能够满足用户的添加,删除,修改,清空,查看购物车的信息!

ConnDB.java(这只是一个得到数据库连接和类)

01 //连接数据库

02 package cn.fqfx.model;

03

04 import java.sql.*;

05

06 public class ConnDB

07 {

08 //定义一个连接

09 private Connection ct = null;

10

11 //得到连接

12 public Connection getConn()

13 {

14 try {

15 //加载驱动

16 Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");

17 //得到连接

18 ct = DriverManager.getConnection

19 ("jdbc:microsoft:sqlserver://localhost:1433;databaseName=whdb2","sa","sa");

20 } catch (Exception e) {

21 e.printStackTrace();

22 // TODO: handle exception

23 }

24 return ct;

25 }

26 }

GoodsBean.java(这个文件主要用来保存从数据库的goods表中取得的信息)

01 //这是一个与Goods表对应的java bean

02 //表的信息可以保存在这里面

03 package cn.fqfx.model;

04

05 public class GoodsBean

06 {

07 //分别与goods表的各个字段相对应

08 private int goodsId = 0;

09 private String goodsName = "";

10 private String goodsInfo = "";

11 private String goodsPlace = "";

12

13

14 public int getGoodsId() {

15 return goodsId;

16 }

17 public void setGoodsId(int goodsId) {

18 this.goodsId = goodsId;

19 }

20

21

22 public String getGoodsName() {

23 return goodsName;

24 }

25 public void setGoodsName(String goodsName) {

26 this.goodsName = goodsName;

27 }

28

29

30 public String getGoodsInfo() {

31 return goodsInfo;

32 }

33 public void setGoodsInfo(String goodsInfo) {

34 this.goodsInfo = goodsInfo;

35 }

36

37

38 public String getGoodsPlace() {

39 return goodsPlace;

40 }

41 public void setGoodsPlace(String goodsPlace) {

42 this.goodsPlace = goodsPlace;

43 }

44 }

MyCartBO.java(这个就是购物车,主要以HashMap实现存放用户想买的商品id,商品数量.然后,通过方法的调用把购物车中的信息返回到界面让用户看)

001 //这是一个业务对象,相当于一个购物车!!

002 //--使用说明:这个购物车最好是在session中使用,因为一个用户一辆购物车,这样东西才不会一直丢

003 package cn.fqfx.model;

004

005 import java.sql.*;

006 import java.util.*;

007

008 public class MyCartBO

009 {

010 //定义几个数据库的连接

011 private Connection ct = null;

012 private PreparedStatement ps = null;

013 private ResultSet rs = null;

014

015 //定义一个HashMap充当购物车,第一个用来存放goodsId,值就是goods的数量

016 HashMapString, String hm = new HashMapString, String();

017

018 //当用户想购买的时候,就加入 购物车里面

019 public void addGoods(String goodsId, String goodsNumber)

020 {

021 hm.put(goodsId, goodsNumber);

022 }

023

024 //当用户不想要东西的时候,就把它删除

025 public void delGoods(String goodsId)

026 {

027 hm.remove(goodsId);

028 }

029

030 //当用户什么也不想要的时候,就清空它

031 public void clearGoods()

032 {

033 hm.clear();

034 }

035

036 //当用户想更换物品的数量的时候,就更新一下

037 public void upGoods(String goodsId, String newNumber)

038 {

039 //还是用加入物品的方法,因为会自动替换掉它,如果货物名字想换,那说明用户想删除了

040 hm.put(goodsId, newNumber);

041 }

042

043 //得到单个物品的数量,要用的话把它转成int型再使用

044 public String getGoodsNumberByGoodsId(String goodsId)

045 {

046 return hm.get(goodsId);

047 }

048

049 //把购物车的东西全部取出来,放入ArrayList里面

050 public ArrayListGoodsBean getAllGoods()

051 {

052 //要知道这个ArrayList是用来放GoodsBean,因为GoodsBean与表相对应,所以可以保存物品的信息

053 ArrayListGoodsBean al = new ArrayListGoodsBean();

054 try {

055 //得到连接

056 ct = new ConnDB().getConn();

057

058 //想一个sql语句,主要是取得goodsId,就可以全部取出来给外面的使用

059 String sql = "select * from goods where goodsId in (";

060 IteratorString it = hm.keySet().iterator();

061 while(it.hasNext())

062 {

063 //把goodsId取出来

064 String goodsId = it.next();

065 if(it.hasNext()){

066 sql += goodsId+",";

067 }else{

068 sql += goodsId+")";

069 }

070 }

071

072 //创建ps,上面把sql语句组织好

073 ps = ct.prepareStatement(sql);

074

075 //执行

076 rs = ps.executeQuery();

077

078 //取出来,放在GoodsBean,再把GoodsBean一个个放入ArrayList中,显示的页面就可以调用了

079 while(rs.next())

080 {

081 GoodsBean gb = new GoodsBean();

082 gb.setGoodsId(rs.getInt(1));

083 gb.setGoodsName(rs.getString(2));

084 gb.setGoodsInfo(rs.getString(3));

085 gb.setGoodsPlace(rs.getString(4));

086

087 //把gb放入al,相当于保存了从数据库中获得的数据

088 al.add(gb);

089 }

090 } catch (Exception e) {

091 e.printStackTrace();

092 // TODO: handle exception

093 }finally{

094 this.closeDBResource();

095 }

096 return al;

097 }

098

099 //关闭数据库资源

100 public void closeDBResource()

101 {

102 try {

103 if(rs != null){

104 rs.close();

105 rs = null;

106 }

107 } catch (Exception e2) {

108 e2.printStackTrace();

109 // TODO: handle exception

110 }

111 try {

112 if(ps != null){

113 ps.close();

114 ps = null;

115 }

116 } catch (Exception e2) {

117 e2.printStackTrace();

118 // TODO: handle exception

119 }

120 try {

121 if(ct != null){

122 ct.close();

123 ct= null;

124 }

125 } catch (Exception e2) {

126 e2.printStackTrace();

127 // TODO: handle exception

128 }

129 }

130 }

java代码doc转pdf提高效率的方法

使用了jacob.jar来调用activex控件,本机需安装WPS或pdfcreator

001 package experiments;

002

003 import com.jacob.activeX.ActiveXComponent;

004 import com.jacob.com.Dispatch;

005 import com.jacob.com.DispatchEvents;

006 import com.jacob.com.Variant;

007 import java.io.File;

008 import java.util.logging.Level;

009 import java.util.logging.Logger;

010

011 public class Doc2Pdf {

012

013 public static Converter newConverter(String name) {

014 if (name.equals("wps")) {

015 return new Wps();

016 } else if (name.equals("pdfcreator")) {

017 return new PdfCreator();

018 }

019 return null;

020 }

021

022 public synchronized static boolean convert(String word, String pdf) {

023 return newConverter("pdfcreator").convert(word, pdf);

024 }

025

026 public static interface Converter {

027

028 public boolean convert(String word, String pdf);

029 }

030

031 public static class Wps implements Converter {

032

033 public synchronized boolean convert(String word, String pdf) {

034 File pdfFile = new File(pdf);

035 File wordFile = new File(word);

036 ActiveXComponent wps = null;

037 try {

038 wps = new ActiveXComponent("wps.application");

039 ActiveXComponent doc = wps.invokeGetComponent("Documents").invokeGetComponent("Open", newVariant(wordFile.getAbsolutePath()));

040 doc.invoke("ExportPdf", new Variant(pdfFile.getAbsolutePath()));

041 doc.invoke("Close");

042 doc.safeRelease();

043 } catch (Exception ex) {

044 Logger.getLogger(Doc2Pdf.class.getName()).log(Level.SEVERE, null, ex);

045 return false;

046 } catch (Error ex) {

047 Logger.getLogger(Doc2Pdf.class.getName()).log(Level.SEVERE, null, ex);

048 return false;

049 } finally {

050 if (wps != null) {

051 wps.invoke("Terminate");

052 wps.safeRelease();

053 }

054 }

055 return true;

056 }

057 }

058

059 public static class PdfCreator implements Converter {

060

061 public static final int STATUS_IN_PROGRESS = 2;

062 public static final int STATUS_WITH_ERRORS = 1;

063 public static final int STATUS_READY = 0;

064 private ActiveXComponent pdfCreator;

065 private DispatchEvents dispatcher;

066 private volatile int status;

067 private Variant defaultPrinter;

068

069 private void init() {

070 pdfCreator = new ActiveXComponent("PDFCreator.clsPDFCreator");

071 dispatcher = new DispatchEvents(pdfCreator, this);

072 pdfCreator.setProperty("cVisible", new Variant(false));

073 pdfCreator.invoke("cStart", new Variant[]{newVariant("/NoProcessingAtStartup"), new Variant(true)});

074 setCOption("UseAutosave", 1);

075 setCOption("UseAutosaveDirectory", 1);

076 setCOption("AutosaveFormat", 0); // 0 = PDF

077 defaultPrinter = pdfCreator.getProperty("cDefaultPrinter");

078 status = STATUS_IN_PROGRESS;

079 pdfCreator.setProperty("cDefaultprinter", "PDFCreator");

080 pdfCreator.invoke("cClearCache");

081 pdfCreator.setProperty("cPrinterStop", false);

082 }

083

084 private void setCOption(String property, Object value) {

085 Dispatch.invoke(pdfCreator, "cOption", Dispatch.Put, new Object[]{property, value}, new int[2]);

086 }

087

088 private void close() {

089 if (pdfCreator != null) {

090 pdfCreator.setProperty("cDefaultprinter", defaultPrinter);

091 pdfCreator.invoke("cClearCache");

092 pdfCreator.setProperty("cPrinterStop", true);

093 pdfCreator.invoke("cClose");

094 pdfCreator.safeRelease();

095 pdfCreator = null;

096 }

097 if (dispatcher != null) {

098 dispatcher.safeRelease();

099 dispatcher = null;

100 }

101 }

102

103 public synchronized boolean convert(String word, String pdf) {

104 File pdfFile = new File(pdf);

105 File wordFile = new File(word);

106 try {

107 init();

108 setCOption("AutosaveDirectory", pdfFile.getParentFile().getAbsolutePath());

109 if (pdfFile.exists()) {

110 pdfFile.delete();

111 }

112 pdfCreator.invoke("cPrintfile", wordFile.getAbsolutePath());

113 int seconds = 0;

114 while (isInProcess()) {

115 seconds++;

116 if (seconds 30) { // timeout

117 throw new Exception("convertion timeout!");

118 }

119 Thread.sleep(1000);

120 }

121 if (isWithErrors()) return false;

122 // 由于转换前设置cOption的AutosaveFilename不能保证输出的文件名与设置的相同(pdfcreator会加入/修改后缀名)

123 // 所以这里让pdfcreator使用自动生成的文件名进行输出,然后在保存后将其重命名为目标文件名

124 File outputFile = newFile(pdfCreator.getPropertyAsString("cOutputFilename"));

125 if (outputFile.exists()) {

126 outputFile.renameTo(pdfFile);

127 }

128 } catch (InterruptedException ex) {

129 Logger.getLogger(Doc2Pdf.class.getName()).log(Level.SEVERE, null, ex);

130 return false;

131 } catch (Exception ex) {

132 Logger.getLogger(Doc2Pdf.class.getName()).log(Level.SEVERE, null, ex);

133 return false;

134 } catch (Error ex) {

135 Logger.getLogger(Doc2Pdf.class.getName()).log(Level.SEVERE, null, ex);

136 return false;

137 } finally {

138 close();

139 }

140 return true;

141 }

142

143 private boolean isInProcess() {

144 return status == STATUS_IN_PROGRESS;

145 }

146

147 private boolean isWithErrors() {

148 return status == STATUS_WITH_ERRORS;

149 }

150

151 // eReady event

152 public void eReady(Variant[] args) {

153 status = STATUS_READY;

154 }

155

156 // eError event

157 public void eError(Variant[] args) {

158 status = STATUS_WITH_ERRORS;

159 }

160 }

161

162 public static void main(String[] args) {

163 convert("e:\\test.doc", "e:\\output.pdf");

164 }

165 }

java高手请进(java加密问题)

package nom.mykimsoy.tools;

/*******************************************************************************

* md5 ��ʵ����RSA Data Security, Inc.���ύ��IETF ��RFC1321�е�MD5 message-digest

* �㷨��

******************************************************************************/

public class MD5 {

static final int S11 = 7;

static final int S12 = 12;

static final int S13 = 17;

static final int S14 = 22;

static final int S21 = 5;

static final int S22 = 9;

static final int S23 = 14;

static final int S24 = 20;

static final int S31 = 4;

static final int S32 = 11;

static final int S33 = 16;

static final int S34 = 23;

static final int S41 = 6;

static final int S42 = 10;

static final int S43 = 15;

static final int S44 = 21;

static final byte[] PADDING = { -128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,

0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,

0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,

0, 0, 0, 0, 0, 0, 0 };

private long[] state = new long[4]; // state (ABCD)

private long[] count = new long[2]; // number of bits, modulo 2^64 (lsb

// first)

private byte[] buffer = new byte[64]; // input buffer

public String digestHexStr;

private byte[] digest = new byte[16];

public String getMD5ofStr(String inbuf) {

md5Init();

md5Update(inbuf.getBytes(), inbuf.length());

md5Final();

digestHexStr = "";

for (int i = 0; i 16; i++) {

digestHexStr += byteHEX(digest[i]);

}

return digestHexStr;

}

public MD5() {

md5Init();

return;

}

private void md5Init() {

count[0] = 0L;

count[1] = 0L;

state[0] = 0x67452301L;

state[1] = 0xefcdab89L;

state[2] = 0x98badcfeL;

state[3] = 0x10325476L;

return;

}

private long F(long x, long y, long z) {

return (x y) | ((~x) z);

}

private long G(long x, long y, long z) {

return (x z) | (y (~z));

}

private long H(long x, long y, long z) {

return x ^ y ^ z;

}

private long I(long x, long y, long z) {

return y ^ (x | (~z));

}

private long FF(long a, long b, long c, long d, long x, long s, long ac) {

a += F(b, c, d) + x + ac;

a = ((int) a s) | ((int) a (32 - s));

a += b;

return a;

}

private long GG(long a, long b, long c, long d, long x, long s, long ac) {

a += G(b, c, d) + x + ac;

a = ((int) a s) | ((int) a (32 - s));

a += b;

return a;

}

private long HH(long a, long b, long c, long d, long x, long s, long ac) {

a += H(b, c, d) + x + ac;

a = ((int) a s) | ((int) a (32 - s));

a += b;

return a;

}

private long II(long a, long b, long c, long d, long x, long s, long ac) {

a += I(b, c, d) + x + ac;

a = ((int) a s) | ((int) a (32 - s));

a += b;

return a;

}

private void md5Update(byte[] inbuf, int inputLen) {

int i, index, partLen;

byte[] block = new byte[64];

index = (int) (count[0] 3) 0x3F;

if ((count[0] += (inputLen 3)) (inputLen 3))

count[1]++;

count[1] += (inputLen 29);

partLen = 64 - index;

if (inputLen = partLen) {

md5Memcpy(buffer, inbuf, index, 0, partLen);

md5Transform(buffer);

for (i = partLen; i + 63 inputLen; i += 64) {

md5Memcpy(block, inbuf, 0, i, 64);

md5Transform(block);

}

index = 0;

} else

i = 0;

md5Memcpy(buffer, inbuf, index, i, inputLen - i);

}

private void md5Final() {

byte[] bits = new byte[8];

int index, padLen;

Encode(bits, count, 8);

index = (int) (count[0] 3) 0x3f;

padLen = (index 56) ? (56 - index) : (120 - index);

md5Update(PADDING, padLen);

md5Update(bits, 8);

Encode(digest, state, 16);

}

private void md5Memcpy(byte[] output, byte[] input, int outpos, int inpos,

int len) {

int i;

for (i = 0; i len; i++)

output[outpos + i] = input[inpos + i];

}

private void md5Transform(byte block[]) {

long a = state[0], b = state[1], c = state[2], d = state[3];

long[] x = new long[16];

Decode(x, block, 64);

/* Round 1 */

a = FF(a, b, c, d, x[0], S11, 0xd76aa478L); /* 1 */

d = FF(d, a, b, c, x[1], S12, 0xe8c7b756L); /* 2 */

c = FF(c, d, a, b, x[2], S13, 0x242070dbL); /* 3 */

b = FF(b, c, d, a, x[3], S14, 0xc1bdceeeL); /* 4 */

a = FF(a, b, c, d, x[4], S11, 0xf57c0fafL); /* 5 */

d = FF(d, a, b, c, x[5], S12, 0x4787c62aL); /* 6 */

c = FF(c, d, a, b, x[6], S13, 0xa8304613L); /* 7 */

b = FF(b, c, d, a, x[7], S14, 0xfd469501L); /* 8 */

a = FF(a, b, c, d, x[8], S11, 0x698098d8L); /* 9 */

d = FF(d, a, b, c, x[9], S12, 0x8b44f7afL); /* 10 */

c = FF(c, d, a, b, x[10], S13, 0xffff5bb1L); /* 11 */

b = FF(b, c, d, a, x[11], S14, 0x895cd7beL); /* 12 */

a = FF(a, b, c, d, x[12], S11, 0x6b901122L); /* 13 */

d = FF(d, a, b, c, x[13], S12, 0xfd987193L); /* 14 */

c = FF(c, d, a, b, x[14], S13, 0xa679438eL); /* 15 */

b = FF(b, c, d, a, x[15], S14, 0x49b40821L); /* 16 */

/* Round 2 */

a = GG(a, b, c, d, x[1], S21, 0xf61e2562L); /* 17 */

d = GG(d, a, b, c, x[6], S22, 0xc040b340L); /* 18 */

c = GG(c, d, a, b, x[11], S23, 0x265e5a51L); /* 19 */

b = GG(b, c, d, a, x[0], S24, 0xe9b6c7aaL); /* 20 */

a = GG(a, b, c, d, x[5], S21, 0xd62f105dL); /* 21 */

d = GG(d, a, b, c, x[10], S22, 0x2441453L); /* 22 */

c = GG(c, d, a, b, x[15], S23, 0xd8a1e681L); /* 23 */

b = GG(b, c, d, a, x[4], S24, 0xe7d3fbc8L); /* 24 */

a = GG(a, b, c, d, x[9], S21, 0x21e1cde6L); /* 25 */

d = GG(d, a, b, c, x[14], S22, 0xc33707d6L); /* 26 */

c = GG(c, d, a, b, x[3], S23, 0xf4d50d87L); /* 27 */

b = GG(b, c, d, a, x[8], S24, 0x455a14edL); /* 28 */

a = GG(a, b, c, d, x[13], S21, 0xa9e3e905L); /* 29 */

d = GG(d, a, b, c, x[2], S22, 0xfcefa3f8L); /* 30 */

c = GG(c, d, a, b, x[7], S23, 0x676f02d9L); /* 31 */

b = GG(b, c, d, a, x[12], S24, 0x8d2a4c8aL); /* 32 */

/* Round 3 */

a = HH(a, b, c, d, x[5], S31, 0xfffa3942L); /* 33 */

d = HH(d, a, b, c, x[8], S32, 0x8771f681L); /* 34 */

c = HH(c, d, a, b, x[11], S33, 0x6d9d6122L); /* 35 */

b = HH(b, c, d, a, x[14], S34, 0xfde5380cL); /* 36 */

a = HH(a, b, c, d, x[1], S31, 0xa4beea44L); /* 37 */

d = HH(d, a, b, c, x[4], S32, 0x4bdecfa9L); /* 38 */

c = HH(c, d, a, b, x[7], S33, 0xf6bb4b60L); /* 39 */

b = HH(b, c, d, a, x[10], S34, 0xbebfbc70L); /* 40 */

a = HH(a, b, c, d, x[13], S31, 0x289b7ec6L); /* 41 */

d = HH(d, a, b, c, x[0], S32, 0xeaa127faL); /* 42 */

c = HH(c, d, a, b, x[3], S33, 0xd4ef3085L); /* 43 */

b = HH(b, c, d, a, x[6], S34, 0x4881d05L); /* 44 */

a = HH(a, b, c, d, x[9], S31, 0xd9d4d039L); /* 45 */

d = HH(d, a, b, c, x[12], S32, 0xe6db99e5L); /* 46 */

c = HH(c, d, a, b, x[15], S33, 0x1fa27cf8L); /* 47 */

b = HH(b, c, d, a, x[2], S34, 0xc4ac5665L); /* 48 */

/* Round 4 */

a = II(a, b, c, d, x[0], S41, 0xf4292244L); /* 49 */

d = II(d, a, b, c, x[7], S42, 0x432aff97L); /* 50 */

c = II(c, d, a, b, x[14], S43, 0xab9423a7L); /* 51 */

b = II(b, c, d, a, x[5], S44, 0xfc93a039L); /* 52 */

a = II(a, b, c, d, x[12], S41, 0x655b59c3L); /* 53 */

d = II(d, a, b, c, x[3], S42, 0x8f0ccc92L); /* 54 */

c = II(c, d, a, b, x[10], S43, 0xffeff47dL); /* 55 */

b = II(b, c, d, a, x[1], S44, 0x85845dd1L); /* 56 */

a = II(a, b, c, d, x[8], S41, 0x6fa87e4fL); /* 57 */

d = II(d, a, b, c, x[15], S42, 0xfe2ce6e0L); /* 58 */

c = II(c, d, a, b, x[6], S43, 0xa3014314L); /* 59 */

b = II(b, c, d, a, x[13], S44, 0x4e0811a1L); /* 60 */

a = II(a, b, c, d, x[4], S41, 0xf7537e82L); /* 61 */

d = II(d, a, b, c, x[11], S42, 0xbd3af235L); /* 62 */

c = II(c, d, a, b, x[2], S43, 0x2ad7d2bbL); /* 63 */

b = II(b, c, d, a, x[9], S44, 0xeb86d391L); /* 64 */

state[0] += a;

state[1] += b;

state[2] += c;

state[3] += d;

}

private void Encode(byte[] output, long[] input, int len) {

int i, j;

for (i = 0, j = 0; j len; i++, j += 4) {

output[j] = (byte) (input[i] 0xffL);

output[j + 1] = (byte) ((input[i] 8) 0xffL);

output[j + 2] = (byte) ((input[i] 16) 0xffL);

output[j + 3] = (byte) ((input[i] 24) 0xffL);

}

}

private void Decode(long[] output, byte[] input, int len) {

int i, j;

for (i = 0, j = 0; j len; i++, j += 4)

output[i] = b2iu(input[j]) | (b2iu(input[j + 1]) 8)

| (b2iu(input[j + 2]) 16) | (b2iu(input[j + 3]) 24);

return;

}

public static long b2iu(byte b) {

return b 0 ? b 0x7F + 128 : b;

}

public static String byteHEX(byte ib) {

char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a',

'b', 'c', 'd', 'e', 'f' };

char[] ob = new char[2];

ob[0] = Digit[(ib 4) 0X0F];

ob[1] = Digit[ib 0X0F];

String s = new String(ob);

return s;

}

}

关于java039和的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站。