开发工具:eclipse-jee-neon-2-642 MySQL5.7.13
一 新建web工程,命名BBS
二 通过JDBC连接MySQL
1.将下载好的
mysql-connector-java-5.1.20-bin.jar包赋值到BBS项目的WEB-INF/lib目录下。
2.在MySQL中新建一个bbs数据库。如图
3.在Eclipse的Windows菜单->Show View->Data Source Explorer,打开数据源浏览窗体,点击New选项,选择MySQL,再如图所示,通过点击Test Connection来测试是否连接成功,如果ping succeeded表示连接成功。
4.在工程中新建一个文件夹,命名为SQL,在该文件夹下,新建一个SQL file,如图:
在sql.sql文件中添加SQL语言,新建一个表,插入一些数据,代码如下:
use bbs;
create table article
(
id int primary key auto_increment,
pid int,
rootid int,
title varchar(255),
cont text,
pdate datetime,
isleaf int
);
insert into article values (null, 0, 1, '蚂蚁大战大象', '蚂蚁大战大象', now(), 1);
insert into article values (null, 1, 1, '大象被打趴下了', '大象被打趴下了',now(), 1);
insert into article values (null, 2, 1, '蚂蚁也不好过','蚂蚁也不好过', now(), 0);
insert into article values (null, 2, 1, '瞎说', '瞎说', now(), 1);
insert into article values (null, 4, 1, '没有瞎说', '没有瞎说', now(), 0);
insert into article values (null, 1, 1, '怎么可能', '怎么可能', now(), 1);
insert into article values (null, 6, 1, '怎么没有可能', '怎么没有可能', now(), 0);
insert into article values (null, 6, 1, '可能性是很大的', '可能性是很大的', now(), 0);
insert into article values (null, 2, 1, '大象进医院了', '大象进医院了', now(), 1);
insert into article values (null, 9, 1, '护士是蚂蚁', '护士是蚂蚁', now(), 0);
执行SQL语句,如下图:
则表示数据插入成功(注意如果出现中文乱码,需要修改数据库的编码格式为utf-8)。
三 BBS管理员登陆界面
在WebContent目录下,新建login.jsp文件,添加代码如下:
<%@ page language="java" contentType="text/html; charset=gbk"
pageEncoding="gbk"%>
<!--内嵌java代码,主要控制逻辑跳转-->
<%
String action = request.getParameter("action");
if (action != null && action.trim().equals("login")) {
String username = request.getParameter("uname");
String password = request.getParameter("pwd");
if(username == null || !username.trim().equals("admin")) {
out.print("<script language='javaScript'> alert('用户名错误');</script>");
} else if(password == null || !password.trim().equals("admin")) {
out.print("<script language='javaScript'> alert('密码错误');</script>");
} else {
session.setAttribute("adminLogined" , "true");
response.sendRedirect("articleFlat.jsp");//重定向到某一个页面
}
}
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gbk">
<title>管理员登陆</title>
</head>
<body>
<h2 align="center">欢迎登陆</h2>
<form action="login.jsp" method="post">
<input type="hidden" name="action" value="login"/>
<table align="center">
<tr>
<td>用户名:</td><td><input type="text" name="uname"/></td> </tr>
<br>
<tr>
<td>密码:</td><td><input type="password" name="pwd" /></td>
</tr>
<br>
<td align="center">
<input type="submit" value="login" />
<input type="reset" value="reset" />
</td>
</table>
</form>
</body>
</html>
添加完成,运行程序,得到如图所示界面: