数据连接池

tomcat中一定要放class-12
web.xml中的配置

<!-- context-param begin 数据连接池-->
 <context-param>
  <param-name>driver</param-name>
  <param-value>oracle.jdbc.driver.OracleDriver</param-value>
 </context-param>
 <context-param>
  <param-name>conn</param-name>
  <param-value>
   jdbc:oracle:thin:@127.0.0.1:1521:oracle
  </param-value>
 </context-param>
 <context-param>
  <param-name>user</param-name>
  <param-value>scott</param-value>
 </context-param>
 <context-param>
  <param-name>password</param-name>
  <param-value>tiger</param-value>
 </context-param>
<!-- context-param end -->

<!-- /loginServlet   直连数据库中时,用到的参数是在servlet中声明的--> 
 <servlet>
  <servlet-name>loginServlet</servlet-name>
  <servlet-class>test.LoginServlet</servlet-class>
  <init-param>
   <param-name>driver</param-name>
   <param-value>oracle.jdbc.driver.OracleDriver</param-value>
  </init-param>
  <init-param>
   <param-name>conn</param-name>
   <param-value>
    jdbc:oracle:thin:@127.0.0.1:1521:oracle
   </param-value>
  </init-param>
  <init-param>
   <param-name>user</param-name>
   <param-value>scott</param-value>
  </init-param>
  <init-param>
   <param-name>password</param-name>
   <param-value>tiger</param-value>
  </init-param>
 </servlet>
 <servlet-mapping>
  <servlet-name>loginServlet</servlet-name>
  <url-pattern>/loginServlet</url-pattern>
 </servlet-mapping>
 
<!-- /servlet/cookieTestServlet --> 

META-INF中----------------------------------------------context.xml中的代码
<?xml version="1.0" encoding="UTF-8"?>
<Context>
   <Resource name="jdbc/ORACLE"  
       auth="Container"      
       type="javax.sql.DataSource"      
       driverClassName="oracle.jdbc.driver.OracleDriver"      
       url="jdbc:oracle:thin:@127.0.0.1:1521:oracle"      
       username="scott"      
       password="tiger"      
       maxActive="100"      
       maxIdle="30"      
       maxWait="10000" /> 
<!--        
  //2、使用连接池获取连接
//  try{
//   InitialContext initContext = new InitialContext();
//   Context context = (Context)initContext.lookup

("java:comp/env");
//   DataSource ds = (DataSource) context.lookup

("jdbc/ORACLE");  
//
   Context context = new InitialContext();
   DataSource ds = (DataSource) context.lookup

("java:comp/env/jdbc/ORACLE"); 
//   
//   conn = ds.getConnection();
//   System.out.println("通过连接池连接到数据库。");
//  }catch(Exception e){
//   throw new ServletException(e);  
//  }    

 -->   
</Context>
在实际中的应用-------------------------------------------------------------------
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.naming.Context;   //Context包
import javax.naming.InitialContext;  //InitialContext包
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javax.sql.DataSource;  //记住是sql中的DataSource

public class LoginServlet extends HttpServlet{
 private Connection conn = null;

