文章目录
教你手把手完成博客系统(一)
源码链接在文末~
-
由四个页面构成
1.博客列表页:显示出当前网站上有哪些博客
2.博客详情页:点击列表的某个博客,就能进入对应的详情页,显示出博客的具体内容
3.博客编辑页:用户输入博客内容,发送到服务器
4.登录页:进行博客系统的登录。
通时,引入第三方库 editor.md 来实现makedown编辑功能
1.实现思路
1.实现博客列表页
让页面从服务器(数据库)拿到博客的数据
2.实现博客详情页
点击博客详情的时候,可以从服务器拿到博客的完整数据
3.实现登录功能
4.实现强制登录
当在未登录时,点击其他页面,都会跳转到登录页面。登录完成后才能使用
5.实现显示用户信息
从服务器获取。在列表页左侧拿到的是当前登录用户的信息。在博客详情页,拿到的是文章作者的信息
6.实现退出登录
7.发布博客
在博客编辑页,输入内容后,点击发布。将数据上传到服务器上并保存。
2.准备工作
1.创建项目
引入依赖,并导入前端页面
创建一个Maven项目
引入依赖
<dependencies>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.15.0</version>
</dependency>
</dependencies>
创建目录webapp和其下的 WEB-INF。创建web.xml文件
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
</web-app>
导入前端页面
会贴到最后
启动Tomcat显示成功
2.设计数据库
设计对应的表结构,把数据库相关代码进行封装
1.找到实体
博客(blog表)
用户(user表)
2.确认实体之间的关系
一对多
一个博客只能属于一个用户
一个用户可以发布多个博客
在博客表中引入userId这个属性
blog(blogId,title,content,postTime,userId)
user(userId,username,password)
在Main目录下创建db.xml文件
create database if not exists blog_system charset utf8;
-- 创建数据库
use blog_system;
drop table if exists blog;
drop table if exists user;
create table blog(
blogId int primary key auto_increment,
title varchar(1024),
content varchar(4096),
postTime datetime,
userId int
);
create table user(
userId int primary key auto_increment,
username varchar(50) unique,
password varchar(50)
);
-- 插入一些测试数据,方便后续进行测试
insert into blog values (1,'这是第一篇博客','#从今天开始我要开始写博客',now(),1);
insert into blog values (2,'这是第二篇博客','#从明天开始我要开始写博客',now(),1);
insert into blog values (3,'这是第三篇博客','#从后天开始我要开始写博客',now(),1);
insert into user values (1,'zhangsan',123);
insert into user values (2,'lisi',123);
mysql> desc blog;
+----------+---------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+---------------+------+-----+---------+----------------+
| blogId | int(11) | NO | PRI | NULL | auto_increment |
| title | varchar(1024) | YES | | NULL | |
| content | varchar(4096) | YES | | NULL | |
| postTime | datetime | YES | | NULL | |
| userId | int(11) | YES | | NULL | |
+----------+---------------+------+-----+---------+----------------+
5 rows in set (0.01 sec)
mysql> desc user;
+----------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+----------------+
| userId | int(11) | NO | PRI | NULL | auto_increment |
| username | varchar(50) | YES | UNI | NULL | |
| password | varchar(50) | YES | | NULL | |
+----------+-------------+------+-----+---------+----------------+
3.封装数据库操作的代码
创建一个包,model。专门用来存储数据库相关的操作
model模型
MVC结构是网站开发中的常用结构
M model:存放操作数据的代码
V view :存放操作/构造界面的代码
C controller :存放业务逻辑,处理前端请求
封装数据库建立连接的操作,使用单例模式表示dataSource
DBUtil类
- 完成对数据库建立连接和关闭连接的实现
package model;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
import com.sun.corba.se.pept.transport.ConnectionCache;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* Created with IntelliJ IDEA.
* Description:
* User: Lenovo
* Author: Weng-Jiaming
* Date: 2024-05-20
* Time: 21:07
*/
//封装数据库建立连接的操作
public class DBUtil {
//单例模式
private volatile static DataSource dataSource = null;
private static DataSource getDataSource(){
if (dataSource==null){
synchronized(DBUtil.class){
if (dataSource==null){
dataSource = new MysqlDataSource();
((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/blog_system?characterEncoding=utf8&useSSL=false");
((MysqlDataSource)dataSource).setUser("root");
((MysqlDataSource)dataSource).setPassword("密码");
}
}
}
return dataSource;
}
/**
* 建立连接诶
* @return
* @throws SQLException
*/
public static Connection getConnection() throws SQLException {
return getDataSource().getConnection();
}
/**
* 释放资源
* @param connection
* @param statement
* @param resultSet
* @throws SQLException
*/
public static void close(Connection connection, PreparedStatement statement, ResultSet resultSet) {
if (resultSet!=null){
//确保非空的情况下,才执行关闭操作
try {
resultSet.close();
//对每个close单独try-catch,前面抛的异常就不会干扰后面代码的执行。
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
if (statement!=null){
try {
statement.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
if (connection!=null){
try {
connection.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
}
4.创建实体类
每个表都需要一个专门的类来表示,表里的每一条数据,就会对应这个类中的一个对象。
把数据库中的数据和代码联系起来
博客实体类
package model;
/**
* Created with IntelliJ IDEA.
* Description:
* User: Lenovo
* Author: Weng-Jiaming
* Date: 2024-05-20
* Time: 21:34
*/
import java.sql.Timestamp;
/**
* Blog对象对应到blog表中的一条记录
* 表里有哪些列,类里就有多少属性
*/
public class Blog {
private int blogId;
private String title;
private String content;
private Timestamp postTime;
private int userId;
//生成getter/setter方法
public int getBlogId() {
return blogId;
}
public void setBlogId(int blogId) {
this.blogId = blogId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Timestamp getPostTime() {
return postTime;
}
public void setPostTime(Timestamp postTime) {
this.postTime = postTime;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
@Override
public String toString() {
return "Blog{" +
"blogId=" + blogId +
", title='" + title + '\'' +
", content='" + content + '\'' +
", postTime=" + postTime +
", userId=" + userId +
'}';
}
}
用户实体类
package model;
/**
* Created with IntelliJ IDEA.
* Description:
* User: Lenovo
* Author: Weng-Jiaming
* Date: 2024-05-20
* Time: 21:36
*/
/**
* 用户实体类
* 一个User对象对应一个user用户表的一条记录
*/
public class User {
private int userId;
private String username;
private String password;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"userId=" + userId +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
5.封装对两个表的操作
创建两个类BlogDao和UserDao,来完成针对博客表和用户表的增删改查操作。
Dao :Data Access Object 数据访问对象
package model;
/**
* Created with IntelliJ IDEA.
* Description:
* User: Lenovo
* Author: Weng-Jiaming
* Date: 2024-05-20
* Time: 21:52
*/
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* 通过BlogDao完成针对blog表的操作
*/
public class BlogDao {
//1.新增操作(提交博客时,存进表中)
public void insert(Blog blog) {
Connection connection = null;
PreparedStatement statement = null;
try {
//1.建立连接诶
connection = DBUtil.getConnection();
//2.构造SQL
String sql = "insert into blog values(null,?,?,now(),?)";
statement = connection.prepareStatement(sql);
statement.setString(1, blog.getTitle());
statement.setString(2, blog.getContent());
statement.setInt(3, blog.getUserId());
//3.执行SQL
statement.executeUpdate();
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
//5.回收资源
DBUtil.close(connection, statement, null);
}
}
//2.查询博客列表(博客列表页)
//把数据库中所有的博客都拿到
public List<Blog> getBlogs() {
List<Blog> blogList = new ArrayList<>();
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
connection = DBUtil.getConnection();
String sql = "select * from blog";
statement = connection.prepareStatement(sql);
resultSet = statement.executeQuery();
while (resultSet.next()) {
Blog blog = new Blog();
blog.setBlogId(resultSet.getInt("blogId"));
blog.setTitle(resultSet.getString("title"));
String content = resultSet.getString("content");
//在列表页显示的正文只需要显示一小部分
//需要对content进行截取
if (content.length() > 100) {
content = content.substring(0, 100) + "...";
}
blog.setContent(content);
blog.setPostTime(resultSet.getTimestamp("postTime"));
blog.setUserId(resultSet.getInt("userId"));
blogList.add(blog);
}
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
DBUtil.close(connection, statement, resultSet);
}
return blogList;
}
//3.根据博客id查询指定的博客
public Blog getBlog(int blogId) {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
connection = DBUtil.getConnection();
String sql = "select * from blog where blogId = ?";
statement = connection.prepareStatement(sql);
statement.setInt(1, blogId);
resultSet = statement.executeQuery();
//拿着blogId进行查询,blogId是主键,是唯一的,
// 查询结果非0即1,不需要while进行遍历
if (resultSet.next()){
Blog blog = new Blog();
blog.setBlogId(resultSet.getInt("blogId"));
blog.setTitle(resultSet.getString("title"));
blog.setContent(resultSet.getString("content"));
blog.setPostTime(resultSet.getTimestamp("postTime"));
blog.setUserId(resultSet.getInt("userId"));
return blog;
}
} catch (SQLException e) {
throw new RuntimeException(e);
}finally {
DBUtil.close(connection,statement,resultSet);
}
return null;
}
//4.根据博客Id删除博客
public void delete(int blogId) {
Connection connection = null;
PreparedStatement statement = null;
try {
connection = DBUtil.getConnection();
String sql = "delete from blog where blogId = ? ";
statement = connection.prepareStatement(sql);
statement.setInt(1,blogId);
statement.executeUpdate();
} catch (SQLException e) {
throw new RuntimeException(e);
}finally {
DBUtil.close(connection,statement,null);
}
}
}
package model;
/**
* Created with IntelliJ IDEA.
* Description:
* User: Lenovo
* Author: Weng-Jiaming
* Date: 2024-05-20
* Time: 21:52
*/
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* 通过UserDao完成针对user表的操作
*/
public class UserDao {
//暂时不需要新增,不需要实现“注册用户”
//暂时不需要删除,不需要实现“注销用户”
//1.根据userId来查到对应的用户信息(获取用户信息)
public User getUserById(int userId) {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
//1,建立连接诶
connection = DBUtil.getConnection();
//2.构造SQL
String sql = "select * from user where userId = ?";
statement = connection.prepareStatement(sql);
statement.setInt(1, userId);
resultSet = statement.executeQuery();
if (resultSet.next()){
User user = new User();
user.setUserId(resultSet.getInt("userId"));
user.setUsername(resultSet.getString("username"));
user.setPassword(resultSet.getString("password"));
return user;
}
} catch (SQLException e) {
throw new RuntimeException(e);
}finally {
DBUtil.close(connection,statement,resultSet);
}
return null;
}
//2.根据username 来查到对应的用户信息(登录)
public User getUserByName(String username) {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
//1,建立连接诶
connection = DBUtil.getConnection();
//2.构造SQL
String sql = "select * from user where username = ?";
statement = connection.prepareStatement(sql);
statement.setString(1, username);
resultSet = statement.executeQuery();
if (resultSet.next()){
User user = new User();
user.setUserId(resultSet.getInt("userId"));
user.setUsername(resultSet.getString("username"));
user.setPassword(resultSet.getString("password"));
return user;
}
} catch (SQLException e) {
throw new RuntimeException(e);
}finally {
DBUtil.close(connection,statement,resultSet);
}
return null;
}
}
JDBC代码大同小异,因此会有一些数据库的框架来进一步的封装。MyBatis、MyBatisPlus、JPA等等
查看源代码,请点击:博客系统完整代码