壹
如果每一款APP的登录界面审核机制为
" admin".equles(username)&&"123456".equles(password)
那么局限性太高,数据成本高,我们之所以连接数据库,是因为APP对应着多个用户,而不是一个用户。
贰
(1)建立数据库
打开MySQL
1、create database db_shop;(创建库)
2、CREATE TABLE `admin_info` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(32) NOT NULL,
`pwd` varchar(64) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
(创建admin_info表,添加字段)
3、INSERT INTO `admin_info` VALUES ('1','admin', '123456');
(添加数据)
结果如下
(2)、安装jar包
包名为:mysql-connector-java-5.1.47-bin.jar
(3)、加载驱动
Class.forName("com.mysql.jdbc.Driver");
(4)、数据库连接
数据库的连接需要三样东西,分别是MySQL的URL地址、用户名、密码
(1)、URL地址:jdbc:mysql://localhost:3306/db_shop
(2)、用户名:root;
(3)、密码:****(依据个人而定)
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db_shop","root","****");
(5)、创建语句容器
Statement st = conn.createStatement();
(6)、创建结果集
ResultSet rs = st.executeQuery( "select * from admin_info where name='"+username+"' and pwd='"+password+"' ");
(7)、//判断所输入的内容是否和规定的一
if(rs.next()){//创建cookie对象
Cookie cookie1 = new Cookie("username",username);
Cookie cookie2 = new Cookie("password",password);
//设置生命周期
cookie1.setMaxAge(24*60*60);
cookie2.setMaxAge(24*60*60);
//保存cookie的值
response.addCookie(cookie1);
response.addCookie(cookie2);
session.setAttribute("username",username);
//session.setMaxInactiveInterval(1);
//跳转相应的页面
%>
<jsp:forward page="correct.jsp" ></jsp:forward>
<%
}
else
{
%>
<jsp:forward page="eroorpage.jsp"></jsp:forward>
<%
}
%>
(8)、关闭数据库
rs.close();
st.close();
conn.close();
顺序不能乱了