欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

jsp+jdbc实现连接数据库的方法

程序员文章站 2022-10-31 13:19:30
本文实例讲述了jsp+jdbc实现连接数据库的方法。分享给大家供大家参考。具体如下: 初次尝试jsp+jdbc,按照书上的例子折腾了半天,就是连不上数据库。于是在网上找材...

本文实例讲述了jsp+jdbc实现连接数据库的方法。分享给大家供大家参考。具体如下:

初次尝试jsp+jdbc,按照书上的例子折腾了半天,就是连不上数据库。于是在网上找材料,终于发现,老的jar包与新版数据库直接不兼容。于是下了新的数据库jdbc包,试了一下,果然搞定。这里,把这个程序跟大家共享下,程序实现了网页登录界面上提取用户名与密码,然后与数据库中用户名密码对应,从而决定程序是否通过登录。

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> 
  welcome<br>
  </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">注册新用户</a></td>
</tr>
</table>
</form>

程序使用tomcat进行发布,myeclipse进行编辑和调试

希望本文所述对大家的jsp程序设计有所帮助。