 public void init() throws ServletException {
  //1、使用servlet的初始化参数获取连接
 ServletConfig config = getServletConfig();//这里以config作为变量名,不用修

改下面代码了
  //2、使用连接池获取连接
    try{
     InitialContext initContext = new 

InitialContext();
     Context context = (Context)

initContext.lookup("java:comp/env");
     DataSource ds = (DataSource) 

context.lookup("jdbc/ORACLE");  

//     Context context = new InitialContext();
//     DataSource ds = (DataSource) 

context.lookup("java:comp/env/jdbc/ORACLE"); 
     
     conn = ds.getConnection();
     System.out.println("通过连接池连接到数据库

。");
    }catch(Exception e){
     throw new ServletException(e);  
    }
   }
/*  //3、jdbc做法
   
  String dbdriver = config.getInitParameter("driver");
  String dburl = config.getInitParameter("conn");
  String user = config.getInitParameter("user");
  String password = config.getInitParameter("password");
  System.out.println("---driver="+dbdriver+"  url="+dburl);
  try {
   Class.forName(dbdriver);
   conn = DriverManager.getConnection(dburl, user, password);
   System.out.println("直接连接到数据库。");
  } catch (Exception e) {
   throw new ServletException(e);
  }
 }
*/

 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  //先获取前台传过来的用户名和密码
  String username = req.getParameter("username");
  String password = req.getParameter("password");
  
  /*boolean flag = if (validateUser(username, password));
  
  if(flag){//表示验证通过,允许登录
   resp.setContentType("text/html; charset=utf-8");
   resp.setCharacterEncoding("utf-8");
   PrintWriter out = resp.getWriter();
   out.println("登录成功, 欢迎"+username+"访问本系统。");
  }else{
   req.setAttribute("msg", "用户名或者密码不正确,请重新输入

!");
   RequestDispatcher rd = req.getRequestDispatcher("/WEB-

INF/login2.jsp");
   rd.forward(req, resp);
  }*/
//  req.setCharacterEncoding("utf-8");//注意:当用户名为汉字“张三”时

,需要使用本行代码;将request传入的汉字转为有效字符;
//  resp.setContentType("text/html;charset=utf-8");//注意:本行代码保

证在页面正确输出汉字;
 
  if (validateUser(username, password)) {//连接到数据库进行判断用户

名和口令
//   if("java".equals(username) && "java".equals(password)){//

直接在本行代码判断用户名和口令
    PrintWriter out = resp.getWriter();
    
    out.println("<HTML>");
    out.println("  

<HEAD><TITLE>welcome</TITLE></HEAD>");
    out.println("  <BODY> <CENTER>");
    out.print("  登录成功, welcome  ");
    out.print(username);
    out.println(".</CENTER>  </BODY>");
    out.println("</HTML>");
    
    out.flush();
    out.close();
   } else {
    System.out.println("您输入用户名是:"+username+",

密码是:"+password+";"+"用户名或者密码错误,请重新输入!");
    /*RequestDispatcher rd = req.getRequestDispatcher

("/login.jsp");*/
    req.setAttribute("msg", "用户名或者密码不正确,请

重新输入!");
    RequestDispatcher rd = req.getRequestDispatcher

("/WEB-INF/login2.jsp");
    rd.forward(req, resp);
   }
 }

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


public void destroy() {
 try {
  if (conn != null){
   conn.close();
  }
 } catch (SQLException e) {
  e.printStackTrace();
 }
}

private boolean validateUser(String username, String password) {
 PreparedStatement ps = null;
 ResultSet rs = null;
 try {
  ps = conn.prepareStatement("SELECT * FROM java_web_user WHERE 

user_id=? AND password=?");
  ps.setString(1, username);
  ps.setString(2, password);
  rs = ps.executeQuery();
  if (rs.next()){
   return true;
  }
 } catch (SQLException e) {
  e.printStackTrace();
 }finally{

  try {
   if (rs != null){
    rs.close();
   }
   if (ps != null){
    ps.close();
   }
  } catch (SQLException e) {
   e.printStackTrace();
  }
 }
 return false;
}
}
login.jsp页面-----------------------------------------------------------------
<%@ page contentType="text/html; charset=GBK"%>
 <% request.setCharacterEncoding("GBK"); %>
<%
 String path = request.getContextPath();
 String basePath = request.getScheme() + "://"
   + request.getServerName() + ":" + request.getServerPort()
   + path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
 <head>
  <base href="<%=basePath%>">

  <title>My JSP 'login.jsp' starting page</title>

  <meta http-equiv="pragma" content="no-cache">
  <meta http-equiv="cache-control" content="no-cache">
  <meta http-equiv="expires" content="0">
  <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
  <meta http-equiv="description" content="This is my page">
  <!--
 <link rel="stylesheet" type="text/css" href="styles.css">
 -->

 </head>

 <body>
  <center>
   <h1>请登录本系统 </h1>
   <br>
   <font color="red">${msg}</font>
   <br>
   <form action="<%=basePath %>loginServlet" method="post">
    <table border="1">
     <tr>
      <td>姓名</td>
      <td><input type="text" 

name="username"></td>
     </tr>
     <tr>
      <td>密码</td>
      <td><input type="password" 

name="password"></td>
     </tr>
     <tr>
      <td colspan="2">
       <input type="submit" 

value="登录">
       <input type="reset" 

value="重置">
      </td>
     </tr>
    </table>
   </form>
  </center>
 </body>
</html>


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值