本文实例讲述了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文件:
welcome
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+"/"; %>My JSP 'login.jsp' starting page miThis is my JSP page.
程序使用tomcat进行发布,myeclipse进行编辑和调试
希望本文所述对大家的jsp程序设计有所帮助。
关键字词: