JavaWeb项目【实现基础博客系统】

1.项目简介:

实现一个简易的博客系统,基本功能包含注册、登录、发表文章、显示文章列表、显示文章详情、删除文章。

2.项目技术:

前端:HTML+CSS+JavaScript
后端:Servlet 的使用
数据库:mysql
项目管理:Maven
项目部署:tomcat
模板引擎:Thymeleaf

3.项目搭建:

  1. 创建项目:创建maven项目,添加文件夹webapp/WEB-INF/web.xml。
  2. 引入依赖:在pom.xml中引入servlet、mysql 依赖。

4.项目内容:

1. 数据库设计:

有需求知,需要两张表 user、blog

create database if not exists newblog;
use newblog;

drop table if exists blog;
create table blog(
    blogId int primary key auto_increment,
    title varchar(512),
    content text,
    userId int,
    postTime datetime
);

drop table if exists user;
create table user(
    userId int primary key auto_increment,
    username varchar(50),
    password varchar(50)
);

2. 封装数据库操作

JDBC操作数据库的代码进行简单封装。
1)DBUtil 和数据库建立连接 / 收尾工作。

public class DBUtil {
    private static final String URL = "jdbc:mysql://127.0.0.1:3306/数据库名称?characterEncoding=utf8&useSSL=false";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "数据库密码";
    private static javax.sql.DataSource dataSource = null;
    public static DataSource getDataSource(){
        // 看一下 dataSource 当前是否已经持有一个实例了。
        // 如果没有持有,就创建 一个新的,
        // 如果持有了,就不必创建新的,直接返回之前的。
        if (dataSource == null){
           MysqlDataSource mysqlDataSource = new MysqlDataSource();
            mysqlDataSource.setUrl(URL);
            mysqlDataSource.setUser(USERNAME);
            mysqlDataSource.setPassword(PASSWORD);
            dataSource =  mysqlDataSource;
        }
        return dataSource;
    }
    public static Connection getConnection(){
        try {
            return getDataSource().getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;    // 返回null,说明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();
            }
        }
    }
}

2)创建实体类
Blog 、User
3)实现BlogDao类、UserDao类
针对博客和用户进行增删改查操作。

3. 实现各功能页面

1)使用模板实现页面
使用模板来代替原始的字符串拼接。
模板也是一个 html 文件,这个文件里面有一些关键信息是不全的,根据服务器这边的数据,来动态的把 html 文件缺失的部分给补全,形成完整的 html,再把完整的html 返回给浏览器。
Thymeleaf 库(模板引擎)来完成模板的渲染工作。
》先通过 maven引入依赖。

 <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf</artifactId>
            <version>3.0.12.RELEASE</version>
        </dependency>

》编写模板文件
博客页中的标题、时间、正文是从数据库来的,通过Servlet 代码生成的。这些都算是关键信息,需要使用Thymeleaf 提供的特殊符号对这些关键信息进行占位
借助Thymeleaf 库,把数据库中获取到的标题、正文等信息,替换到占位符这里。
占位符:如下
${ } 、th:each 、 th:text

博客列表页:

<body>
   <div class="nav">   <!-- 导航栏 -->
       <!--  如果是用户未登录,就显示未登录,并且显示 登录/注册 按钮-->
       <!-- 如果是用户已登录,就显示 欢迎xx -->
       <h3 class="nav-title">我的博客系统</h3>
       <div class="spacer"></div> <!-- 空白符 -->
       <a href="login.html" class="nav-button" th:if="${!isLogin}">登录</a>   <!-- th:if 满足条件就显示 -->
       <a href="register.html" class="nav-button" th:if="${!isLogin}">注册</a>
       <div th:if="${isLogin}" th:text="${'欢迎' + user.username}"></div>
       <a href="blog_insert.html" class="nav-button" th:if="${isLogin}">写博客</a>
       <a href="logout" class="nav-button" th:if="${isLogin}">注销</a>
   </div>
    <!--  .container 存放了所有博客  -->
    <div class="container">
        <!--  .blog 对应到一篇博客 -->
        <div class="blog" th:each="blog : ${blogs}">    <!-- each表示循环 -->
            <a th:href="${'blogContent?blogId=' + blog.blogId}" class="title" th:text="${blog.title}">我是标题</a>      <!-- <a href="#" 使用# 表示点击之后没效果 -->
            <div class="post-time" th:text="${blog.postTime}">2021-07-13 11:01:00</div>
            <div class="desc" th:text="${blog.content}">我是正文的摘要...</div>
        </div>
    </div>
</body>

博客详情页:

