【发布时间】:2019-06-10 11:19:14
【问题描述】:
我有一个 jsp 页面 LoginCheck.jsp,我想调用数据库来验证登录详细信息和一个 java 类 CmDatabaseConnection,我在其中创建连接池。
LoginCheck.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ page import ="java.sql.*" %>
<%@ page import ="java.util.Date" %>
<%@ page import ="com.wipro.clk.CmDatabaseConnection" %>
<%@ page import ="com.mchange.v2.c3p0.ComboPooledDataSource" %>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String userid = request.getParameter("username");
System.out.println("entered username is " +userid);
String pwd=request.getParameter("password");
System.out.println("entered password is " +pwd);
ComboPooledDataSource dataSource = CmDatabaseConnection.makeConnectionPool();
Connection con=dataSource.getConnection();
/* Class.forName ("oracle.jdbc.driver.OracleDriver");
Connection con= DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521/CCB25", "CISADM", "CISADM"); */
//
// USE BINDS ! to avoid sql injection
// push the userid and passwd comparison to the db
// no need to get the password and compare locally
//
String query = "select password from cmlogin where userid=? and password=?";
PreparedStatement st = con.prepareStatement(query);
st.setString(1,userid);
st.setString(2,pwd);
ResultSet rs = st.executeQuery();
System.out.println("Size is "+st.getFetchSize());
String pass1;
// .next will advance if the query has any results
//
if (rs.next()) {
pass1 = rs.getString("password");
System.out.println("value of result pass1" +pass1);
String name =request.getParameter("username");
System.out.println(name);
session.setAttribute("nam",name);
%>
<jsp:forward page="admin.jsp"></jsp:forward>
<%
} else {
String msg="Username or password failed";
%>
<center> <p style="font-family:verdana;color:red;"> <%=msg %>
<jsp:include page="Login.jsp"></jsp:include>
<% }
con.close();
%>
</body>
CmDatabaseConnection.java
package com.wipro.clk;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class CmDatabaseConnection {
public static ComboPooledDataSource makeConnectionPool()
{
ComboPooledDataSource cpds = new ComboPooledDataSource();
try
{
cpds.setDriverClass("oracle.jdbc.driver.OracleDriver");
cpds.setJdbcUrl("jdbc:oracle:thin:@localhost:1521/CCB25");
cpds.setUser("CISADM");
cpds.setPassword("CISADM");
cpds.setMaxPoolSize(100);
cpds.setMinPoolSize(5);
cpds.setMaxStatements(180);
cpds.setAcquireIncrement(20);
}
catch (Exception ex)
{
ex.printStackTrace();
}
return cpds;
}
}
现在我的疑问是,是否有必要在我想调用数据库时调用以下行?
ComboPooledDataSource dataSource = CmDatabaseConnection.makeConnectionPool();
Connection con=dataSource.getConnection();
或者是否有可能获得一次 db 连接并在每个 java/jsp 文件中使用相同的连接?如果我们在每个文件中都使用相同的,那么是否不需要关闭连接?
【问题讨论】: