JSP连接数据库
1、将c3p0-0.9.5.2.jar/mchange-commons-java-0.2.11.jar/ojdbc6.jar三个包放在WEB-INF的lib文件夹下,将web.xml文件放到WEB-INF下
2、在java Resources的src下新建一个包,在包里新建一个类用来连接数据库
3、编写连接数据库的代码:
package com.hanqi.web; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import com.mchange.v2.c3p0.ComboPooledDataSource; public class CardDao { // private ComboPooledDataSource cp=new ComboPooledDataSource("helloc3p0"); //验证输入信息 public boolean checklogin(String cardid,String password) { boolean rtn=false; try { Connection conn=cp.getConnection(); PreparedStatement ps=conn.prepareStatement("select * from bank where bcardid=?and bpassword=?"); ps.setString(1, cardid); ps.setString(2, password); ResultSet rs=ps.executeQuery(); rtn=rs.next(); rs.close(); ps.close(); conn.close(); } catch (SQLException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } return rtn; } }
<%@page import="java.net.URLEncoder"%> <%@page import="com.hanqi.web.CardDao"%> <%@ 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> <% //设置不缓存页面 response.setHeader("cache-control","no-cache"); //设置定时跳转 //response.setHeader("refresh", "2;URL=http://www.baidu.com"); String cardid=request.getParameter("cardid"); String password=request.getParameter("password"); if(cardid==null||password==null||cardid.equals("")||password.equals("")) { out.write("请正确登陆系统"); response.setHeader("refresh", "3;"); } else{ //检查登陆信息 CardDao cd=new CardDao(); if(cd.checklogin(cardid, password)) { //out.write("登陆成功"); //无缓存,直接发送 response.getWriter().write("验证成功"); //创建cookie Cookie ck=new Cookie("cardid",cardid); //设置过期时间 ck.setMaxAge(10*24*60*60); //发送 response.addCookie(ck); // String name="张三 "; //对中文进行转码 Cookie ck1=new Cookie("username",URLEncoder.encode("张三")); response.addCookie(ck1); //创建session session.setAttribute("cardid", cardid); session.setAttribute("username", "李四"); //设置session的超时时间 //默认设置是20分钟 //如果连续超过20分钟没有任何请求发送给服务器,session就失效 //session.setMaxInactiveInterval(6); //页面跳转 response.sendRedirect("main.jsp"); //response.sendRedirect("http://www.baidu.com"); //获取application属性 int count=Integer.parseInt(application.getAttribute("count").toString()); out.print("<br>网站计数器:"+count++); application.setAttribute("count",count); } else { out.write("登录失败"); //跳回登陆页面 response.setHeader("refresh", "2;URL=bank.jsp"); } } %> </body> </html>