jsp---登陆程序实现
数据库脚本.sql
/*
Navicat MySQL Data Transfer
Source Server : localhost_3306
Source Server Version : 50022
Source Host : localhost:3306
Source Database : logint
Target Server Type : MYSQL
Target Server Version : 50022
File Encoding : 65001
Date: 2013-06-06 11:44:55
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `user_login`
-- ----------------------------
DROP TABLE IF EXISTS `user_login`;
CREATE TABLE `user_login` (
`username` varchar(30) NOT NULL,
`password` varchar(30) NOT NULL,
`id` int(30) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=gbk;
-- ----------------------------
-- Records of user_login
-- ----------------------------
login.html:
<html> <head> <script language="javaScript"> function validate(f){ if(!(/^\w{5,15}$/.test(f.username.value))){ alert(“用户名必须是5到15位!”);//碰到莫名其妙的错,这一行引号不是英文的,所以导致验证失效,导致直接可以跳转到check.jsp中 f.username.focus(); return false; } if(!(/^\w{5,15}$/.test(f.password.value))){ alert(“密码必须是5到15位!”); f.password.focus(); return false; } return true; } </script>
<body> <form action="check.jsp" method="post" onSubmit="return validate(this)"> <center> <table border="1"> <tr> <td colspan="2" align="center">系统用户登录</td> </tr> <tr> <td >用户名:</td> <td><input type="text" name="username" ></td> </tr> <tr> <td >密  码:</td> <td><input type="text" name="password" ></td> </tr> <tr > <td colspan="2" align="center"> <input type="submit" value="提交"> <input type="reset" value="重置"> </td> </tr> </table> </center> </form> </body> </html>
check.jsp
<%@page contentType="text/html;charset=GBK"%> <%@page import="java.sql.*"%> <html> <head> <title>check.jsp</title> </head> <%! public static final String DBDRIVER = "com.mysql.jdbc.Driver";//数据库驱动 public static final String DBURL = "jdbc:mysql://localhost:3306/loginT";//数据库连接地址 public static final String DBUSER = "root";//数据库用户名 public static final String DBPASS = "admin";//数据库密码 %> <% Connection conn = null;//声明数据量连接对象 PreparedStatement pstmt = null;//声明数据库操作对象 ResultSet rs = null;//声明一个结果集对象 boolean flag = false;// 定义变量,如果用户是合法用户,则将falg标记为true String sql = null;//用于保存sql语句 %> <% String name = request.getParameter("username"); String password = request.getParameter("password"); try{ sql = "select username from user_login where username=? and password=?" ; //加载驱动程序 Class.forName(DBDRIVER); //连接数据库 conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS); //实例化数据库操作对象 pstmt = conn.prepareStatement(sql); //设置pstmt的内容 pstmt.setString(1,name); pstmt.setString(2,password); //查询记录 rs = pstmt.executeQuery(); //判断是否有记录 if(rs.next()){ flag = true; } //关闭 rs.close(); pstmt.close(); conn.close(); }catch(Exception e){ } %> <% if(flag){ %> <jsp:forward page="success.html" /> <% } else{ %> <jsp:forward page="failure.html" /> <% } %> </html>