创建必要的目录.引入需要的依赖
本系统要存入博客文章的信息,
创建博客表.博客的id,博客的标题,博客的内容,博客的日期,博文的博主id
也要存入用户的信息,
创建用户表,用户id,用户名,用户密码
create database if not exists MyBlogSystem;
use MyBlogSystem;
drop table if exists blog;
-- 创建一个博客表
create table blog (
blogId int primary key auto_increment,
title varchar(1024),
content mediumtext,
postTime datetime,
userId int
);
drop table if exists user;
-- 创建一个用户信息表
create table user (
userId int primary key auto_increment,
username varchar(128) unique,
password varchar(128)
);
创建包Dao用来放数据库的代码.
用来连接数据库
package Dao;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DBUtil {
private static final String URL = "jdbc:mysql://127.0.0.1:3306/MyBlogSystem?characterEncoding=utf8&useSSL=true&serverTimezone=UTC";
private static final String USERNAME = "root";
private static final String PASSWORD = "0000";
private static volatile DataSource dataSource = null;
private static DataSource getDataSource() {
if(dataSource == null){
synchronized(DBUtil.class){
if(dataSource == null){
dataSource = new MysqlDataSource();
((MysqlDataSource) dataSource).setURL(URL);
((MysqlDataSource) dataSource).setUser(USERNAME);
((MysqlDataSource) dataSource).setPassword(PASSWORD);
}
}
}
return dataSource;
}
public static Connection getConnection() throws SQLException {
return getDataSource().getConnection();
}
public static void close(Connection connection, PreparedStatement statement, ResultSet resultSet){
if(resultSet != null){
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(statement != null){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(connection != null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
Blog
package Dao;
import java.sql.Timestamp;
public class Blog {
public int blogId;
public String title;
public String content;
public Timestamp postTime;
public int userId;
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;
}
}
package Dao;
public class User {
public int userId;
public String username;
public 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;
}
}
package Dao;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
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,?,?,?,?)";
statement = connection.prepareStatement(sql);
statement.setString(1,blog.getTitle());
statement.setString(2,blog.getContent());
statement.setTimestamp(3,blog.getPostTime());
statement.setInt(4,blog.getUserId());
// 3. 执行 SQL 语句
int ret = statement.executeUpdate();
if(ret == 1){
System.out.println("插入成功");
}else {
System.out.println("插入失败");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtil.close(connection,statement,null);
}
}
// 2. 获取全部博客
public List<Blog> selectAll() {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
List<Blog> list = new ArrayList<>();
try {
// 1. 建立连接
connection = DBUtil.getConnection();
// 2. 拼装 SQL 语句
// 这里加上order by postTime desc 就可以根据时间排序了.
String sql = "select * from blog order by postTime desc ";
statement = connection.prepareStatement(sql);
// 3. 执行 SQL 语句
resultSet = statement.executeQuery();
// 4. 遍历结果集
while (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"));
list.add(blog);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtil.close(connection,statement,resultSet);
}
return list;
}
// 3. 获取个人博客
public List<Blog> selectAllPerson(int userId){
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
List<Blog> list = new ArrayList<>();
try {
// 1. 建立连接
connection = DBUtil.getConnection();
// 2. 拼装 SQL 语句
// 这里加上order by postTime desc 就可以根据时间排序了.
String sql = "select * from blog where userId = ? order by postTime desc ";
statement = connection.prepareStatement(sql);
statement.setInt(1,userId);
// 3. 执行 SQL 语句
resultSet = statement.executeQuery();
// 4. 遍历结果集
while (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"));
list.add(blog);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtil.close(connection,statement,resultSet);
}
return list;
}
// 4. 根据文章id获取指定博客
public Blog selectOne(int blogId) {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
// 1. 建立连接
connection = DBUtil.getConnection();
// 2. 拼装 SQL 语句
// 这里加上order by postTime desc 就可以根据时间排序了.
String sql = "select * from blog where blogId = ? ";
statement = connection.prepareStatement(sql);
statement.setInt(1,blogId);
// 3. 执行 SQL 语句
resultSet = statement.executeQuery();
// 4. 遍历结果集
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) {
e.printStackTrace();
} finally {
DBUtil.close(connection,statement,resultSet);
}
return null;
}
// 5. 删除指定文章id的博客
public void delete(int blogId) {
Connection connection = null;
PreparedStatement statement = null;
try {
// 1. 建立连接
connection = DBUtil.getConnection();
// 2. 拼装 SQL 语句
String sql = "delete from blog where blogId = ?";
statement = connection.prepareStatement(sql);
statement.setInt(1,blogId);
// 3. 执行 SQL 语句
int ret = statement.executeUpdate();
if(ret == 1){
System.out.println("删除成功");
}else{
System.out.println("删除失败");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtil.close(connection,statement,null);
}
}
// 6. 计算个人文章的总数
public Integer selectTotal(int userId) {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
// 1. 建立连接
connection = DBUtil.getConnection();
// 2. 拼装 SQL 语句
String sql = "select count(userId) from blog where userId = ?";
statement = connection.prepareStatement(sql);
statement.setInt(1,userId);
// 3. 执行 SQL 语句
resultSet = statement.executeQuery();
// 4. 遍历结果集
if (resultSet.next()){
return resultSet.getInt("count(userId)");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtil.close(connection,statement,resultSet);
}
return null;
}
public static void main(String[] args) {
BlogDao blogDao = new BlogDao();
Blog blog = new Blog();
blog.setContent("你好");
blog.setTitle("你好");
blog.setUserId(1);
blog.setPostTime(new Timestamp(System.currentTimeMillis()));
blogDao.insert(blog);
System.out.println(blogDao.selectAll());
}
}
package Dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class UserDao {
// 注册账号
public void insert(User user){
Connection connection = null;
PreparedStatement statement = null;
try {
// 1. 建立连接
connection = DBUtil.getConnection();
// 2. 拼装 SQL 语句
String sql = "insert into user values (null,?,?)";
statement = connection.prepareStatement(sql);
statement.setString(1,user.getUserName());
statement.setString(2, user.getPassWord());
// 3. 执行 SQL 语句
int ret = statement.executeUpdate();
if(ret == 1){
System.out.println("注册成功!");
}else{
System.out.println("注册失败!");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtil.close(connection,statement,null);
}
}
// 通过用户名查找
public User selectByName(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);
// 3. 执行 SQL 语句
resultSet = statement.executeQuery();
// 4. 查找结果集
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) {
e.printStackTrace();
} finally {
DBUtil.close(connection,statement,resultSet);
}
return null;
}
// 通过用户id查找
public User selectById(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);
// 3. 执行 SQL 语句
resultSet = statement.executeQuery();
// 4. 遍历结果集
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) {
e.printStackTrace();
} finally {
DBUtil.close(connection,statement,resultSet);
}
return null;
}
}
package View;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
@WebListener
public class ThymeleafConfig implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
ServletContext context = servletContextEvent.getServletContext();
// 1. 创建 engine 实例
TemplateEngine engine = new TemplateEngine();
// 2. 创建 resolve 对象
ServletContextTemplateResolver resolver = new ServletContextTemplateResolver(context);
resolver.setCharacterEncoding("utf-8");
resolver.setPrefix("/WEB-INF/template/");
resolver.setSuffix(".html");
// 3. 把 resolve 对象和 engine 关联起来
engine.setTemplateResolver(resolver);
// 4. 把 engine 放到 ServletContext;
context.setAttribute("engine",engine);
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
}
}
观看可以看出,内容的部分是动态的,其他都是静态的.(用户个人界面暂不管)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="css/list.css">
<link rel="stylesheet" href="css/common.css">
</head>
<body>
<div class="nav">
<img src="image/2.png" alt="头像">
<span class="title">我的博客系统</span>
<a href="home.html">主页</a>
<a href="edit.html">创作</a>
<a href="login.html">注销</a>
</div>
<div class="parent">
<div class="left">
<div class="card">
<img src="image/头像.jpg">
<span class="name">蜡笔小新</span>
<a href="#">github 地址</a>
<div class='one'>
<span>文章</span>
<span>分类</span>
</div>
<div class='one'>
<span>2</span>
<span>1</span>
</div>
</div>
</div>
<div class="right">
<div class="article" th:each="blog : ${blogs}">
<h2 class="title" th:text="${blog.title}">我的第一篇博客</h2>
<span class="date" th:text="${blog.postTime}">2022-4-17</span>
<div class="desc" th:text="${blog.content}">今天开始我要认真写博客</div>
<a th:href="${'details.html?blogId=' + blog.blogId}" class="more" >查看全文>></a>
</div>
</div>
</div>
</body>
</html>
package View;
import Dao.Blog;
import Dao.BlogDao;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@WebServlet("/index.html")
public class IndexServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
// 1.从数据库拿到所有的博客列表
BlogDao blogDao = new BlogDao();
List<Blog> blogs = blogDao.selectAll();
// 2.通过模板引擎渲染页面
TemplateEngine engine = (TemplateEngine) getServletContext().getAttribute("engine");
WebContext webContext = new WebContext(req,resp,getServletContext());
webContext.setVariable("blogs",blogs);
engine.process("index",webContext, resp.getWriter());
}
}
在之前css里面加上 overflow: auto 就有一个滚动条了
只需更改 SelectAll()中的代码.这里的80是随便设置的
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="css/moreList.css">
<link rel="stylesheet" href="css/common.css">
</head>
<body>
<div class="nav">
<img src="image/2.png" alt="头像">
<span class="title">我的博客系统</span>
<a href="home.html">主页</a>
<a href="edit.html">创作</a>
<a href="login.html">注销</a>
</div>
<div class="parent">
<div class="left">
<div class="card">
<img src="image/头像.jpg">
<span class="name">蜡笔小新</span>
<a href="#">github 地址</a>
<div class='one'>
<span>文章</span>
<span>分类</span>
</div>
<div class='one'>
<span>2</span>
<span>1</span>
</div>
</div>
</div>
<div class="right">
<div class="article">
<h2 class="title" th:text="${blog.title}">我的第一篇博客</h2>
<span class="date" th:text="${blog.postTime}">2022-4-17</span>
<div class="desc" th:text="${blog.content}">1</div>
</div>
</div>
</div>
</body>
</html>
package View;
import Dao.Blog;
import Dao.BlogDao;
import com.sun.xml.internal.bind.v2.schemagen.xmlschema.List;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/details.html")
public class DetailsServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
String str = req.getParameter("blogId");
if(str == null || str.length() == 0){
resp.getWriter().write("blogId缺失!");
return;
}
int blogId = Integer.parseInt(str);
BlogDao blogDao = new BlogDao();
Blog blog = blogDao.selectOne(blogId);
if(blog == null){
resp.getWriter().write("当前博客不存在!");
return;
}
TemplateEngine engine = (TemplateEngine) getServletContext().getAttribute("engine");
WebContext webContext = new WebContext(req,resp,getServletContext());
webContext.setVariable("blog",blog);
engine.process("details",webContext,resp.getWriter());
}
}
package View;
import Dao.User;
import Dao.UserDao;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
// 1. 获取用户名密码
String username = req.getParameter("username");
String password = req.getParameter("password");
// 2. 判断用户名密码是否为空
if(username == null || "".equals(username) || password == null || "".equals(password)){
resp.getWriter().write("<h3>用户名或者密码为空,登录失败!</h3>");
return;
}
// 3. 判断输入的用户名或者密码是否正确
UserDao userDao = new UserDao();
User user = userDao.selectByName(username);
if(user == null){
resp.getWriter().write("<h3>用户名或者密码错误,登录失败!</h3>");
return;
}
if(!user.getPassWord().equals(password)){
resp.getWriter().write("<h3>用户名或者密码错误,登录失败!</h3>");
return;
}
// 4. 登陆成功,就把user存到HttpSession中
HttpSession session = req.getSession(true);
session.setAttribute("user",user);
// 5. 重定向到主页
resp.sendRedirect("index.html");
}
}
package View;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet("/logout")
public class LogoutServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
// 1. 检查当前的用户是否登录
HttpSession session = req.getSession(false);
if(session == null){
resp.getWriter().write("<h3>当前未登录</h3>");
return;
}
// 2. 删除user
session.removeAttribute("user");
// 3. 重定向到登录页面
resp.sendRedirect("login.html");
}
}
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="css/common.css">
<link rel="stylesheet" href="css/login.css">
</head>
<body>
<div class="nav">
<img src="image/logo.png" alt="头像">
<span class="title">我的博客系统</span>
<a href="index.html">主页</a>
<a href="edit.html">创作</a>
<a href="register.html">注册</a>
</div>
<div id="one">
<div class="login">
<form action="register" method="post">
<div class="text">注册</div>
<div class="one"><span class="name">用户名</span><input type="text" class="user" name="username"></div>
<div class="one"><span class="name">密码</span><input type="password" class="password" name="password1"></div>
<div class="one"><span class="name">确认密码</span><input type="password" class="password" name="password2"></div>
<div class="submit"><input type="submit" value="注 册" ></div>
</form>
</div>
</div>
</body>
</html>
package View;
import Dao.User;
import Dao.UserDao;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html; charset=utf-8");
// 1. 获取输入的用户名和密码
String username = req.getParameter("username");
String password1 = req.getParameter("password1");
String password2 = req.getParameter("password2");
// 2. 如果有一个为空就注册失败
if (username == null || password1 == null || password2 == null || "".equals(username) || "".equals(password1) || "".equals(password2)) {
resp.getWriter().write("<h3>输入有误!注册失败!</h3>");
return;
}
UserDao userDao = new UserDao();
User user = userDao.selectByName(username);
// 如果user不为空.表示有人注册了
if(user!=null){
resp.getWriter().write("<h3>用户名已经被使用了</h3>");
return;
}
// 如果两次密码不一致注册失败
if(!password1.equals(password2)){
resp.getWriter().write("<h3>两次输入的密码不一致,注册失败!");
return;
}
// 这里就注册成功了
User user1 = new User();
user1.setUserName(username);
user1.setPassWord(password1);
userDao.insert(user1);
resp.sendRedirect("login.html");
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="css/common.css">
<link rel="stylesheet" href="css/edit.css">
<!-- 引入 editor.md 的依赖 -->
<link rel="stylesheet" href="editor.md/css/editormd.min.css" />
<script src="js/jquery.min.js"></script>
<script src="editor.md/lib/marked.min.js"></script>
<script src="editor.md/lib/prettify.min.js"></script>
<script src="editor.md/editormd.js"></script>
</head>
<body>
<div class="nav">
<img src="image/2.png" alt="头像">
<span class="title">我的博客系统</span>
<a href="index.html">主页</a>
<a href="edit.html">创作</a>
<a href="logout">注销</a>
</div>
<div class="leader">
<form action="edit" method="post" style="height:100%">
<div class="empOne">
<input type="text" class="title" value="在这里写下文章标题" onblur="if(this.value == '')this.value='在这里写下文章标题';" onclick="if(this.value == '在这里写下文章标题')this.value='';" name="title">
<input type="submit" value="发布文章" class="publish">
</div>
<div id="editor">
<textarea name="content" style="display:none;"></textarea>
</div>
</form>
</div>
<script>
// 初始化编辑器
var editor = editormd("editor", {
// 这里的尺寸必须在这里设置. 设置样式会被 editormd 自动覆盖掉.
width: "100%",
// 高度 100% 意思是和父元素一样高. 要在父元素的基础上去掉标题编辑区的高度
height: "calc(100% - 75px)",
// 编辑器中的初始内容
markdown: "# 在这里写下一篇博客",
// 指定 editor.md 依赖的插件路径
path: "editor.md/lib/",
saveHTMLToTextarea: true
});
</script>
</body>
</html>
package View;
import Dao.Blog;
import Dao.BlogDao;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;
@WebServlet("/edit")
public class EditServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
// 1. 获取参数
String title = req.getParameter("title");
String content = req.getParameter("content");
// 2. 判断是否存在
if(title==null || "".equals(title) || content==null || "".equals(content)){
resp.getWriter().write("<h3>文章标题或者内容不存在</h3>");
return;
}
// 插入到数据库中
Blog blog = new Blog();
blog.setContent(content);
blog.setTitle(title);
blog.setPostTime(new Timestamp(System.currentTimeMillis()));
BlogDao blogDao = new BlogDao();
blogDao.insert(blog);
// 重定向
resp.sendRedirect("index.html");
}
}
根据这里的blogId查找当前的userId,如果登录的userId等于当前的userId 就有删除按钮
前端改进
添加样式
#deleteA {
margin: 5px;
display: block;
text-align: center;
color:black;
text-decoration: none;
}
#deleteA:hover{
background-color: rgba(206, 144, 64, 0.8);
}
修改 DetailsServlet
package View;
import Dao.BlogDao;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/delete")
public class DeleteServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
String str = req.getParameter("blogId");
int blogId = Integer.parseInt(str);
BlogDao blogDao = new BlogDao();
blogDao.delete(blogId);
resp.sendRedirect("index.html");
}
}
package common;
import Dao.User;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
public class Util {
public static User checkLoginStatus (HttpServletRequest req){
// 判断是否登录了. 如果能够拿到 Session, 并且拿到 Session 里的 user对象,就认为是登录状态
HttpSession session = req.getSession(false);
if(session == null){
// 没有登录的情况
return null;
}
User user = (User) session.getAttribute("user");
return user;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="css/moreList.css">
<link rel="stylesheet" href="css/common.css">
<!-- 引入 editor.md 的依赖 -->
<link rel="stylesheet" href="editor.md/css/editormd.min.css" />
<script src="js/jquery.min.js"></script>
<script src="editor.md/lib/marked.min.js"></script>
<script src="editor.md/lib/prettify.min.js"></script>
<script src="editor.md/editormd.js"></script>
</head>
<body>
<div class="nav">
<img src="image/2.png" alt="头像">
<span class="title">我的博客系统</span>
<a href="index.html">主页</a>
<a href="personlist.html">我的</a>
<a href="edit.html">创作</a>
<a href="logout">注销</a>
</div>
<div class="parent">
<div class="left">
<div class="card">
<img src="image/头像.jpg">
<span class="name" th:text="${user.username}">蜡笔小新</span>
<a href="#">github 地址</a>
<div class='one'>
<span>文章</span>
<span>分类</span>
</div>
<div class='one'>
<span>2</span>
<span>1</span>
</div>
</div>
</div>
<div class="right">
<div class="article">
<h2 class="title" th:text="${blog.title}">我的第一篇博客</h2>
<span class="date" th:text="${blog.postTime}">2022-4-17</span>
<a th:href="${'delete?blogId=' + blog.blogId}" id="deleteA" th:if="${showDelete}">删除文章</a>
<div class="desc" id="content" th:text="${blog.content}" style="background-color: transparent;"></div>
</div>
</div>
</div>
<script>
function renderMD() {
let contentDiv = document.querySelector('#content');
let markdown = contentDiv.innerHTML;
// 1把contentDiv清空
contentDiv.innerHTML = '';
editormd.markdownToHTML('content',{
markdown: markdown
});
}
renderMD();
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="css/list.css">
<link rel="stylesheet" href="css/common.css">
</head>
<body>
<div class="nav">
<img src="image/2.png" alt="头像">
<span class="title">我的博客系统</span>
<a href="index.html">主页</a>
<a href="personlist.html">个人主页</a>
<a href="edit.html">创作</a>
<a href="logout">注销</a>
</div>
<div class="parent">
<div class="left">
<div class="card">
<img src="image/头像.jpg">
<span class="name" th:text="${user.username}">蜡笔小新</span>
<a href="#">github 地址</a>
<div class='one'>
<span>文章</span>
<span>分类</span>
</div>
<div class='one'>
<span>2</span>
<span>1</span>
</div>
</div>
</div>
<div class="right">
<div class="article" th:each="blog : ${blogs}">
<h2 class="title" th:text="${blog.title}">我的第一篇博客</h2>
<span class="date" th:text="${blog.postTime}">2022-4-17</span>
<div class="desc" th:text="${blog.content}">.</div>
<a th:href="${'details.html?blogId=' + blog.blogId}" class="more">查看全文>></a>
</div>
</div>
</div>
</body>
</html>
package View;
import Dao.Blog;
import Dao.BlogDao;
import Dao.User;
import Dao.UserDao;
import common.Util;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@WebServlet("/personlist.html")
public class PersonServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
User user = Util.checkLoginStatus(req);
if(user == null){
resp.sendRedirect("login.html");
return;
}
BlogDao blogDao = new BlogDao();
List<Blog> blogs = blogDao.selectAllPerson(user.getUserId());
TemplateEngine engine = (TemplateEngine) getServletContext().getAttribute("engine");
WebContext webContext = new WebContext(req,resp,getServletContext());
webContext.setVariable("blogs",blogs);
engine.process("personlist",webContext,resp.getWriter());
}
}
public void update(Blog blog){
Connection connection = null;
PreparedStatement statement = null;
try {
// 1. 建立连接
connection = DBUtil.getConnection();
// 2. 拼装 SQL 语句
String sql = "update blog set content = ? ,title = ?,postTime = ? where blogId = ?";
statement = connection.prepareStatement(sql);
statement.setString(1,blog.getContent());
statement.setString(2,blog.getTitle());
statement.setTimestamp(3,blog.getPostTime());
statement.setInt(4,blog.getBlogId());
// 3. 执行 SQL 语句
int ret = statement.executeUpdate();
if(ret == 1){
System.out.println("编辑成功");
}else{
System.out.println("编辑失败");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtil.close(connection,statement,null);
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="css/common.css">
<link rel="stylesheet" href="css/edit.css">
<!-- 引入 editor.md 的依赖 -->
<link rel="stylesheet" href="editor.md/css/editormd.min.css" />
<script src="js/jquery.min.js"></script>
<script src="editor.md/lib/marked.min.js"></script>
<script src="editor.md/lib/prettify.min.js"></script>
<script src="editor.md/editormd.js"></script>
</head>
<body>
<div class="nav">
<img src="image/2.png" alt="头像">
<span class="title">我的博客系统</span>
<a href="index.html">主页</a>
<a href="personlist.html">我的</a>
<a href="edit.html">创作</a>
<a href="logout">注销</a>
</div>
<div class="leader">
<form th:action="${'update?blogId=' + blog.blogId}" method="post" style="height:100%">
<div class="empOne">
<input type="text" class="title" th:value="${blog.title}" name="title">
<input type="submit" value="发布文章" class="publish">
</div>
<div id="editor">
<textarea name="content" style="display:none;" th:text="${blog.content}"></textarea>
</div>
</form>
</div>
<script>
// 初始化编辑器
var editor = editormd("editor", {
// 这里的尺寸必须在这里设置. 设置样式会被 editormd 自动覆盖掉.
width: "100%",
// 高度 100% 意思是和父元素一样高. 要在父元素的基础上去掉标题编辑区的高度
height: "calc(100% - 75px)",
// 指定 editor.md 依赖的插件路径
path: "editor.md/lib/",
saveHTMLToTextarea: true
});
</script>
</body>
</html>
这里的 doget 请求是进入编辑页
dopost请求是提交编辑后的内容
package View;
import Dao.Blog;
import Dao.BlogDao;
import Dao.User;
import common.Util;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;
@WebServlet("/update")
public class UpdateServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
String str = req.getParameter("blogId");
if(str==null || "".equals(str)){
resp.getWriter().write("<h3>博客Id不存在</h3>");
return;
}
int blogId = Integer.parseInt(str);
BlogDao blogDao = new BlogDao();
Blog blog = blogDao.selectOne(blogId);
if(blog == null){
resp.getWriter().write("<h3>博文不存在</h3>");
return;
}
TemplateEngine engine = (TemplateEngine) getServletContext().getAttribute("engine");
WebContext webContext = new WebContext(req,resp,getServletContext());
webContext.setVariable("blog",blog);
engine.process("alter",webContext,resp.getWriter());
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
req.setCharacterEncoding("utf-8");
User user = Util.checkLoginStatus(req);
if(user == null){
resp.sendRedirect("login.html");
return;
}
// 1. 获取参数
String title = req.getParameter("title");
String content = req.getParameter("content");
String str = req.getParameter("blogId");
if(str==null || "".equals(str)){
System.out.println("blogId不存在");
return;
}
int blogId = Integer.parseInt(str);
// 2. 判断是否存在
if(title==null || "".equals(title) || content==null || "".equals(content)){
resp.getWriter().write("<h3>文章标题或者内容不存在</h3>");
return;
}
// 插入到数据库中
Blog blog = new Blog();
blog.setContent(content);
blog.setTitle(title);
blog.setPostTime(new Timestamp(System.currentTimeMillis()));
blog.setBlogId(blogId);
BlogDao blogDao = new BlogDao();
blogDao.update(blog);
// 重定向
resp.sendRedirect("personlist.html");
}
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://wangzhi430.blog.csdn.net/article/details/124669731
内容来源于网络,如有侵权,请联系作者删除!