jsp基础语法 六 jsp+jdbc访问数据库
学习过了jsp基础语法以及HTML和javascript的用法之后,jsp+jdbc连接数据库开发动态WEB网页就可以实现了。
对于学过java SE的同学来说,数据库的操作并不陌生,如果有忘记的或者不会的可以到http://zhaoyuqiang.blog.51cto.com/6328846/1127658 学习。
jsp中的数据库连接又是如何呢? 怎样才能利用上我们学过的HTML和javascript的知识呢? 这就是我们这一篇文章的学习内容----jsp+jdbc访问数据库。
我们就以一个实例来说明jsp+jdbc访问数据库 ---用户登录实例。 就像登录邮箱一样,用户输入账号和密码,如果正确的话就跳转到主页上,如果错误的话就提示或者跳转到错误页上。如下图所示:
首先先建立数据库,在MySQL中建立数据库test,建立表 users.如下图所示
数据库建完后在MyEclipse中建立项目,将MySQL的驱动包导进lib中。
建立第一个jsp页面----登陆页面 login.jsp
<%@ page language="java" contentType="text/html" pageEncoding="utf-8"%> <html> <head> <title>登录页面</title> <script type="text/javascript"> // 验证 如果用户名和密码为空的话会出现提示框 function chkData() { if(frmLogin.username.value=="") { alert("请输入用户名。"); return false; } else if(frmLogin.userpassword.value=="") { alert("请输入密码。"); return false; } else { return true; } } </script> </head> <body> <center><h4>用户登录</h4></center> <form name="frmLogin" action="doLogin.jsp" method="post"> <table align="center" border="1"> <tr> <td>用户名:</td> <td><input type="text" name="username"/></td> </tr> <tr> <td>密 码:</td> <td><input type="password" name="userpassword"/></td> </tr> <tr> <td colspan="2" align="center"> <input type="submit" value="登录" onClick="return chkData();"/> <input type="reset" value="重置"/> </td> </tr> </table> </form> </body> </html>
建立第二个页面 检查页面 chklogin.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <%@page import="java.sql.*"%> <% //接收客户端传来的数据 request.setCharacterEncoding("utf-8"); String username = request.getParameter("username"); String userpassword = request.getParameter("userpassword"); //进行数据库查询 final String CLS="com.mysql.jdbc.Driver"; final String URL="jdbc:mysql://localhost:3306/test"; final String USER="root"; final String PWD="425680992"; Connection conn = null; PreparedStatement pStmt = null; ResultSet rs = null; try{ Class.forName(CLS); conn = DriverManager.getConnection(URL, USER, PWD); String sql = "select * from user where " + " username=? and userpassword=?"; pStmt = conn.prepareStatement(sql); pStmt.setString(1, username); pStmt.setString(2, userpassword); rs= pStmt.executeQuery(); if(rs.next()){ //登录成功 //转向 response.sendRedirect("index.jsp"); }else{ response.sendRedirect("login.jsp"); } }catch(Exception ex){ ex.printStackTrace(); } conn.close(); %>
建立第三个页面 成功页(主页) index.jsp
<%@ page contentType="text/html" pageEncoding="utf-8"%> <html> <head> <title>主页</title> </head> <body> <center> <h1>登录操作</h1> <h2>登录成功</h2> <h2>欢迎<font color="red"><%=request.getParameter("uname")%></font>光临!!</h2> </center> </body> </html>
建立第四个页面 失败页 fail.jsp
<%@ page contentType="text/html" pageEncoding="GB2312"%> <html> <head> <title>失败页</title> </head> <body> <center> <h1>登录操作</h1> <h2>登录失败,请重新<a href="login.jsp">登录!</a></h2> </center> </body> </html>
运行结果就不再演示了。
注意事项:
1. 对于数据库的操作代码都要放在<%%>里面。
2. 数据库的代码写法并不是一成不变的,但是其基本思想是一样的。
3.注意编码的操作。
本文出自 “赵玉强的博客” 博客,请务必保留此出处http://zhaoyuqiang.blog.51cto.com/6328846/1128403