本文實(shí)例講述了jsp+jdbc實(shí)現(xiàn)連接數(shù)據(jù)庫(kù)的方法。分享給大家供大家參考。具體如下:
初次嘗試JSP+jdbc,按照書(shū)上的例子折騰了半天,就是連不上數(shù)據(jù)庫(kù)。于是在網(wǎng)上找材料,終于發(fā)現(xiàn),老的jar包與新版數(shù)據(jù)庫(kù)直接不兼容。于是下了新的數(shù)據(jù)庫(kù)jdbc包,試了一下,果然搞定。這里,把這個(gè)程序跟大家共享下,程序?qū)崿F(xiàn)了網(wǎng)頁(yè)登錄界面上提取用戶名與密碼,然后與數(shù)據(jù)庫(kù)中用戶名密碼對(duì)應(yīng),從而決定程序是否通過(guò)登錄。
inc.jsp文件:
%@ page import="java.sql.Connection"%> %@ page import="java.sql.DriverManager"%> %@ page import="java.sql.Statement"%> %@ page import="java.sql.ResultSet"%> %@ page import="java.sql.ResultSetMetaData"%> % String drv = "com.mysql.jdbc.Driver"; String url = "jdbc:mysql://localhost:3306/demo"; String usr = "nari"; String pwd = "nari"; %>
welcome.jsp文件:
html> body> welcomebr> /body> /html>
login_action.jsp文件:
%@ include file="inc.jsp" %> % String username = request.getParameter("username"); String password = request.getParameter("password"); if(username == null || password == null){ response.sendRedirect("index.jsp"); } boolean isValid = false; String sql = "select * from user where username='"+username+"'and password='"+password+"'"; out.println("===>"+sql); try{ Class.forName(drv).newInstance(); Connection conn = DriverManager.getConnection(url, usr,pwd); Statement stm = conn.createStatement(); ResultSet rs = stm.executeQuery(sql); if(rs.next())isValid = true; rs.close(); stm.close(); conn.close(); }catch(Exception e){ e.printStackTrace(); out.println(e); } if(isValid){ response.sendRedirect("welcome.jsp"); }else response.sendRedirect("index.jsp"); %> % /* if(username.endsWith("a"))response.sendRedirect("welcome.jsp"); else response.sendRedirect("index.jsp"); */%>
index.jsp文件:
%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> % String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> 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="description" content="This is my page"> /head> body> miThis is my JSP page.br> /body> /html> form name="form1" action="login_action.jsp" method="post"> table width="200" border="1"> tr> td colspan="2">登錄窗口/td> /tr> tr> td>用戶名/td> td>input type="text" name="username" size="10"/>/td> /tr> tr> td>密碼/td> td>input type ="password" name="password" size="10"/>/td> /tr> tr> td colspan="2">input type="submit" name="submit" value="登錄"> a href="register.jsp">注冊(cè)新用戶/a>/td> /tr> /table> /form>
程序使用tomcat進(jìn)行發(fā)布,myeclipse進(jìn)行編輯和調(diào)試
希望本文所述對(duì)大家的jsp程序設(shè)計(jì)有所幫助。
標(biāo)簽:青島 云浮 江西 丹東 宿州 西藏 貴州 紅河
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《jsp+jdbc實(shí)現(xiàn)連接數(shù)據(jù)庫(kù)的方法》,本文關(guān)鍵詞 jsp+jdbc,實(shí)現(xiàn),連接,數(shù)據(jù)庫(kù),;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。