<body>
    <div class="nav">   <!-- 导航栏 -->
    <!--  如果是用户未登录,就显示未登录,并且显示 登录/注册 按钮-->
    <!-- 如果是用户已登录,就显示 欢迎xx -->
        <h3 class="nav-title">我的博客系统</h3>
        <div class="spacer"></div> <!-- 空白符 -->
        <a  class="nav-button" th:href="${'blogDelete?blogId=' + blog.blogId}">删除</a>
     </div>
     <!-- 作为整个博客的容器 -->
     <div class="container">                                      <!-- 给模板里传的可以是 整数 字符串 对象-->
         <h3 th:text="${blog.title}" class="title">这是博客标题</h3>
         <div class="author" th:text="${user.username}">多多</div>          <!-- th:text="${username}  user是对象,也可以写username 字符串 -->
         <div class="post-time" th:text="${blog.postTime}">2021-07-30 16:00:00</div>
         <div class="content" th:text="${blog.content}">
             这里是博客正文,欢迎浏览博客内容
         </div>
     </div>
</body>

》进行具体渲染


@WebListener
public class ThymeleafConfig implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        // 使用这个  表示 初始化完了
        // 这个方法就会在当前 webapp 的 ServletContext 初始化之后立即执行,
        // Thymeleaf 的初始化就在这里调用即可

        // 初始化 Thymeleaf
        // 1)创建一个 engine (引擎),负责把Java 中的数据替换到模板中
       TemplateEngine engine = new TemplateEngine();
        // 2) 创建一个 resolver 对象(解析器),负责找到 html 模板在哪里
        // 供 engine 对象使用
        ServletContextTemplateResolver resolver = new ServletContextTemplateResolver(sce.getServletContext());
        // 3) 给 resolver 设置一些属性,让他能够找到 html 模板
        resolver.setCharacterEncoding("utf-8");
        // Prefix 表示"前缀",设定了满足啥样条件的文件被加载到内存中作为 html 模板
        resolver.setPrefix("/WEB-INF/template/");  // resolver 对象寻找模板页面 进行拼接
        // Suffix 表示 "后缀"
        resolver.setSuffix(".html");
        // 4) 把 resolver 和 engine 关联起来
        engine.setTemplateResolver(resolver);

        // 把初始化好的 engine 对象交给 ServletContext 来保管
        ServletContext context = sce.getServletContext();
        context.setAttribute("engine",engine);
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        // 表示 context对象销毁完了
    }
}

2)登录页面
Servlet 需要从请求中读取到用户名和密码,根据用户名在数据库中查找。
登录成功后,创建一个 session,把当前登录成功的用户信息保存到 session中。

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 从 req 中读取用户提交的 username 和 password
       String username =  req.getParameter("username");
       String password = req.getParameter("password");
       if (username == null || "".equals(username)
               || password == null || "".equals(password)){
           resp.sendError(404,"用户名或密码不能为空");
           return;
       }
       // 2. 从数据库中查找指定用户名的用户信息
       UserDao userDao = new UserDao();
       User user = userDao.selectByName(username);
       if (user == null){
           resp.sendError(404,"用户名或者密码错误");
           return;
       }
       if (!password.equals(user.getPassword())){
           // 密码不匹配
           resp.sendError(404,"用户名或者密码错误");
           return;
       }
       // 3. 登录成功! 创建会话
        HttpSession session = req.getSession(true);  // 不存在就创建, 存在就返回,  默认是不存在的情况
        session.setAttribute("user",user);  // 插入刚才的 user 对象 ,把user对象 放到 session中
        // 4. 直接把 用户页面 重定向 到博客列表页
        resp.sendRedirect("blogList");
    }
}

3)注册页面
与登录功能类似,除了 根据用户名在数据库中查找,若用户名不存在,则将该数据插入。

 //  构造 dao.User 对象,插入到数据库中
        User newUser = new User();
        newUser.setUsername(username);
        newUser.setPassword(password);
        userDao.insert(newUser);

4)博客编辑页面
Servlet 来处理服务器发送的 Post 请求,把读取的数据插入数据库中。

<body>
    <form action="blogInsert" method="POST">
        <!-- 用 input 表示文章的标题 -->
        <input type="text" name="title" class="title">
        <!-- 用这个输入框表示正文 -->
        <textarea name="content" rows="30" ></textarea>    
        <input type="submit" value="发布博客" class="button">
    </form>
</body>

处理请求前要先判断用户是否已经登录。未登录则不能插入。
5)删除功能
注意只能删除自己的文章。

4.项目文件夹

在这里插入图片描述
api 包:当前服务器和页面之间前后交互的接口。Servlet
config : 配置类, ThymeleafConfig
dao 包:跟数据库相关的类。
webapp:存放前端页面。
在这里插入图片描述

5. 实现效果

博客列表页
在这里插入图片描述

博客详情页
在这里插入图片描述
注册页面
在这里插入图片描述

登录页面
在这里插入图片描述
登录后进入自己的列表页
在这里插入图片描述
博客编辑页面
在这里插入图片描述

简易博客系统在线链接:
http://106.54.183.128:8080/newblog/blogList

  • 3
    点赞
  • 41
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值